diff --git a/package.json b/package.json index 6f64e2a..675e252 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ }, "scripts": { "dev": "npx nodemon --ignore playground/generator-output/ --exec ts-node -- src/cli/main generate --config ./playground/sanity-generator.config.ts", - "dev:test": "npx nodemon --ignore test/generator-output/ --exec ts-node -- src/cli/main generate --config ./test/ressources/generator-config.ts", + "dev:test": "npx nodemon --ignore test/generator-output/ --exec ts-node -- src/cli/main generate --config ./test/ressources/generator-config-external-resolver-and-trim.ts", "dev:sanity": "yarn dev & cd playground && yarn dev", "preview": "npx ts-node src/cli/main generate --config ./client/sanity-generator.config.ts --watch ", "build": "rimraf ./build && tsc && cp -r src/static build/static", diff --git a/playground/generator-output/queries/get-page-by-slug.ts b/playground/generator-output/queries/get-page-by-slug.ts index 557efa2..37d9346 100644 --- a/playground/generator-output/queries/get-page-by-slug.ts +++ b/playground/generator-output/queries/get-page-by-slug.ts @@ -1,5 +1,10 @@ -import { inlineResolver0, localeString, inlineResolver1 } from "../resolver"; +import { + inlineResolver0, + inlineResolver1, + localeString, + inlineResolver2, +} from "../resolver"; // prettier-ignore export const getPageBySlug = /* groq */` -*[_type == "page" && slug.current == $slug] { ..., ${inlineResolver0("seoTitle")}, gallery { ..., ${localeString("sectionTitle")}, slides[] { ..., slide { ..., ${inlineResolver1("title")} } } }, sections[] { ..., gallerySection { ..., ${localeString("sectionTitle")}, slides[] { ..., slide { ..., ${localeString("title")} } } }, textSection { ..., ${localeString("title")} }, featuresSection { ..., ${localeString("title")}, ${localeString("subtitle")} } } }[0] ` +*[_type == "page" && slug.current == $slug] { ..., ${inlineResolver0("seoTitle")}, ${inlineResolver1("pageHeader")}, gallery { ..., ${localeString("sectionTitle")}, slides[] { ..., slide { ..., ${inlineResolver2("title")} } } }, sections[] { ..., gallerySection { ..., ${localeString("sectionTitle")}, slides[] { ..., slide { ..., ${localeString("title")} } } }, textSection { ..., ${localeString("title")} }, featuresSection { ..., ${localeString("title")}, ${localeString("subtitle")} } } }[0] ` diff --git a/playground/generator-output/queries/get-pages.ts b/playground/generator-output/queries/get-pages.ts index 63f2b33..e14dd05 100644 --- a/playground/generator-output/queries/get-pages.ts +++ b/playground/generator-output/queries/get-pages.ts @@ -1,5 +1,10 @@ -import { inlineResolver0, localeString, inlineResolver1 } from "../resolver"; +import { + inlineResolver0, + inlineResolver1, + localeString, + inlineResolver2, +} from "../resolver"; // prettier-ignore export const getPages = /* groq */` -*[_type == "page"] { ..., ${inlineResolver0("seoTitle")}, gallery { ..., ${localeString("sectionTitle")}, slides[] { ..., slide { ..., ${inlineResolver1("title")} } } }, sections[] { ..., gallerySection { ..., ${localeString("sectionTitle")}, slides[] { ..., slide { ..., ${localeString("title")} } } }, textSection { ..., ${localeString("title")} }, featuresSection { ..., ${localeString("title")}, ${localeString("subtitle")} } } }[0] ` +*[_type == "page"] { ..., ${inlineResolver0("seoTitle")}, ${inlineResolver1("pageHeader")}, gallery { ..., ${localeString("sectionTitle")}, slides[] { ..., slide { ..., ${inlineResolver2("title")} } } }, sections[] { ..., gallerySection { ..., ${localeString("sectionTitle")}, slides[] { ..., slide { ..., ${localeString("title")} } } }, textSection { ..., ${localeString("title")} }, featuresSection { ..., ${localeString("title")}, ${localeString("subtitle")} } } }[0] ` diff --git a/playground/generator-output/resolver/index.ts b/playground/generator-output/resolver/index.ts index 3dc2a29..dfd2ffb 100644 --- a/playground/generator-output/resolver/index.ts +++ b/playground/generator-output/resolver/index.ts @@ -1,3 +1,4 @@ export * from "./inline-resolver0"; export * from "./inline-resolver1"; +export * from "./inline-resolver2"; export * from "./locale-string"; diff --git a/playground/generator-output/resolver/inline-resolver1.ts b/playground/generator-output/resolver/inline-resolver1.ts index 76ab50c..c6137cb 100644 --- a/playground/generator-output/resolver/inline-resolver1.ts +++ b/playground/generator-output/resolver/inline-resolver1.ts @@ -1,4 +1,4 @@ import { type Resolver } from "sanity-generator/types"; // prettier-ignore -export const inlineResolver1: Resolver = (name) => ( /* groq */ `"${name}": {"super": "cool"}` ) +export const inlineResolver1: Resolver = (name2) => ( /* groq */ ` "${name2}-wrapped": { "title": ${name2}.title, "subtitle": ${name2}.subtitle } ` ) diff --git a/playground/generator-output/resolver/inline-resolver2.ts b/playground/generator-output/resolver/inline-resolver2.ts new file mode 100644 index 0000000..83b7d33 --- /dev/null +++ b/playground/generator-output/resolver/inline-resolver2.ts @@ -0,0 +1,4 @@ +import { type Resolver } from "sanity-generator/types"; + +// prettier-ignore +export const inlineResolver2: Resolver = (name) => ( /* groq */ `"${name}": {"super": "cool"}` ) diff --git a/playground/schemas/documents/page.ts b/playground/schemas/documents/page.ts index aae3def..02bbc64 100644 --- a/playground/schemas/documents/page.ts +++ b/playground/schemas/documents/page.ts @@ -1,9 +1,6 @@ -import { GeneratorSchemaDefinition} from './../../../src/types/index' import {defineArrayMember, defineField, defineType} from 'sanity' - -declare module 'sanity' { - interface BaseSchemaDefinition extends GeneratorSchemaDefinition {} -} +import {header} from '../factories' +import {title} from 'process' type Page = any export const pageSchema: Page = defineType({ @@ -24,29 +21,27 @@ export const pageSchema: Page = defineType({ defineField({ type: 'localeString', title: 'Title (Open Graph)', - group: 'seo', name: 'seoTitle', description: 'Used for Open Graph previews implemented by facebook, twitter, google etc.', generator: { - resolver: (name) => /* groq */` + resolver: (name) => /* groq */ ` "${name}": { "germanTitle": ${name}.de, "englishTitle": ${name}.en } - ` + `, }, }), + header('pageHeader', 'content'), defineField({ type: 'object', name: 'gallery', - - + group: 'content', fields: [ defineField({ type: 'localeString', name: 'sectionTitle', - }), defineField({ type: 'array', @@ -56,14 +51,30 @@ export const pageSchema: Page = defineType({ type: 'object', name: 'slide', fields: [ + defineField({ + name: 'image', + type: 'image', + }), { type: 'string', name: 'title', generator: { - resolver: (name) => /* groq */`"${name}": {"super": "cool"}`, + resolver: (name) => /* groq */ `"${name}": {"super": "cool"}`, }, }, ], + preview: { + select: { + title: 'title', + image: "image" + }, + prepare(props) { + return { + title: props.title, + media: props.image + } + }, + }, }), ], }), diff --git a/playground/schemas/factories/header.ts b/playground/schemas/factories/header.ts new file mode 100644 index 0000000..fdbc1db --- /dev/null +++ b/playground/schemas/factories/header.ts @@ -0,0 +1,20 @@ +import {defineField} from 'sanity' + +export const header = (name: string, group = "") => + defineField({ + type: 'object', + name, + group, + fields: [ + {name: 'title', type: 'string'}, + {name: 'subtitle', type: 'string'}, + ], + generator: { + resolver: (name: string) => /* groq */ ` + "${name}-wrapped": { + "title": ${name}.title, + "subtitle": ${name}.subtitle + } + `, + }, + }) diff --git a/playground/schemas/factories/index.ts b/playground/schemas/factories/index.ts new file mode 100644 index 0000000..c73f6da --- /dev/null +++ b/playground/schemas/factories/index.ts @@ -0,0 +1 @@ +export * from './header' diff --git a/playground/tsconfig.json b/playground/tsconfig.json index a2e968e..cb0ba75 100644 --- a/playground/tsconfig.json +++ b/playground/tsconfig.json @@ -14,6 +14,7 @@ "isolatedModules": true, "jsx": "preserve", "incremental": true, + "rootDir": ".", "paths": { "sanity-generator/*": ["../src/*"] } diff --git a/playground/types/global.d.ts b/playground/types/global.d.ts new file mode 100644 index 0000000..37b7d17 --- /dev/null +++ b/playground/types/global.d.ts @@ -0,0 +1,6 @@ +import {GeneratorSchemaDefinition} from 'sanity-generator/types' +export {} + +declare module 'sanity' { + interface FieldDefinitionBase extends GeneratorSchemaDefinition {} +} diff --git a/test/generator-output/resolver/index.ts b/test/generator-output/resolver/index.ts new file mode 100644 index 0000000..12c5644 --- /dev/null +++ b/test/generator-output/resolver/index.ts @@ -0,0 +1,4 @@ +export * from "./inline-resolver0"; +export * from "./inline-resolver1"; +export * from "./locale-string"; +export * from "./special-number"; diff --git a/test/generator-output/resolver/locale-string.ts b/test/generator-output/resolver/locale-string.ts index e69de29..526fb40 100644 --- a/test/generator-output/resolver/locale-string.ts +++ b/test/generator-output/resolver/locale-string.ts @@ -0,0 +1,4 @@ +import { type Resolver } from "sanity-generator/types"; + +// prettier-ignore +export const localeString: Resolver = (name) => ( /* groq */ ` "${name}": coalesce(${name}[$lang], ${name}.en) ` ) diff --git a/test/generator-output/resolver/special-number.ts b/test/generator-output/resolver/special-number.ts new file mode 100644 index 0000000..bc15853 --- /dev/null +++ b/test/generator-output/resolver/special-number.ts @@ -0,0 +1,4 @@ +import { type Resolver } from "sanity-generator/types"; + +// prettier-ignore +export const specialNumber: Resolver = (name) => ( /* groq */ ` "${name}-special-number": ${name} ` ) diff --git a/tsconfig.json b/tsconfig.json index 061221a..33e4be2 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,110 +1,25 @@ { "compilerOptions": { - /* Visit https://aka.ms/tsconfig to read more about this file */ - - /* Projects */ - // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - "lib": ["es6"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ - // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ - - /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ - "rootDir": "src", /* Specify the root folder within your source files. */ - // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ - "types": ["node"], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ - // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ - // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ - // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ - // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ - "resolveJsonModule": true, /* Enable importing .json files. */ - // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ - // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ - - /* Emit */ - "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ - "outDir": "build", /* Specify an output folder for all emitted files. */ - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ - - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ - - /* Type Checking */ - "strict": false, /* Enable all strict type-checking options. */ - "noImplicitAny": false, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ - // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ + "target": "es2016", + "lib": ["es6"], + "module": "commonjs", + "rootDir": "src", + "types": ["node"], + "resolveJsonModule": true, + "allowJs": true, + "declaration": true, + "outDir": "build", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + + "strict": false, + "noImplicitAny": false, + + "skipLibCheck": true, + "baseUrl": ".", + "paths": { + "sanity-generator/*": ["src/*"] + } }, "exclude": ["playground", "build", "src/static"], "include": ["src"]