@sanity/codegen 8.0.0 → 8.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/dist/_exports/index.d.ts +23 -19
- package/dist/readConfig.js +15 -15
- package/dist/readConfig.js.map +1 -1
- package/dist/typescript/expressionResolvers.js +1 -1
- package/dist/typescript/expressionResolvers.js.map +1 -1
- package/dist/typescript/findQueriesInPath.js +1 -1
- package/dist/typescript/findQueriesInPath.js.map +1 -1
- package/dist/typescript/helpers.js +15 -0
- package/dist/typescript/helpers.js.map +1 -1
- package/dist/typescript/moduleResolver.js +1 -1
- package/dist/typescript/moduleResolver.js.map +1 -1
- package/dist/typescript/typeGenerator.js +18 -7
- package/dist/typescript/typeGenerator.js.map +1 -1
- package/dist/utils/debug.js +1 -1
- package/dist/utils/debug.js.map +1 -1
- package/package.json +11 -8
package/README.md
CHANGED
|
@@ -1,3 +1,29 @@
|
|
|
1
1
|
# @sanity/codegen
|
|
2
2
|
|
|
3
3
|
Codegen toolkit for Sanity.io, used to generate Typescript types for a Sanity Schema & GROQ queries.
|
|
4
|
+
|
|
5
|
+
## Typed `client.fetch` results
|
|
6
|
+
|
|
7
|
+
With `overloadClientMethods` enabled (the default), the generated file ends with a query type map that registers every query it found, so `client.fetch(query)` in `@sanity/client`, and `sanityFetch({query})` in `next-sanity`, return the generated result type without a generic:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
// Query TypeMap
|
|
11
|
+
declare global {
|
|
12
|
+
interface SanityQueries {
|
|
13
|
+
'*[_type == "post"]': PostsQueryResult
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
// Lets @sanity/client releases that predate the global registry read it too
|
|
17
|
+
declare module '@sanity/client' {
|
|
18
|
+
interface SanityQueries extends globalThis.SanityQueries {}
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The two blocks serve different `@sanity/client` releases, and the same generated file works with all of them:
|
|
23
|
+
|
|
24
|
+
- The `declare global` block is the registry. `@sanity/client` releases that know about it read it directly, and because it is a global interface rather than a module augmentation, it does not depend on module resolution: it is seen whether or not `@sanity/client` is a direct dependency of the project that holds the generated file, however many copies of the client are installed (a copy nested inside `next-sanity` reads the same registry), and from every entry point, `@sanity/client/stega` included.
|
|
25
|
+
- The `declare module '@sanity/client'` block is a bridge for releases that only read the `SanityQueries` interface exported from `@sanity/client`, which is every release since 6.21.0. Interface merging unions the `extends` clauses of an interface's declarations, so the bridge makes that interface inherit the global registry. On releases that already inherit it, the bridge is a duplicate `extends` of the same type, which TypeScript accepts.
|
|
26
|
+
|
|
27
|
+
The bridge is the only line that resolves `@sanity/client`. When the client cannot be resolved from the generated file, TypeScript reports `TS2664: Invalid module name in augmentation` for it in a `.ts` file, while in a declaration file an augmentation whose module cannot be found is skipped silently. Pointing `generates` at a `.d.ts` path therefore keeps the file valid in such a layout, and the global registry still types the client that is installed.
|
|
28
|
+
|
|
29
|
+
The earlier output, a `declare module '@sanity/client'` block that carried the whole map, keeps working with every `@sanity/client` release that accepts the new one.
|
package/dist/_exports/index.d.ts
CHANGED
|
@@ -4,9 +4,9 @@ import {FSWatcher} from 'chokidar'
|
|
|
4
4
|
import {SchemaType} from 'groq-js'
|
|
5
5
|
import * as t from '@babel/types'
|
|
6
6
|
import {TransformOptions} from '@babel/core'
|
|
7
|
+
import * as v from 'valibot'
|
|
7
8
|
import {WorkerChannel} from '@sanity/worker-channels'
|
|
8
9
|
import {WorkerChannelReporter} from '@sanity/worker-channels'
|
|
9
|
-
import * as z from 'zod/mini'
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* @deprecated use TypeGenConfig
|
|
@@ -17,27 +17,31 @@ export declare type CodegenConfig = TypeGenConfig
|
|
|
17
17
|
/**
|
|
18
18
|
* @public
|
|
19
19
|
*/
|
|
20
|
-
export declare const configDefinition:
|
|
20
|
+
export declare const configDefinition: v.ObjectSchema<
|
|
21
21
|
{
|
|
22
|
-
formatGeneratedCode:
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
prettier: 'prettier'
|
|
29
|
-
}>,
|
|
30
|
-
]
|
|
31
|
-
>
|
|
22
|
+
readonly formatGeneratedCode: v.OptionalSchema<
|
|
23
|
+
v.UnionSchema<
|
|
24
|
+
[v.BooleanSchema<undefined>, v.PicklistSchema<['oxfmt', 'prettier'], undefined>],
|
|
25
|
+
undefined
|
|
26
|
+
>,
|
|
27
|
+
true
|
|
32
28
|
>
|
|
33
|
-
generates:
|
|
34
|
-
overloadClientMethods:
|
|
35
|
-
path:
|
|
36
|
-
|
|
29
|
+
readonly generates: v.OptionalSchema<v.StringSchema<undefined>, './sanity.types.ts'>
|
|
30
|
+
readonly overloadClientMethods: v.OptionalSchema<v.BooleanSchema<undefined>, true>
|
|
31
|
+
readonly path: v.OptionalSchema<
|
|
32
|
+
v.UnionSchema<
|
|
33
|
+
[v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>],
|
|
34
|
+
undefined
|
|
35
|
+
>,
|
|
36
|
+
readonly [
|
|
37
|
+
'./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
38
|
+
'./app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
39
|
+
'./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',
|
|
40
|
+
]
|
|
37
41
|
>
|
|
38
|
-
schema:
|
|
42
|
+
readonly schema: v.OptionalSchema<v.StringSchema<undefined>, './schema.json'>
|
|
39
43
|
},
|
|
40
|
-
|
|
44
|
+
undefined
|
|
41
45
|
>
|
|
42
46
|
|
|
43
47
|
/**
|
|
@@ -440,7 +444,7 @@ declare interface TypeEvaluationStats {
|
|
|
440
444
|
}
|
|
441
445
|
|
|
442
446
|
/** @public */
|
|
443
|
-
export declare type TypeGenConfig =
|
|
447
|
+
export declare type TypeGenConfig = v.InferOutput<typeof configDefinition>
|
|
444
448
|
|
|
445
449
|
/**
|
|
446
450
|
* A class used to generate TypeScript types from a given schema
|
package/dist/readConfig.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import json5 from 'json5';
|
|
3
|
-
import * as
|
|
3
|
+
import * as v from 'valibot';
|
|
4
4
|
/**
|
|
5
5
|
* @public
|
|
6
|
-
*/ export const configDefinition =
|
|
7
|
-
formatGeneratedCode:
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
*/ export const configDefinition = v.object({
|
|
7
|
+
formatGeneratedCode: v.optional(v.union([
|
|
8
|
+
v.boolean(),
|
|
9
|
+
v.picklist([
|
|
10
10
|
'oxfmt',
|
|
11
11
|
'prettier'
|
|
12
12
|
])
|
|
13
13
|
]), true),
|
|
14
|
-
generates:
|
|
15
|
-
overloadClientMethods:
|
|
16
|
-
path:
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
generates: v.optional(v.string(), './sanity.types.ts'),
|
|
15
|
+
overloadClientMethods: v.optional(v.boolean(), true),
|
|
16
|
+
path: v.optional(v.union([
|
|
17
|
+
v.string(),
|
|
18
|
+
v.array(v.string())
|
|
19
19
|
]), [
|
|
20
20
|
'./src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
21
21
|
'./app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',
|
|
22
22
|
'./sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}'
|
|
23
23
|
]),
|
|
24
|
-
schema:
|
|
24
|
+
schema: v.optional(v.string(), './schema.json')
|
|
25
25
|
});
|
|
26
26
|
/**
|
|
27
27
|
* Read, parse and process a config file
|
|
@@ -31,15 +31,15 @@ import * as z from 'zod/mini';
|
|
|
31
31
|
const content = await readFile(path, 'utf8');
|
|
32
32
|
// eslint-disable-next-line import-x/no-named-as-default-member -- json5 is CJS and doesn't support named exports
|
|
33
33
|
const json = json5.parse(content);
|
|
34
|
-
return
|
|
34
|
+
return v.parseAsync(configDefinition, json);
|
|
35
35
|
} catch (error) {
|
|
36
|
-
if (
|
|
37
|
-
throw new TypeError(`Error in config file\n ${error.issues.map((
|
|
36
|
+
if (v.isValiError(error)) {
|
|
37
|
+
throw new TypeError(`Error in config file\n ${error.issues.map((issue)=>issue.message).join('\n')}`, {
|
|
38
38
|
cause: error
|
|
39
39
|
});
|
|
40
40
|
}
|
|
41
41
|
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {
|
|
42
|
-
return
|
|
42
|
+
return v.parse(configDefinition, {});
|
|
43
43
|
}
|
|
44
44
|
throw error;
|
|
45
45
|
}
|
package/dist/readConfig.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as
|
|
1
|
+
{"version":3,"sources":["../src/readConfig.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport json5 from 'json5'\nimport * as v from 'valibot'\n\n/**\n * The formatter to use for generated code.\n * - `false` - Do not format generated code.\n * - `true` | `'prettier'` - Format with prettier.\n * - `'oxfmt'` - Format with oxfmt. Throws if oxfmt is not installed.\n * @public\n */\nexport type FormatGeneratedCode = 'oxfmt' | 'prettier' | boolean\n\n/**\n * @public\n */\nexport const configDefinition = v.object({\n formatGeneratedCode: v.optional(v.union([v.boolean(), v.picklist(['oxfmt', 'prettier'])]), true),\n generates: v.optional(v.string(), './sanity.types.ts'),\n overloadClientMethods: v.optional(v.boolean(), true),\n path: v.optional(v.union([v.string(), v.array(v.string())]), [\n './src/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './app/**/*.{ts,tsx,js,jsx,mjs,cjs,astro,vue,svelte}',\n './sanity/**/*.{ts,tsx,js,jsx,mjs,cjs}',\n ]),\n schema: v.optional(v.string(), './schema.json'),\n})\n\n/** @public */\nexport type TypeGenConfig = v.InferOutput<typeof configDefinition>\n\n/**\n * @deprecated use TypeGenConfig\n * @public\n */\nexport type CodegenConfig = TypeGenConfig\n\n/**\n * Read, parse and process a config file\n * @internal\n */\nexport async function readConfig(path: string): Promise<TypeGenConfig> {\n try {\n const content = await readFile(path, 'utf8')\n // eslint-disable-next-line import-x/no-named-as-default-member -- json5 is CJS and doesn't support named exports\n const json = json5.parse(content)\n return v.parseAsync(configDefinition, json)\n } catch (error) {\n if (v.isValiError(error)) {\n throw new TypeError(\n `Error in config file\\n ${error.issues.map((issue) => issue.message).join('\\n')}`,\n {cause: error},\n )\n }\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return v.parse(configDefinition, {})\n }\n\n throw error\n }\n}\n"],"names":["readFile","json5","v","configDefinition","object","formatGeneratedCode","optional","union","boolean","picklist","generates","string","overloadClientMethods","path","array","schema","readConfig","content","json","parse","parseAsync","error","isValiError","TypeError","issues","map","issue","message","join","cause","code"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAEzC,OAAOC,WAAW,QAAO;AACzB,YAAYC,OAAO,UAAS;AAW5B;;CAEC,GACD,OAAO,MAAMC,mBAAmBD,EAAEE,MAAM,CAAC;IACvCC,qBAAqBH,EAAEI,QAAQ,CAACJ,EAAEK,KAAK,CAAC;QAACL,EAAEM,OAAO;QAAIN,EAAEO,QAAQ,CAAC;YAAC;YAAS;SAAW;KAAE,GAAG;IAC3FC,WAAWR,EAAEI,QAAQ,CAACJ,EAAES,MAAM,IAAI;IAClCC,uBAAuBV,EAAEI,QAAQ,CAACJ,EAAEM,OAAO,IAAI;IAC/CK,MAAMX,EAAEI,QAAQ,CAACJ,EAAEK,KAAK,CAAC;QAACL,EAAES,MAAM;QAAIT,EAAEY,KAAK,CAACZ,EAAES,MAAM;KAAI,GAAG;QAC3D;QACA;QACA;KACD;IACDI,QAAQb,EAAEI,QAAQ,CAACJ,EAAES,MAAM,IAAI;AACjC,GAAE;AAWF;;;CAGC,GACD,OAAO,eAAeK,WAAWH,IAAY;IAC3C,IAAI;QACF,MAAMI,UAAU,MAAMjB,SAASa,MAAM;QACrC,iHAAiH;QACjH,MAAMK,OAAOjB,MAAMkB,KAAK,CAACF;QACzB,OAAOf,EAAEkB,UAAU,CAACjB,kBAAkBe;IACxC,EAAE,OAAOG,OAAO;QACd,IAAInB,EAAEoB,WAAW,CAACD,QAAQ;YACxB,MAAM,IAAIE,UACR,CAAC,uBAAuB,EAAEF,MAAMG,MAAM,CAACC,GAAG,CAAC,CAACC,QAAUA,MAAMC,OAAO,EAAEC,IAAI,CAAC,OAAO,EACjF;gBAACC,OAAOR;YAAK;QAEjB;QACA,IAAI,OAAOA,UAAU,YAAYA,UAAU,QAAQ,UAAUA,SAASA,MAAMS,IAAI,KAAK,UAAU;YAC7F,OAAO5B,EAAEiB,KAAK,CAAChB,kBAAkB,CAAC;QACpC;QAEA,MAAMkB;IACR;AACF"}
|
|
@@ -3,7 +3,7 @@ import path from 'node:path';
|
|
|
3
3
|
import { traverse } from '@babel/core';
|
|
4
4
|
import { Scope } from '@babel/traverse';
|
|
5
5
|
import * as babelTypes from '@babel/types';
|
|
6
|
-
import createDebug from '
|
|
6
|
+
import { createDebug } from 'obug';
|
|
7
7
|
import { formatPath } from '../utils/formatPath.js';
|
|
8
8
|
import { parseSourceFile } from './parseSource.js';
|
|
9
9
|
const debug = createDebug('sanity:codegen:findQueries:debug');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/typescript/expressionResolvers.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions, traverse} from '@babel/core'\nimport {Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\nimport createDebug from 'debug'\n\nimport {formatPath} from '../utils/formatPath.js'\nimport {parseSourceFile} from './parseSource.js'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = new Set(['groq'])\nconst FUNCTION_WRAPPER_ALLOW_LIST = new Set(['defineQuery'])\n\n/**\n * resolveExpression takes a node and returns the resolved value of the expression.\n * @beta\n * @internal\n */\nexport function resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments = [],\n node,\n params = [],\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments?: babelTypes.Node[]\n node: babelTypes.Node\n params?: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n if (\n babelTypes.isTaggedTemplateExpression(node) &&\n babelTypes.isIdentifier(node.tag) &&\n TAGGED_TEMPLATE_ALLOW_LIST.has(node.tag.name)\n ) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.quasi,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: expression,\n params,\n resolver,\n scope,\n }),\n )\n return node.quasis\n .map((quasi, idx) => {\n return (quasi.value.cooked || '') + (resolvedExpressions[idx] || '')\n })\n .join('')\n }\n\n if (babelTypes.isLiteral(node)) {\n if (node.type === 'NullLiteral' || node.type === 'RegExpLiteral') {\n throw new Error(`Unsupported literal type: ${node.type}`)\n }\n\n return node.value.toString()\n }\n\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isVariableDeclarator(node)) {\n const init = node.init ?? (babelTypes.isAssignmentPattern(node.id) && node.id.right)\n if (!init) {\n throw new Error(`Unsupported variable declarator`)\n }\n\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: init,\n resolver,\n scope,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.has(node.callee.name)\n ) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n node: node.arguments[0]!,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n })\n }\n\n if (\n babelTypes.isArrowFunctionExpression(node) ||\n babelTypes.isFunctionDeclaration(node) ||\n babelTypes.isFunctionExpression(node)\n ) {\n const newScope = new Scope(scope.path, scope)\n\n for (const [i, param] of params.entries()) {\n newScope.push({\n id: param as babelTypes.LVal,\n init: fnArguments[i] as babelTypes.Expression | undefined,\n })\n }\n\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.body,\n params: node.params,\n resolver,\n scope: newScope,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n node: node.callee,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({babelConfig, file, filename, fnArguments, node, resolver})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.right,\n params,\n resolver,\n scope,\n })\n }\n\n // Handle TypeScript type assertions (e.g., `'foo' as string`)\n if (babelTypes.isTSAsExpression(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.expression,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isMemberExpression(node)) {\n const propertyName = getMemberPropertyName(node)\n const objExpr = resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.object,\n resolver,\n scope,\n })\n const prop = findObjectProperty(objExpr, propertyName, filename, node)\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: prop.value,\n params,\n resolver,\n scope,\n })\n }\n\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveIdentifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.Identifier\n params: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n const paramIndex = params.findIndex(\n (param) =>\n (babelTypes.isIdentifier(param) && node.name === param.name) ||\n (babelTypes.isAssignmentPattern(param) &&\n babelTypes.isIdentifier(param.left) &&\n node.name === param.left.name),\n )\n let argument = fnArguments[paramIndex]\n if (!argument && paramIndex !== -1 && babelTypes.isAssignmentPattern(params[paramIndex])) {\n argument = params[paramIndex].right\n }\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: argument,\n params,\n resolver,\n scope,\n })\n }\n const binding = scope.getBinding(node.name)\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`,\n )\n }\n }\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: binding.path.node,\n params,\n resolver,\n scope,\n })\n }\n\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveCallExpression({\n babelConfig,\n file,\n filename,\n node,\n params,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.CallExpression\n params: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments: node.arguments,\n node: callee,\n params,\n resolver,\n scope,\n })\n}\n\nfunction resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.ExportSpecifier | babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}) {\n let importDeclaration: babelTypes.ImportDeclaration | undefined\n traverse(file, {\n ImportDeclaration(n) {\n if (!babelTypes.isImportDeclaration(n.node)) {\n return\n }\n for (const specifier of n.node.specifiers) {\n if (\n babelTypes.isImportDefaultSpecifier(specifier) &&\n specifier.local.loc?.identifierName === node.local.name\n ) {\n importDeclaration = n.node\n break\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration = n.node\n }\n }\n },\n })\n\n if (!importDeclaration) {\n throw new Error(`Could not find import declaration for ${node.local.name}`)\n }\n\n const importName = node.local.name\n const importFileName = importDeclaration.source.value\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(formatPath(importPath))\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let scope: Scope | undefined\n traverse(tree, {\n Program(p) {\n scope = p.scope\n },\n })\n if (!scope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = scope.getBinding(importName)\n return {binding, importFileName, importName, resolvedFile, scope, tree}\n}\n\nfunction resolveImportSpecifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.ExportSpecifier | babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n const {binding, importFileName, importName, resolvedFile, scope, tree} = resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n })\n\n if (binding) {\n return resolveExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n fnArguments,\n node: binding.path.node,\n resolver,\n scope,\n })\n }\n\n // It's not a global binding, but it might be a named export\n let namedExport: babelTypes.ExportNamedDeclaration | undefined\n let newImportName: string | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportNamedDeclaration') {\n for (const specifier of p.node.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exported.type === 'Identifier' &&\n specifier.exported.name === importName\n ) {\n namedExport = p.node\n newImportName = specifier.exported.name\n }\n }\n }\n },\n })\n\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n babelConfig,\n filename: resolvedFile,\n fnArguments,\n importName: newImportName,\n node: namedExport,\n resolver,\n })\n }\n\n let result: resolveExpressionReturnType | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportAllDeclaration') {\n try {\n result = resolveExportSpecifier({\n babelConfig,\n filename: resolvedFile,\n fnArguments,\n importName,\n node: p.node,\n resolver,\n })\n } catch (e) {\n if ((e as Error).cause !== `noBinding:${importName}`) throw e\n }\n }\n },\n })\n if (result) return result\n\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n}\n\nfunction resolveExportSpecifier({\n babelConfig,\n filename,\n fnArguments,\n importName,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n filename: string\n fnArguments: babelTypes.Node[]\n importName: string\n node: babelTypes.ExportAllDeclaration | babelTypes.ExportNamedDeclaration\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`)\n }\n\n const importFileName = node.source.value\n const importPath = path.resolve(path.dirname(filename), importFileName)\n const resolvedFile = resolver(formatPath(importPath))\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n fnArguments,\n node: binding.path.node,\n resolver,\n scope: newScope,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`, {\n cause: `noBinding:${importName}`,\n })\n}\n\nfunction getMemberPropertyName(node: babelTypes.MemberExpression): string {\n const {computed, loc, property} = node\n if (!computed && babelTypes.isIdentifier(property)) {\n return property.name\n }\n if (computed && babelTypes.isStringLiteral(property)) {\n return property.value\n }\n const locInfo = loc ? `${loc.filename}:${loc.start.line}:${loc.start.column}` : 'unknown location'\n throw new Error(`Unsupported MemberExpression property type: ${property.type} @ ${locInfo}`)\n}\n\nfunction findObjectProperty(\n objExpr: babelTypes.ObjectExpression,\n propertyName: string,\n filename: string,\n node: babelTypes.Node,\n): babelTypes.ObjectProperty {\n for (const prop of objExpr.properties) {\n if (!babelTypes.isObjectProperty(prop)) continue\n if (babelTypes.isIdentifier(prop.key) && prop.key.name === propertyName) {\n return prop\n }\n if (babelTypes.isStringLiteral(prop.key) && prop.key.value === propertyName) {\n return prop\n }\n }\n throw new Error(\n `Could not find property \"${propertyName}\" in object expression in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.Node\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): babelTypes.ObjectExpression {\n if (babelTypes.isObjectExpression(node)) {\n return node\n }\n if (babelTypes.isTSAsExpression(node)) {\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.expression,\n resolver,\n scope,\n })\n }\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n throw new Error(`Could not find binding for \"${node.name}\" in ${filename}`)\n }\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: binding.path.node,\n resolver,\n scope,\n })\n }\n if (babelTypes.isVariableDeclarator(node)) {\n if (!node.init) {\n throw new Error(`Variable declarator has no init`)\n }\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.init,\n resolver,\n scope,\n })\n }\n if (babelTypes.isMemberExpression(node)) {\n const propertyName = getMemberPropertyName(node)\n const objExpr = resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.object,\n resolver,\n scope,\n })\n const prop = findObjectProperty(objExpr, propertyName, filename, node)\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: prop.value,\n resolver,\n scope,\n })\n }\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportToObjectExpression({babelConfig, file, filename, node, resolver})\n }\n throw new Error(\n `Cannot resolve node type \"${node.type}\" to ObjectExpression in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveImportToObjectExpression({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}): babelTypes.ObjectExpression {\n const {binding, importFileName, importName, resolvedFile, scope, tree} = resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n })\n\n if (!binding) {\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n }\n\n return resolveToObjectExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n node: binding.path.node,\n resolver,\n scope,\n })\n}\n"],"names":["fs","path","traverse","Scope","babelTypes","createDebug","formatPath","parseSourceFile","debug","TAGGED_TEMPLATE_ALLOW_LIST","Set","FUNCTION_WRAPPER_ALLOW_LIST","resolveExpression","babelConfig","file","filename","fnArguments","node","params","resolver","scope","type","loc","start","line","column","isTaggedTemplateExpression","isIdentifier","tag","has","name","quasi","isTemplateLiteral","resolvedExpressions","expressions","map","expression","quasis","idx","value","cooked","join","isLiteral","Error","toString","resolveIdentifier","isVariableDeclarator","init","isAssignmentPattern","id","right","isCallExpression","callee","arguments","resolveCallExpression","isArrowFunctionExpression","isFunctionDeclaration","isFunctionExpression","newScope","i","param","entries","push","body","isNewExpression","isImportDefaultSpecifier","isImportSpecifier","resolveImportSpecifier","isTSAsExpression","isMemberExpression","propertyName","getMemberPropertyName","objExpr","resolveToObjectExpression","object","prop","findObjectProperty","paramIndex","findIndex","left","argument","binding","getBinding","isSame","resolveImportBinding","importDeclaration","ImportDeclaration","n","isImportDeclaration","specifier","specifiers","local","identifierName","importName","importFileName","source","importPath","startsWith","resolve","dirname","resolvedFile","readFileSync","tree","Program","p","namedExport","newImportName","ExportDeclaration","exported","resolveExportSpecifier","result","e","cause","computed","property","isStringLiteral","locInfo","properties","isObjectProperty","key","isObjectExpression","resolveImportToObjectExpression"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAE5B,SAA+BC,QAAQ,QAAO,cAAa;AAC3D,SAAQC,KAAK,QAAO,kBAAiB;AACrC,YAAYC,gBAAgB,eAAc;AAC1C,OAAOC,iBAAiB,QAAO;AAE/B,SAAQC,UAAU,QAAO,yBAAwB;AACjD,SAAQC,eAAe,QAAO,mBAAkB;AAEhD,MAAMC,QAAQH,YAAY;AAI1B,MAAMI,6BAA6B,IAAIC,IAAI;IAAC;CAAO;AACnD,MAAMC,8BAA8B,IAAID,IAAI;IAAC;CAAc;AAE3D;;;;CAIC,GACD,OAAO,SAASE,kBAAkB,EAChCC,WAAW,EACXC,IAAI,EACJC,QAAQ,EACRC,cAAc,EAAE,EAChBC,IAAI,EACJC,SAAS,EAAE,EACXC,QAAQ,EACRC,KAAK,EAUN;IACCZ,MACE,CAAC,eAAe,EAAES,KAAKI,IAAI,CAAC,IAAI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MAAMuD,UAAUC,0BAA0B;YACxC5D;YACAC;YACAC;YACAE,MAAMA,KAAKyD,MAAM;YACjBvD;YACAC;QACF;QACA,MAAMuD,OAAOC,mBAAmBJ,SAASF,cAAcvD,UAAUE;QACjE,OAAOwD,0BAA0B;YAC/B5D;YACAC;YACAC;YACAE,MAAM0D,KAAKpC,KAAK;YAChBpB;YACAC;QACF;IACF;IACA,IAAIhB,WAAW6D,wBAAwB,CAAChD,SAASb,WAAW8D,iBAAiB,CAACjD,OAAO;QACnF,OAAOwG,gCAAgC;YAAC5G;YAAaC;YAAMC;YAAUE;YAAME;QAAQ;IACrF;IACA,MAAM,IAAIwB,MACR,CAAC,0BAA0B,EAAE1B,KAAKI,IAAI,CAAC,yBAAyB,EAAEN,SAAS,CAAC,EAAEE,KAAKK,GAAG,EAAEC,MAAMC,KAAK,CAAC,EAAEP,KAAKK,GAAG,EAAEC,MAAME,QAAQ;AAElI;AAEA,SAASgG,gCAAgC,EACvC5G,WAAW,EACXC,IAAI,EACJC,QAAQ,EACRE,IAAI,EACJE,QAAQ,EAOT;IACC,MAAM,EAAC8D,OAAO,EAAEa,cAAc,EAAED,UAAU,EAAEO,YAAY,EAAEhF,KAAK,EAAEkF,IAAI,EAAC,GAAGlB,qBAAqB;QAC5FvE;QACAC;QACAC;QACAE;QACAE;IACF;IAEA,IAAI,CAAC8D,SAAS;QACZ,MAAM,IAAItC,MAAM,CAAC,mCAAmC,EAAEkD,WAAW,KAAK,EAAEC,gBAAgB;IAC1F;IAEA,OAAOrB,0BAA0B;QAC/B5D;QACAC,MAAMwF;QACNvF,UAAUqF;QACVnF,MAAMgE,QAAQhF,IAAI,CAACgB,IAAI;QACvBE;QACAC;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/typescript/expressionResolvers.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {type TransformOptions, traverse} from '@babel/core'\nimport {Scope} from '@babel/traverse'\nimport * as babelTypes from '@babel/types'\nimport {createDebug} from 'obug'\n\nimport {formatPath} from '../utils/formatPath.js'\nimport {parseSourceFile} from './parseSource.js'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ntype resolveExpressionReturnType = string\n\nconst TAGGED_TEMPLATE_ALLOW_LIST = new Set(['groq'])\nconst FUNCTION_WRAPPER_ALLOW_LIST = new Set(['defineQuery'])\n\n/**\n * resolveExpression takes a node and returns the resolved value of the expression.\n * @beta\n * @internal\n */\nexport function resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments = [],\n node,\n params = [],\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments?: babelTypes.Node[]\n node: babelTypes.Node\n params?: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n debug(\n `Resolving node ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n if (\n babelTypes.isTaggedTemplateExpression(node) &&\n babelTypes.isIdentifier(node.tag) &&\n TAGGED_TEMPLATE_ALLOW_LIST.has(node.tag.name)\n ) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.quasi,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isTemplateLiteral(node)) {\n const resolvedExpressions = node.expressions.map((expression) =>\n resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: expression,\n params,\n resolver,\n scope,\n }),\n )\n return node.quasis\n .map((quasi, idx) => {\n return (quasi.value.cooked || '') + (resolvedExpressions[idx] || '')\n })\n .join('')\n }\n\n if (babelTypes.isLiteral(node)) {\n if (node.type === 'NullLiteral' || node.type === 'RegExpLiteral') {\n throw new Error(`Unsupported literal type: ${node.type}`)\n }\n\n return node.value.toString()\n }\n\n if (babelTypes.isIdentifier(node)) {\n return resolveIdentifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isVariableDeclarator(node)) {\n const init = node.init ?? (babelTypes.isAssignmentPattern(node.id) && node.id.right)\n if (!init) {\n throw new Error(`Unsupported variable declarator`)\n }\n\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: init,\n resolver,\n scope,\n })\n }\n\n if (\n babelTypes.isCallExpression(node) &&\n babelTypes.isIdentifier(node.callee) &&\n FUNCTION_WRAPPER_ALLOW_LIST.has(node.callee.name)\n ) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n node: node.arguments[0]!,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isCallExpression(node)) {\n return resolveCallExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n })\n }\n\n if (\n babelTypes.isArrowFunctionExpression(node) ||\n babelTypes.isFunctionDeclaration(node) ||\n babelTypes.isFunctionExpression(node)\n ) {\n const newScope = new Scope(scope.path, scope)\n\n for (const [i, param] of params.entries()) {\n newScope.push({\n id: param as babelTypes.LVal,\n init: fnArguments[i] as babelTypes.Expression | undefined,\n })\n }\n\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.body,\n params: node.params,\n resolver,\n scope: newScope,\n })\n }\n\n if (babelTypes.isNewExpression(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n node: node.callee,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportSpecifier({babelConfig, file, filename, fnArguments, node, resolver})\n }\n\n if (babelTypes.isAssignmentPattern(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.right,\n params,\n resolver,\n scope,\n })\n }\n\n // Handle TypeScript type assertions (e.g., `'foo' as string`)\n if (babelTypes.isTSAsExpression(node)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: node.expression,\n params,\n resolver,\n scope,\n })\n }\n\n if (babelTypes.isMemberExpression(node)) {\n const propertyName = getMemberPropertyName(node)\n const objExpr = resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.object,\n resolver,\n scope,\n })\n const prop = findObjectProperty(objExpr, propertyName, filename, node)\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: prop.value,\n params,\n resolver,\n scope,\n })\n }\n\n throw new Error(\n `Unsupported expression type: ${node.type} in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveIdentifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n params,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.Identifier\n params: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n const paramIndex = params.findIndex(\n (param) =>\n (babelTypes.isIdentifier(param) && node.name === param.name) ||\n (babelTypes.isAssignmentPattern(param) &&\n babelTypes.isIdentifier(param.left) &&\n node.name === param.left.name),\n )\n let argument = fnArguments[paramIndex]\n if (!argument && paramIndex !== -1 && babelTypes.isAssignmentPattern(params[paramIndex])) {\n argument = params[paramIndex].right\n }\n if (argument && babelTypes.isLiteral(argument)) {\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: argument,\n params,\n resolver,\n scope,\n })\n }\n const binding = scope.getBinding(node.name)\n if (binding) {\n if (babelTypes.isIdentifier(binding.path.node)) {\n const isSame = binding.path.node.name === node.name\n if (isSame) {\n throw new Error(\n `Could not resolve same identifier \"${node.name}\" in \"${filename}:${node.loc?.start.line}:${node.loc?.start.column}\"`,\n )\n }\n }\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments,\n node: binding.path.node,\n params,\n resolver,\n scope,\n })\n }\n\n throw new Error(\n `Could not find binding for node \"${node.name}\" in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveCallExpression({\n babelConfig,\n file,\n filename,\n node,\n params,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.CallExpression\n params: babelTypes.Node[]\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): resolveExpressionReturnType {\n const {callee} = node\n return resolveExpression({\n babelConfig,\n file,\n filename,\n fnArguments: node.arguments,\n node: callee,\n params,\n resolver,\n scope,\n })\n}\n\nfunction resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.ExportSpecifier | babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}) {\n let importDeclaration: babelTypes.ImportDeclaration | undefined\n traverse(file, {\n ImportDeclaration(n) {\n if (!babelTypes.isImportDeclaration(n.node)) {\n return\n }\n for (const specifier of n.node.specifiers) {\n if (\n babelTypes.isImportDefaultSpecifier(specifier) &&\n specifier.local.loc?.identifierName === node.local.name\n ) {\n importDeclaration = n.node\n break\n }\n if (specifier.local.name === node.local.name) {\n importDeclaration = n.node\n }\n }\n },\n })\n\n if (!importDeclaration) {\n throw new Error(`Could not find import declaration for ${node.local.name}`)\n }\n\n const importName = node.local.name\n const importFileName = importDeclaration.source.value\n\n const importPath =\n importFileName.startsWith('./') || importFileName.startsWith('../')\n ? path.resolve(path.dirname(filename), importFileName)\n : importFileName\n\n const resolvedFile = resolver(formatPath(importPath))\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let scope: Scope | undefined\n traverse(tree, {\n Program(p) {\n scope = p.scope\n },\n })\n if (!scope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = scope.getBinding(importName)\n return {binding, importFileName, importName, resolvedFile, scope, tree}\n}\n\nfunction resolveImportSpecifier({\n babelConfig,\n file,\n filename,\n fnArguments,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n fnArguments: babelTypes.Node[]\n node: babelTypes.ExportSpecifier | babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n const {binding, importFileName, importName, resolvedFile, scope, tree} = resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n })\n\n if (binding) {\n return resolveExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n fnArguments,\n node: binding.path.node,\n resolver,\n scope,\n })\n }\n\n // It's not a global binding, but it might be a named export\n let namedExport: babelTypes.ExportNamedDeclaration | undefined\n let newImportName: string | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportNamedDeclaration') {\n for (const specifier of p.node.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exported.type === 'Identifier' &&\n specifier.exported.name === importName\n ) {\n namedExport = p.node\n newImportName = specifier.exported.name\n }\n }\n }\n },\n })\n\n if (namedExport && newImportName) {\n return resolveExportSpecifier({\n babelConfig,\n filename: resolvedFile,\n fnArguments,\n importName: newImportName,\n node: namedExport,\n resolver,\n })\n }\n\n let result: resolveExpressionReturnType | undefined\n traverse(tree, {\n ExportDeclaration(p) {\n if (p.node.type === 'ExportAllDeclaration') {\n try {\n result = resolveExportSpecifier({\n babelConfig,\n filename: resolvedFile,\n fnArguments,\n importName,\n node: p.node,\n resolver,\n })\n } catch (e) {\n if ((e as Error).cause !== `noBinding:${importName}`) throw e\n }\n }\n },\n })\n if (result) return result\n\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n}\n\nfunction resolveExportSpecifier({\n babelConfig,\n filename,\n fnArguments,\n importName,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n filename: string\n fnArguments: babelTypes.Node[]\n importName: string\n node: babelTypes.ExportAllDeclaration | babelTypes.ExportNamedDeclaration\n resolver: NodeJS.RequireResolve\n}): resolveExpressionReturnType {\n if (!node.source) {\n throw new Error(`Could not find source for export \"${importName}\" in ${filename}`)\n }\n\n const importFileName = node.source.value\n const importPath = path.resolve(path.dirname(filename), importFileName)\n const resolvedFile = resolver(formatPath(importPath))\n const source = fs.readFileSync(resolvedFile)\n const tree = parseSourceFile(source.toString(), resolvedFile, babelConfig)\n\n let newScope: Scope | undefined\n traverse(tree, {\n Program(p) {\n newScope = p.scope\n },\n })\n if (!newScope) {\n throw new Error(`Could not find scope for ${filename}`)\n }\n\n const binding = newScope.getBinding(importName)\n if (binding) {\n return resolveExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n fnArguments,\n node: binding.path.node,\n resolver,\n scope: newScope,\n })\n }\n\n throw new Error(`Could not find binding for export \"${importName}\" in ${importFileName}`, {\n cause: `noBinding:${importName}`,\n })\n}\n\nfunction getMemberPropertyName(node: babelTypes.MemberExpression): string {\n const {computed, loc, property} = node\n if (!computed && babelTypes.isIdentifier(property)) {\n return property.name\n }\n if (computed && babelTypes.isStringLiteral(property)) {\n return property.value\n }\n const locInfo = loc ? `${loc.filename}:${loc.start.line}:${loc.start.column}` : 'unknown location'\n throw new Error(`Unsupported MemberExpression property type: ${property.type} @ ${locInfo}`)\n}\n\nfunction findObjectProperty(\n objExpr: babelTypes.ObjectExpression,\n propertyName: string,\n filename: string,\n node: babelTypes.Node,\n): babelTypes.ObjectProperty {\n for (const prop of objExpr.properties) {\n if (!babelTypes.isObjectProperty(prop)) continue\n if (babelTypes.isIdentifier(prop.key) && prop.key.name === propertyName) {\n return prop\n }\n if (babelTypes.isStringLiteral(prop.key) && prop.key.value === propertyName) {\n return prop\n }\n }\n throw new Error(\n `Could not find property \"${propertyName}\" in object expression in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n scope,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.Node\n resolver: NodeJS.RequireResolve\n scope: Scope\n}): babelTypes.ObjectExpression {\n if (babelTypes.isObjectExpression(node)) {\n return node\n }\n if (babelTypes.isTSAsExpression(node)) {\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.expression,\n resolver,\n scope,\n })\n }\n if (babelTypes.isIdentifier(node)) {\n const binding = scope.getBinding(node.name)\n if (!binding) {\n throw new Error(`Could not find binding for \"${node.name}\" in ${filename}`)\n }\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: binding.path.node,\n resolver,\n scope,\n })\n }\n if (babelTypes.isVariableDeclarator(node)) {\n if (!node.init) {\n throw new Error(`Variable declarator has no init`)\n }\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.init,\n resolver,\n scope,\n })\n }\n if (babelTypes.isMemberExpression(node)) {\n const propertyName = getMemberPropertyName(node)\n const objExpr = resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: node.object,\n resolver,\n scope,\n })\n const prop = findObjectProperty(objExpr, propertyName, filename, node)\n return resolveToObjectExpression({\n babelConfig,\n file,\n filename,\n node: prop.value,\n resolver,\n scope,\n })\n }\n if (babelTypes.isImportDefaultSpecifier(node) || babelTypes.isImportSpecifier(node)) {\n return resolveImportToObjectExpression({babelConfig, file, filename, node, resolver})\n }\n throw new Error(\n `Cannot resolve node type \"${node.type}\" to ObjectExpression in ${filename}:${node.loc?.start.line}:${node.loc?.start.column}`,\n )\n}\n\nfunction resolveImportToObjectExpression({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n}: {\n babelConfig: TransformOptions\n file: babelTypes.File\n filename: string\n node: babelTypes.ImportDefaultSpecifier | babelTypes.ImportSpecifier\n resolver: NodeJS.RequireResolve\n}): babelTypes.ObjectExpression {\n const {binding, importFileName, importName, resolvedFile, scope, tree} = resolveImportBinding({\n babelConfig,\n file,\n filename,\n node,\n resolver,\n })\n\n if (!binding) {\n throw new Error(`Could not find binding for import \"${importName}\" in ${importFileName}`)\n }\n\n return resolveToObjectExpression({\n babelConfig,\n file: tree,\n filename: resolvedFile,\n node: binding.path.node,\n resolver,\n scope,\n })\n}\n"],"names":["fs","path","traverse","Scope","babelTypes","createDebug","formatPath","parseSourceFile","debug","TAGGED_TEMPLATE_ALLOW_LIST","Set","FUNCTION_WRAPPER_ALLOW_LIST","resolveExpression","babelConfig","file","filename","fnArguments","node","params","resolver","scope","type","loc","start","line","column","isTaggedTemplateExpression","isIdentifier","tag","has","name","quasi","isTemplateLiteral","resolvedExpressions","expressions","map","expression","quasis","idx","value","cooked","join","isLiteral","Error","toString","resolveIdentifier","isVariableDeclarator","init","isAssignmentPattern","id","right","isCallExpression","callee","arguments","resolveCallExpression","isArrowFunctionExpression","isFunctionDeclaration","isFunctionExpression","newScope","i","param","entries","push","body","isNewExpression","isImportDefaultSpecifier","isImportSpecifier","resolveImportSpecifier","isTSAsExpression","isMemberExpression","propertyName","getMemberPropertyName","objExpr","resolveToObjectExpression","object","prop","findObjectProperty","paramIndex","findIndex","left","argument","binding","getBinding","isSame","resolveImportBinding","importDeclaration","ImportDeclaration","n","isImportDeclaration","specifier","specifiers","local","identifierName","importName","importFileName","source","importPath","startsWith","resolve","dirname","resolvedFile","readFileSync","tree","Program","p","namedExport","newImportName","ExportDeclaration","exported","resolveExportSpecifier","result","e","cause","computed","property","isStringLiteral","locInfo","properties","isObjectProperty","key","isObjectExpression","resolveImportToObjectExpression"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAE5B,SAA+BC,QAAQ,QAAO,cAAa;AAC3D,SAAQC,KAAK,QAAO,kBAAiB;AACrC,YAAYC,gBAAgB,eAAc;AAC1C,SAAQC,WAAW,QAAO,OAAM;AAEhC,SAAQC,UAAU,QAAO,yBAAwB;AACjD,SAAQC,eAAe,QAAO,mBAAkB;AAEhD,MAAMC,QAAQH,YAAY;AAI1B,MAAMI,6BAA6B,IAAIC,IAAI;IAAC;CAAO;AACnD,MAAMC,8BAA8B,IAAID,IAAI;IAAC;CAAc;AAE3D;;;;CAIC,GACD,OAAO,SAASE,kBAAkB,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"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
|
-
import createDebug from 'debug';
|
|
3
2
|
import glob from 'globby';
|
|
3
|
+
import { createDebug } from 'obug';
|
|
4
4
|
import { getBabelConfig } from '../getBabelConfig.js';
|
|
5
5
|
import { findQueriesInSource } from './findQueriesInSource.js';
|
|
6
6
|
import { normalizeGlobPattern } from './helpers.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/typescript/findQueriesInPath.ts"],"sourcesContent":["import fs from 'node:fs/promises'\n\nimport {type TransformOptions} from '@babel/core'\nimport
|
|
1
|
+
{"version":3,"sources":["../../src/typescript/findQueriesInPath.ts"],"sourcesContent":["import fs from 'node:fs/promises'\n\nimport {type TransformOptions} from '@babel/core'\nimport glob from 'globby'\nimport {createDebug} from 'obug'\n\nimport {getBabelConfig} from '../getBabelConfig.js'\nimport {findQueriesInSource} from './findQueriesInSource.js'\nimport {normalizeGlobPattern} from './helpers.js'\nimport {getResolver} from './moduleResolver.js'\nimport {type ExtractedModule, QueryExtractionError} from './types.js'\n\nconst debug = createDebug('sanity:codegen:findQueries:debug')\n\ninterface FindQueriesInPathOptions {\n path: string | string[]\n\n babelOptions?: TransformOptions\n resolver?: NodeJS.RequireResolve\n}\n\n/**\n * findQueriesInPath takes a path or array of paths and returns all GROQ queries in the files.\n * @param path - The path or array of paths to search for queries\n * @param babelOptions - The babel configuration to use when parsing the source\n * @param resolver - A resolver function to use when resolving module imports\n * @returns An async generator that yields the results of the search\n * @beta\n * @internal\n */\nexport function findQueriesInPath({\n babelOptions = getBabelConfig(),\n path,\n resolver = getResolver(),\n}: FindQueriesInPathOptions): {files: string[]; queries: AsyncIterable<ExtractedModule>} {\n const queryNames = new Set()\n // Holds all query names found in the source files\n debug(`Globing ${path}`)\n\n // Normalize glob patterns to use forward slashes on all platforms\n const normalizedPath = normalizeGlobPattern(path)\n\n const files = glob\n .sync(normalizedPath, {\n absolute: false,\n ignore: ['**/node_modules/**'], // we never want to look in node_modules\n onlyFiles: true,\n })\n .toSorted()\n\n async function* getQueries(): AsyncGenerator<ExtractedModule> {\n for (const filename of files) {\n if (typeof filename !== 'string') {\n continue\n }\n\n debug(`Found file \"${filename}\"`)\n try {\n const source = await fs.readFile(filename, 'utf8')\n const pluckedModuleResult = findQueriesInSource(source, filename, babelOptions, resolver)\n // Check and error on duplicate query names, because we can't generate types with the same name.\n for (const {variable} of pluckedModuleResult.queries) {\n if (queryNames.has(variable.id.name)) {\n throw new Error(\n `Duplicate query name found: \"${variable.id.name}\". Query names must be unique across all files.`,\n )\n }\n queryNames.add(variable.id.name)\n }\n\n yield pluckedModuleResult\n } catch (cause) {\n debug(`Error in file \"${filename}\"`, cause)\n\n yield {\n errors: [new QueryExtractionError({cause, filename})],\n filename,\n queries: [],\n }\n }\n }\n }\n\n return {files, queries: getQueries()}\n}\n"],"names":["fs","glob","createDebug","getBabelConfig","findQueriesInSource","normalizeGlobPattern","getResolver","QueryExtractionError","debug","findQueriesInPath","babelOptions","path","resolver","queryNames","Set","normalizedPath","files","sync","absolute","ignore","onlyFiles","toSorted","getQueries","filename","source","readFile","pluckedModuleResult","variable","queries","has","id","name","Error","add","cause","errors"],"mappings":"AAAA,OAAOA,QAAQ,mBAAkB;AAGjC,OAAOC,UAAU,SAAQ;AACzB,SAAQC,WAAW,QAAO,OAAM;AAEhC,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAAQC,oBAAoB,QAAO,eAAc;AACjD,SAAQC,WAAW,QAAO,sBAAqB;AAC/C,SAA8BC,oBAAoB,QAAO,aAAY;AAErE,MAAMC,QAAQN,YAAY;AAS1B;;;;;;;;CAQC,GACD,OAAO,SAASO,kBAAkB,EAChCC,eAAeP,gBAAgB,EAC/BQ,IAAI,EACJC,WAAWN,aAAa,EACC;IACzB,MAAMO,aAAa,IAAIC;IACvB,kDAAkD;IAClDN,MAAM,CAAC,QAAQ,EAAEG,MAAM;IAEvB,kEAAkE;IAClE,MAAMI,iBAAiBV,qBAAqBM;IAE5C,MAAMK,QAAQf,KACXgB,IAAI,CAACF,gBAAgB;QACpBG,UAAU;QACVC,QAAQ;YAAC;SAAqB;QAC9BC,WAAW;IACb,GACCC,QAAQ;IAEX,gBAAgBC;QACd,KAAK,MAAMC,YAAYP,MAAO;YAC5B,IAAI,OAAOO,aAAa,UAAU;gBAChC;YACF;YAEAf,MAAM,CAAC,YAAY,EAAEe,SAAS,CAAC,CAAC;YAChC,IAAI;gBACF,MAAMC,SAAS,MAAMxB,GAAGyB,QAAQ,CAACF,UAAU;gBAC3C,MAAMG,sBAAsBtB,oBAAoBoB,QAAQD,UAAUb,cAAcE;gBAChF,gGAAgG;gBAChG,KAAK,MAAM,EAACe,QAAQ,EAAC,IAAID,oBAAoBE,OAAO,CAAE;oBACpD,IAAIf,WAAWgB,GAAG,CAACF,SAASG,EAAE,CAACC,IAAI,GAAG;wBACpC,MAAM,IAAIC,MACR,CAAC,6BAA6B,EAAEL,SAASG,EAAE,CAACC,IAAI,CAAC,+CAA+C,CAAC;oBAErG;oBACAlB,WAAWoB,GAAG,CAACN,SAASG,EAAE,CAACC,IAAI;gBACjC;gBAEA,MAAML;YACR,EAAE,OAAOQ,OAAO;gBACd1B,MAAM,CAAC,eAAe,EAAEe,SAAS,CAAC,CAAC,EAAEW;gBAErC,MAAM;oBACJC,QAAQ;wBAAC,IAAI5B,qBAAqB;4BAAC2B;4BAAOX;wBAAQ;qBAAG;oBACrDA;oBACAK,SAAS,EAAE;gBACb;YACF;QACF;IACF;IAEA,OAAO;QAACZ;QAAOY,SAASN;IAAY;AACtC"}
|
|
@@ -70,6 +70,21 @@ export function weakMapMemo(fn) {
|
|
|
70
70
|
export function generateCode(node) {
|
|
71
71
|
return `${new CodeGenerator(node).generate().code.trim()}\n\n`;
|
|
72
72
|
}
|
|
73
|
+
export function tsDeclareGlobal(body) {
|
|
74
|
+
const declaration = t.tsModuleDeclaration(t.identifier('global'), t.tsModuleBlock(body));
|
|
75
|
+
declaration.declare = true;
|
|
76
|
+
// Babel 7's generator reads the keyword from `global`, Babel 8's from `kind`; set both so the
|
|
77
|
+
// output is `declare global {` on either.
|
|
78
|
+
declaration.global = true;
|
|
79
|
+
declaration.kind = 'global';
|
|
80
|
+
return declaration;
|
|
81
|
+
}
|
|
82
|
+
export function tsDeclareModule(name, body) {
|
|
83
|
+
const declaration = t.tsModuleDeclaration(t.stringLiteral(name), t.tsModuleBlock(body));
|
|
84
|
+
declaration.declare = true;
|
|
85
|
+
declaration.kind = 'module';
|
|
86
|
+
return declaration;
|
|
87
|
+
}
|
|
73
88
|
export function getFilterArrayUnionType(typeNode, predicate) {
|
|
74
89
|
if (typeNode.of.type !== 'union') {
|
|
75
90
|
return typeNode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/typescript/helpers.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {type ArrayTypeNode, type UnionTypeNode} from 'groq-js'\n\nimport {formatPath} from '../utils/formatPath.js'\nimport {RESERVED_IDENTIFIERS} from './constants.js'\n\nexport function normalizePrintablePath(root: string, filename: string) {\n const resolved = path.resolve(root, filename)\n // Always use Unix-style paths for consistent output across platforms\n return formatPath(path.relative(root, resolved))\n}\n\n/**\n * Normalizes a glob pattern to use forward slashes (POSIX-style paths).\n * Glob patterns must use forward slashes, even on Windows.\n *\n * @param pattern - A glob pattern string or array of patterns\n * @returns The normalized pattern(s) with forward slashes\n * @see https://github.com/sindresorhus/globby#api\n */\nexport function normalizeGlobPattern(pattern: string | string[]): string | string[] {\n if (Array.isArray(pattern)) {\n return pattern.map((p) => formatPath(p))\n }\n return formatPath(pattern)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replaceAll(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n\n/**\n * Checks if a string is a valid ECMAScript IdentifierName.\n * IdentifierNames start with a letter, underscore, or $, and contain only\n * alphanumeric characters, underscores, or $.\n */\nexport function isIdentifierName(input: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(input)\n}\n\nfunction normalizeIdentifier(input: string): string {\n const sanitized = sanitizeIdentifier(input)\n return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`\n}\n\nexport function getUniqueIdentifierForName(name: string, currentIdentifiers: Set<string>) {\n const desiredName = normalizeIdentifier(name)\n let resultingName = desiredName\n let index = 2\n while (currentIdentifiers.has(resultingName) || RESERVED_IDENTIFIERS.has(resultingName)) {\n resultingName = `${desiredName}_${index}`\n index++\n }\n return t.identifier(resultingName)\n}\n\nexport function computeOnce<TReturn>(fn: () => TReturn): () => TReturn {\n const ref = {computed: false, current: undefined as TReturn | undefined}\n\n return function () {\n if (ref.computed) return ref.current as TReturn\n ref.current = fn()\n ref.computed = true\n return ref.current\n }\n}\n\nexport function weakMapMemo<TParam extends object, TReturn>(fn: (arg: TParam) => TReturn) {\n const cache = new WeakMap<object, TReturn>()\n\n const wrapped = function (arg: TParam) {\n if (cache.has(arg)) return cache.get(arg)!\n const result = fn(arg)\n cache.set(arg, result)\n return result\n }\n\n return wrapped\n}\n\nexport function generateCode(node: t.Node) {\n return `${new CodeGenerator(node).generate().code.trim()}\\n\\n`\n}\n\nexport function getFilterArrayUnionType(\n typeNode: ArrayTypeNode,\n predicate: (unionTypeNode: UnionTypeNode['of'][number]) => boolean,\n): ArrayTypeNode {\n if (typeNode.of.type !== 'union') {\n return typeNode\n }\n\n return {\n ...typeNode,\n of: {\n ...typeNode.of,\n of: typeNode.of.of.filter((unionTypeNode) => predicate(unionTypeNode)),\n },\n } satisfies ArrayTypeNode<UnionTypeNode>\n}\n"],"names":["path","CodeGenerator","t","formatPath","RESERVED_IDENTIFIERS","normalizePrintablePath","root","filename","resolved","resolve","relative","normalizeGlobPattern","pattern","Array","isArray","map","p","sanitizeIdentifier","input","replace","replaceAll","_","char","toUpperCase","isIdentifierName","test","normalizeIdentifier","sanitized","charAt","slice","getUniqueIdentifierForName","name","currentIdentifiers","desiredName","resultingName","index","has","identifier","computeOnce","fn","ref","computed","current","undefined","weakMapMemo","cache","WeakMap","wrapped","arg","get","result","set","generateCode","node","generate","code","trim","getFilterArrayUnionType","typeNode","predicate","of","type","filter","unionTypeNode"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,YAAYC,OAAO,eAAc;AAGjC,SAAQC,UAAU,QAAO,yBAAwB;AACjD,SAAQC,oBAAoB,QAAO,iBAAgB;AAEnD,OAAO,SAASC,uBAAuBC,IAAY,EAAEC,QAAgB;IACnE,MAAMC,WAAWR,KAAKS,OAAO,CAACH,MAAMC;IACpC,qEAAqE;IACrE,OAAOJ,WAAWH,KAAKU,QAAQ,CAACJ,MAAME;AACxC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,qBAAqBC,OAA0B;IAC7D,IAAIC,MAAMC,OAAO,CAACF,UAAU;QAC1B,OAAOA,QAAQG,GAAG,CAAC,CAACC,IAAMb,WAAWa;IACvC;IACA,OAAOb,WAAWS;AACpB;AAEA,SAASK,mBAAmBC,KAAa;IACvC,OAAO,GAAGA,MAAMC,OAAO,CAAC,OAAO,KAAKC,UAAU,CAAC,eAAe,CAACC,GAAGC,OAASA,KAAKC,WAAW,KAAK;AAClG;AAEA;;;;CAIC,GACD,OAAO,SAASC,iBAAiBN,KAAa;IAC5C,OAAO,6BAA6BO,IAAI,CAACP;AAC3C;AAEA,SAASQ,oBAAoBR,KAAa;IACxC,MAAMS,YAAYV,mBAAmBC;IACrC,OAAO,GAAGS,UAAUC,MAAM,CAAC,GAAGL,WAAW,KAAKI,UAAUE,KAAK,CAAC,IAAI;AACpE;AAEA,OAAO,SAASC,2BAA2BC,IAAY,EAAEC,kBAA+B;IACtF,MAAMC,cAAcP,oBAAoBK;IACxC,IAAIG,gBAAgBD;IACpB,IAAIE,QAAQ;IACZ,MAAOH,mBAAmBI,GAAG,CAACF,kBAAkB9B,qBAAqBgC,GAAG,CAACF,eAAgB;QACvFA,gBAAgB,GAAGD,YAAY,CAAC,EAAEE,OAAO;QACzCA;IACF;IACA,OAAOjC,EAAEmC,UAAU,CAACH;AACtB;AAEA,OAAO,SAASI,YAAqBC,EAAiB;IACpD,MAAMC,MAAM;QAACC,UAAU;QAAOC,SAASC;IAAgC;IAEvE,OAAO;QACL,IAAIH,IAAIC,QAAQ,EAAE,OAAOD,IAAIE,OAAO;QACpCF,IAAIE,OAAO,GAAGH;QACdC,IAAIC,QAAQ,GAAG;QACf,OAAOD,IAAIE,OAAO;IACpB;AACF;AAEA,OAAO,SAASE,YAA4CL,EAA4B;IACtF,MAAMM,QAAQ,IAAIC;IAElB,MAAMC,UAAU,SAAUC,GAAW;QACnC,IAAIH,MAAMT,GAAG,CAACY,MAAM,OAAOH,MAAMI,GAAG,CAACD;QACrC,MAAME,SAASX,GAAGS;QAClBH,MAAMM,GAAG,CAACH,KAAKE;QACf,OAAOA;IACT;IAEA,OAAOH;AACT;AAEA,OAAO,SAASK,aAAaC,IAAY;IACvC,OAAO,GAAG,IAAIpD,cAAcoD,MAAMC,QAAQ,GAAGC,IAAI,CAACC,IAAI,GAAG,IAAI,CAAC;AAChE;AAEA,OAAO,SAASC,wBACdC,QAAuB,EACvBC,SAAkE;IAElE,IAAID,SAASE,EAAE,CAACC,IAAI,KAAK,SAAS;QAChC,OAAOH;IACT;IAEA,OAAO;QACL,GAAGA,QAAQ;QACXE,IAAI;YACF,GAAGF,SAASE,EAAE;YACdA,IAAIF,SAASE,EAAE,CAACA,EAAE,CAACE,MAAM,CAAC,CAACC,gBAAkBJ,UAAUI;QACzD;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/typescript/helpers.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {CodeGenerator} from '@babel/generator'\nimport * as t from '@babel/types'\nimport {type ArrayTypeNode, type UnionTypeNode} from 'groq-js'\n\nimport {formatPath} from '../utils/formatPath.js'\nimport {RESERVED_IDENTIFIERS} from './constants.js'\n\nexport function normalizePrintablePath(root: string, filename: string) {\n const resolved = path.resolve(root, filename)\n // Always use Unix-style paths for consistent output across platforms\n return formatPath(path.relative(root, resolved))\n}\n\n/**\n * Normalizes a glob pattern to use forward slashes (POSIX-style paths).\n * Glob patterns must use forward slashes, even on Windows.\n *\n * @param pattern - A glob pattern string or array of patterns\n * @returns The normalized pattern(s) with forward slashes\n * @see https://github.com/sindresorhus/globby#api\n */\nexport function normalizeGlobPattern(pattern: string | string[]): string | string[] {\n if (Array.isArray(pattern)) {\n return pattern.map((p) => formatPath(p))\n }\n return formatPath(pattern)\n}\n\nfunction sanitizeIdentifier(input: string): string {\n return `${input.replace(/^\\d/, '_').replaceAll(/[^$\\w]+(.)/g, (_, char) => char.toUpperCase())}`\n}\n\n/**\n * Checks if a string is a valid ECMAScript IdentifierName.\n * IdentifierNames start with a letter, underscore, or $, and contain only\n * alphanumeric characters, underscores, or $.\n */\nexport function isIdentifierName(input: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(input)\n}\n\nfunction normalizeIdentifier(input: string): string {\n const sanitized = sanitizeIdentifier(input)\n return `${sanitized.charAt(0).toUpperCase()}${sanitized.slice(1)}`\n}\n\nexport function getUniqueIdentifierForName(name: string, currentIdentifiers: Set<string>) {\n const desiredName = normalizeIdentifier(name)\n let resultingName = desiredName\n let index = 2\n while (currentIdentifiers.has(resultingName) || RESERVED_IDENTIFIERS.has(resultingName)) {\n resultingName = `${desiredName}_${index}`\n index++\n }\n return t.identifier(resultingName)\n}\n\nexport function computeOnce<TReturn>(fn: () => TReturn): () => TReturn {\n const ref = {computed: false, current: undefined as TReturn | undefined}\n\n return function () {\n if (ref.computed) return ref.current as TReturn\n ref.current = fn()\n ref.computed = true\n return ref.current\n }\n}\n\nexport function weakMapMemo<TParam extends object, TReturn>(fn: (arg: TParam) => TReturn) {\n const cache = new WeakMap<object, TReturn>()\n\n const wrapped = function (arg: TParam) {\n if (cache.has(arg)) return cache.get(arg)!\n const result = fn(arg)\n cache.set(arg, result)\n return result\n }\n\n return wrapped\n}\n\nexport function generateCode(node: t.Node) {\n return `${new CodeGenerator(node).generate().code.trim()}\\n\\n`\n}\n\nexport function tsDeclareGlobal(body: t.Statement[]): t.TSModuleDeclaration {\n const declaration = t.tsModuleDeclaration(t.identifier('global'), t.tsModuleBlock(body))\n declaration.declare = true\n // Babel 7's generator reads the keyword from `global`, Babel 8's from `kind`; set both so the\n // output is `declare global {` on either.\n declaration.global = true\n declaration.kind = 'global'\n return declaration\n}\n\nexport function tsDeclareModule(name: string, body: t.Statement[]): t.TSModuleDeclaration {\n const declaration = t.tsModuleDeclaration(t.stringLiteral(name), t.tsModuleBlock(body))\n declaration.declare = true\n declaration.kind = 'module'\n return declaration\n}\n\nexport function getFilterArrayUnionType(\n typeNode: ArrayTypeNode,\n predicate: (unionTypeNode: UnionTypeNode['of'][number]) => boolean,\n): ArrayTypeNode {\n if (typeNode.of.type !== 'union') {\n return typeNode\n }\n\n return {\n ...typeNode,\n of: {\n ...typeNode.of,\n of: typeNode.of.of.filter((unionTypeNode) => predicate(unionTypeNode)),\n },\n } satisfies ArrayTypeNode<UnionTypeNode>\n}\n"],"names":["path","CodeGenerator","t","formatPath","RESERVED_IDENTIFIERS","normalizePrintablePath","root","filename","resolved","resolve","relative","normalizeGlobPattern","pattern","Array","isArray","map","p","sanitizeIdentifier","input","replace","replaceAll","_","char","toUpperCase","isIdentifierName","test","normalizeIdentifier","sanitized","charAt","slice","getUniqueIdentifierForName","name","currentIdentifiers","desiredName","resultingName","index","has","identifier","computeOnce","fn","ref","computed","current","undefined","weakMapMemo","cache","WeakMap","wrapped","arg","get","result","set","generateCode","node","generate","code","trim","tsDeclareGlobal","body","declaration","tsModuleDeclaration","tsModuleBlock","declare","global","kind","tsDeclareModule","stringLiteral","getFilterArrayUnionType","typeNode","predicate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IAAI;YACF,GAAGF,SAASE,EAAE;YACdA,IAAIF,SAASE,EAAE,CAACA,EAAE,CAACE,MAAM,CAAC,CAACC,gBAAkBJ,UAAUI;QACzD;IACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import createDebug from '
|
|
2
|
+
import { createDebug } from 'obug';
|
|
3
3
|
import { createMatchPath, loadConfig as loadTSConfig } from 'tsconfig-paths';
|
|
4
4
|
const require = createRequire(import.meta.url);
|
|
5
5
|
const debug = createDebug('sanity:codegen:moduleResolver');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/typescript/moduleResolver.ts"],"sourcesContent":["import {createRequire} from 'node:module'\n\nimport createDebug from '
|
|
1
|
+
{"version":3,"sources":["../../src/typescript/moduleResolver.ts"],"sourcesContent":["import {createRequire} from 'node:module'\n\nimport {createDebug} from 'obug'\nimport {createMatchPath, loadConfig as loadTSConfig} from 'tsconfig-paths'\n\nconst require = createRequire(import.meta.url)\nconst debug = createDebug('sanity:codegen:moduleResolver')\n\n/**\n * This is a custom implementation of require.resolve that takes into account the paths\n * configuration in tsconfig.json. This is necessary if we want to resolve paths that are\n * custom defined in the tsconfig.json file.\n * Resolving here is best effort and might not work in all cases.\n * @beta\n */\nexport function getResolver(cwd?: string): NodeJS.RequireResolve {\n const tsConfig = loadTSConfig(cwd)\n\n if (tsConfig.resultType === 'failed') {\n debug('Could not load tsconfig, using default resolver: %s', tsConfig.message)\n return require.resolve\n }\n\n const matchPath = createMatchPath(\n tsConfig.absoluteBaseUrl,\n tsConfig.paths,\n tsConfig.mainFields,\n tsConfig.addMatchAll,\n )\n\n const resolve = function (request: string, options?: {paths?: string[]}): string {\n const found = matchPath(request)\n if (found !== undefined) {\n return require.resolve(found, options)\n }\n return require.resolve(request, options)\n }\n\n // wrap the resolve.path function to make it available.\n resolve.paths = (request: string): string[] | null => {\n return require.resolve.paths(request)\n }\n return resolve\n}\n"],"names":["createRequire","createDebug","createMatchPath","loadConfig","loadTSConfig","require","url","debug","getResolver","cwd","tsConfig","resultType","message","resolve","matchPath","absoluteBaseUrl","paths","mainFields","addMatchAll","request","options","found","undefined"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AAEzC,SAAQC,WAAW,QAAO,OAAM;AAChC,SAAQC,eAAe,EAAEC,cAAcC,YAAY,QAAO,iBAAgB;AAE1E,MAAMC,UAAUL,cAAc,YAAYM,GAAG;AAC7C,MAAMC,QAAQN,YAAY;AAE1B;;;;;;CAMC,GACD,OAAO,SAASO,YAAYC,GAAY;IACtC,MAAMC,WAAWN,aAAaK;IAE9B,IAAIC,SAASC,UAAU,KAAK,UAAU;QACpCJ,MAAM,uDAAuDG,SAASE,OAAO;QAC7E,OAAOP,QAAQQ,OAAO;IACxB;IAEA,MAAMC,YAAYZ,gBAChBQ,SAASK,eAAe,EACxBL,SAASM,KAAK,EACdN,SAASO,UAAU,EACnBP,SAASQ,WAAW;IAGtB,MAAML,UAAU,SAAUM,OAAe,EAAEC,OAA4B;QACrE,MAAMC,QAAQP,UAAUK;QACxB,IAAIE,UAAUC,WAAW;YACvB,OAAOjB,QAAQQ,OAAO,CAACQ,OAAOD;QAChC;QACA,OAAOf,QAAQQ,OAAO,CAACM,SAASC;IAClC;IAEA,uDAAuD;IACvDP,QAAQG,KAAK,GAAG,CAACG;QACf,OAAOd,QAAQQ,OAAO,CAACG,KAAK,CAACG;IAC/B;IACA,OAAON;AACT"}
|
|
@@ -3,7 +3,7 @@ import * as t from '@babel/types';
|
|
|
3
3
|
import { createSelector } from 'reselect';
|
|
4
4
|
import { resultSuffix } from '../casing.js';
|
|
5
5
|
import { ALL_SANITY_SCHEMA_TYPES, ARRAY_OF, INTERNAL_REFERENCE_SYMBOL, SANITY_QUERIES } from './constants.js';
|
|
6
|
-
import { computeOnce, generateCode, getUniqueIdentifierForName, normalizePrintablePath } from './helpers.js';
|
|
6
|
+
import { computeOnce, generateCode, getUniqueIdentifierForName, normalizePrintablePath, tsDeclareGlobal, tsDeclareModule } from './helpers.js';
|
|
7
7
|
import { SchemaTypeGenerator } from './schemaTypeGenerator.js';
|
|
8
8
|
import { QueryEvaluationError } from './types.js';
|
|
9
9
|
/**
|
|
@@ -166,20 +166,31 @@ import { QueryEvaluationError } from './types.js';
|
|
|
166
166
|
typesByQuerystring[query].push(id.name);
|
|
167
167
|
}
|
|
168
168
|
const queryReturnInterface = t.tsInterfaceDeclaration(SANITY_QUERIES, null, [], t.tsInterfaceBody(Object.entries(typesByQuerystring).map(([query, types])=>{
|
|
169
|
-
return t.tsPropertySignature(t.stringLiteral(query), t.tsTypeAnnotation(
|
|
169
|
+
return t.tsPropertySignature(t.stringLiteral(query), t.tsTypeAnnotation(t.tsUnionType(types.map((type)=>t.tsTypeReference(t.identifier(type))))));
|
|
170
170
|
})));
|
|
171
|
-
const
|
|
171
|
+
const globalRegistry = t.addComments(tsDeclareGlobal([
|
|
172
172
|
queryReturnInterface
|
|
173
|
-
])
|
|
174
|
-
const clientImport = t.addComments(t.importDeclaration([], t.stringLiteral('@sanity/client')), 'leading', [
|
|
173
|
+
]), 'leading', [
|
|
175
174
|
{
|
|
176
175
|
type: 'CommentLine',
|
|
177
176
|
value: ' Query TypeMap'
|
|
178
177
|
}
|
|
179
178
|
]);
|
|
179
|
+
// The client-side global registry: https://github.com/sanity-io/client/pull/1319 (8.x) and
|
|
180
|
+
// https://github.com/sanity-io/client/pull/1320 (7.x)
|
|
181
|
+
const bridge = t.addComments(tsDeclareModule('@sanity/client', [
|
|
182
|
+
t.tsInterfaceDeclaration(SANITY_QUERIES, null, [
|
|
183
|
+
t.tsExpressionWithTypeArguments(t.tsQualifiedName(t.identifier('globalThis'), SANITY_QUERIES))
|
|
184
|
+
], t.tsInterfaceBody([]))
|
|
185
|
+
]), 'leading', [
|
|
186
|
+
{
|
|
187
|
+
type: 'CommentLine',
|
|
188
|
+
value: ' Lets @sanity/client releases that predate the global registry read it too'
|
|
189
|
+
}
|
|
190
|
+
]);
|
|
180
191
|
const ast = t.program([
|
|
181
|
-
|
|
182
|
-
|
|
192
|
+
globalRegistry,
|
|
193
|
+
bridge
|
|
183
194
|
]);
|
|
184
195
|
const code = generateCode(ast);
|
|
185
196
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/typescript/typeGenerator.ts"],"sourcesContent":["/* eslint-disable unicorn/consistent-function-scoping */\nimport process from 'node:process'\n\nimport * as t from '@babel/types'\nimport {type WorkerChannel, type WorkerChannelReporter} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {resultSuffix} from '../casing.js'\nimport {\n ALL_SANITY_SCHEMA_TYPES,\n ARRAY_OF,\n INTERNAL_REFERENCE_SYMBOL,\n SANITY_QUERIES,\n} from './constants.js'\nimport {\n computeOnce,\n generateCode,\n getUniqueIdentifierForName,\n normalizePrintablePath,\n} from './helpers.js'\nimport {SchemaTypeGenerator} from './schemaTypeGenerator.js'\nimport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n QueryEvaluationError,\n type QueryExtractionError,\n} from './types.js'\n\n/** @public */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<{\n evaluatedModules: WorkerChannel.Stream<EvaluatedModule>\n generatedQueryTypes: WorkerChannel.Event<{\n queryMapDeclaration: {ast: t.Program; code: string}\n }>\n generatedSchemaTypes: WorkerChannel.Event<{\n allSanitySchemaTypesDeclaration: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n internalReferenceSymbol: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n schemaTypeDeclarations: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n name: string\n tsType: t.TSType\n }[]\n }>\n}>\n\n/** @public */\nexport interface GenerateTypesOptions {\n schema: SchemaType\n\n overloadClientMethods?: boolean\n queries?: AsyncIterable<ExtractedModule>\n reporter?: WorkerChannelReporter<TypegenWorkerChannel>\n root?: string\n schemaPath?: string\n}\n\ntype GetEvaluatedModulesOptions = GenerateTypesOptions & {\n schemaTypeDeclarations: ReturnType<TypeGenerator['getSchemaTypeDeclarations']>\n schemaTypeGenerator: SchemaTypeGenerator\n}\ntype GetQueryMapDeclarationOptions = GenerateTypesOptions & {\n evaluatedModules: EvaluatedModule[]\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @beta\n */\nexport class TypeGenerator {\n private getSchemaTypeGenerator = createSelector(\n [(options: GenerateTypesOptions) => options.schema],\n\n (schema) => new SchemaTypeGenerator(schema),\n )\n\n private getSchemaTypeDeclarations = createSelector(\n [\n (options: GenerateTypesOptions) => options.root,\n (options: GenerateTypesOptions) => options.schemaPath,\n this.getSchemaTypeGenerator,\n ],\n\n (root = process.cwd(), schemaPath, schema) =>\n [...schema].map(({id, name, tsType}, index) => {\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n let ast = t.exportNamedDeclaration(typeAlias)\n\n if (index === 0 && schemaPath) {\n ast = t.addComments(ast, 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, schemaPath)}`},\n ])\n }\n const code = generateCode(ast)\n return {ast, code, id, name, tsType}\n }),\n )\n\n private getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length > 0\n ? t.tsUnionType(schemaTypes.map(({id}) => t.tsTypeReference(id)))\n : t.tsNeverKeyword(),\n ),\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ALL_SANITY_SCHEMA_TYPES}\n },\n )\n\n private getArrayOfDeclaration = computeOnce(() => {\n // Creates: type ArrayOf<T> = Array<T & { _key: string }>;\n const typeParam = t.tsTypeParameter(null, null, 'T')\n const intersectionType = t.tsIntersectionType([\n t.tsTypeReference(t.identifier('T')),\n t.tsTypeLiteral([\n t.tsPropertySignature(t.identifier('_key'), t.tsTypeAnnotation(t.tsStringKeyword())),\n ]),\n ])\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([intersectionType]),\n )\n\n const ast = t.tsTypeAliasDeclaration(\n ARRAY_OF,\n t.tsTypeParameterDeclaration([typeParam]),\n arrayType,\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ARRAY_OF}\n })\n\n private getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), 'unique')\n\n const id = INTERNAL_REFERENCE_SYMBOL\n id.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const declaration = t.variableDeclaration('const', [t.variableDeclarator(id)])\n declaration.declare = true\n const ast = t.exportNamedDeclaration(declaration)\n const code = generateCode(ast)\n\n return {ast, code, id}\n })\n\n private static async getEvaluatedModules({\n queries: extractedModules,\n reporter: report,\n root = process.cwd(),\n schemaTypeDeclarations,\n schemaTypeGenerator,\n }: GetEvaluatedModulesOptions) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end()\n return []\n }\n\n const currentIdentifiers = new Set<string>(schemaTypeDeclarations.map(({id}) => id.name))\n const evaluatedModuleResults: EvaluatedModule[] = []\n\n for await (const {filename, ...extractedModule} of extractedModules) {\n const queries: EvaluatedQuery[] = []\n const errors: (QueryEvaluationError | QueryExtractionError)[] = [...extractedModule.errors]\n\n for (const extractedQuery of extractedModule.queries) {\n const {variable} = extractedQuery\n try {\n const {stats, tsType} = schemaTypeGenerator.evaluateQuery(extractedQuery)\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers)\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n const trimmedQuery = extractedQuery.query.replaceAll(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const ast = t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {type: 'CommentLine', value: ` Query: ${trimmedQuery}`},\n ])\n\n const evaluatedQueryResult: EvaluatedQuery = {\n ast,\n code: generateCode(ast),\n id,\n stats,\n tsType,\n ...extractedQuery,\n }\n\n currentIdentifiers.add(id.name)\n queries.push(evaluatedQueryResult)\n } catch (cause) {\n errors.push(new QueryEvaluationError({cause, filename, variable}))\n }\n }\n\n const evaluatedModule: EvaluatedModule = {\n errors,\n filename,\n queries,\n }\n report?.stream.evaluatedModules.emit(evaluatedModule)\n evaluatedModuleResults.push(evaluatedModule)\n }\n report?.stream.evaluatedModules.end()\n\n return evaluatedModuleResults\n }\n\n private static async getQueryMapDeclaration({\n evaluatedModules,\n overloadClientMethods = true,\n }: GetQueryMapDeclarationOptions) {\n if (!overloadClientMethods) return {ast: t.program([]), code: ''}\n\n const queries = evaluatedModules.flatMap((module) => module.queries)\n if (queries.length === 0) return {ast: t.program([]), code: ''}\n\n const typesByQuerystring: {[query: string]: string[]} = {}\n for (const {id, query} of queries) {\n typesByQuerystring[query] ??= []\n typesByQuerystring[query].push(id.name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t.tsInterfaceBody(\n Object.entries(typesByQuerystring).map(([query, types]) => {\n return t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n types.length > 0\n ? t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type))))\n : t.tsNeverKeyword(),\n ),\n )\n }),\n ),\n )\n\n const declareModule = t.declareModule(\n t.stringLiteral('@sanity/client'),\n t.blockStatement([queryReturnInterface]),\n )\n\n const clientImport = t.addComments(\n t.importDeclaration([], t.stringLiteral('@sanity/client')),\n 'leading',\n [{type: 'CommentLine', value: ' Query TypeMap'}],\n )\n\n const ast = t.program([clientImport, declareModule])\n const code = generateCode(ast)\n return {ast, code}\n }\n\n async generateTypes(options: GenerateTypesOptions) {\n const {reporter: report} = options\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration()\n const schemaTypeGenerator = this.getSchemaTypeGenerator(options)\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options)\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options)\n\n report?.event.generatedSchemaTypes({\n allSanitySchemaTypesDeclaration,\n internalReferenceSymbol,\n schemaTypeDeclarations,\n })\n\n // Queries can produce `inline` type nodes that the schema-side generator\n // never sees (e.g. filtering a tagged-union array down to its inline\n // members). Evaluate modules before deciding whether the ArrayOf helper is\n // needed, so query-only usage still triggers the declaration.\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator,\n })\n\n const program = t.program([])\n let code = ''\n\n program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n if (schemaTypeGenerator.isArrayOfUsed()) {\n const arrayOfDeclaration = this.getArrayOfDeclaration()\n program.body.push(arrayOfDeclaration.ast)\n code += arrayOfDeclaration.code\n }\n\n for (const declaration of schemaTypeDeclarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n\n program.body.push(allSanitySchemaTypesDeclaration.ast)\n code += allSanitySchemaTypesDeclaration.code\n\n for (const {queries} of evaluatedModules) {\n for (const query of queries) {\n program.body.push(query.ast)\n code += query.code\n }\n }\n\n const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules,\n })\n program.body.push(...queryMapDeclaration.ast.body)\n code += queryMapDeclaration.code\n\n report?.event.generatedQueryTypes({queryMapDeclaration})\n\n return {ast: program, code}\n }\n}\n"],"names":["process","t","createSelector","resultSuffix","ALL_SANITY_SCHEMA_TYPES","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","SANITY_QUERIES","computeOnce","generateCode","getUniqueIdentifierForName","normalizePrintablePath","SchemaTypeGenerator","QueryEvaluationError","TypeGenerator","getSchemaTypeGenerator","options","schema","getSchemaTypeDeclarations","root","schemaPath","cwd","map","id","name","tsType","index","typeAlias","tsTypeAliasDeclaration","ast","exportNamedDeclaration","addComments","type","value","code","getAllSanitySchemaTypesDeclaration","schemaTypes","length","tsUnionType","tsTypeReference","tsNeverKeyword","getArrayOfDeclaration","typeParam","tsTypeParameter","intersectionType","tsIntersectionType","identifier","tsTypeLiteral","tsPropertySignature","tsTypeAnnotation","tsStringKeyword","arrayType","tsTypeParameterInstantiation","tsTypeParameterDeclaration","getInternalReferenceSymbolDeclaration","typeOperator","tsTypeOperator","tsSymbolKeyword","typeAnnotation","declaration","variableDeclaration","variableDeclarator","declare","getEvaluatedModules","queries","extractedModules","reporter","report","schemaTypeDeclarations","schemaTypeGenerator","stream","evaluatedModules","end","currentIdentifiers","Set","evaluatedModuleResults","filename","extractedModule","errors","extractedQuery","variable","stats","evaluateQuery","trimmedQuery","query","replaceAll","trim","evaluatedQueryResult","add","push","cause","evaluatedModule","emit","getQueryMapDeclaration","overloadClientMethods","program","flatMap","module","typesByQuerystring","queryReturnInterface","tsInterfaceDeclaration","tsInterfaceBody","Object","entries","types","stringLiteral","declareModule","blockStatement","clientImport","importDeclaration","generateTypes","internalReferenceSymbol","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","body","isArrayOfUsed","arrayOfDeclaration","queryMapDeclaration","generatedQueryTypes"],"mappings":"AAAA,sDAAsD,GACtD,OAAOA,aAAa,eAAc;AAElC,YAAYC,OAAO,eAAc;AAGjC,SAAQC,cAAc,QAAO,WAAU;AAEvC,SAAQC,YAAY,QAAO,eAAc;AACzC,SACEC,uBAAuB,EACvBC,QAAQ,EACRC,yBAAyB,EACzBC,cAAc,QACT,iBAAgB;AACvB,SACEC,WAAW,EACXC,YAAY,EACZC,0BAA0B,EAC1BC,sBAAsB,QACjB,eAAc;AACrB,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAIEC,oBAAoB,QAEf,aAAY;AAgDnB;;;CAGC,GACD,OAAO,MAAMC;IACHC,yBAAyBb,eAC/B;QAAC,CAACc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;YAChD2B,QAAQoB,IAAI,CAAC1B,IAAI,CAAC9B,YAAY9B,GAAG;YACjCK,QAAQyB,YAAYzB,IAAI;QAC1B;QAEA6D,QAAQoB,IAAI,CAAC1B,IAAI,CAACuB,gCAAgCnF,GAAG;QACrDK,QAAQ8E,gCAAgC9E,IAAI;QAE5C,KAAK,MAAM,EAAC8B,OAAO,EAAC,IAAIO,iBAAkB;YACxC,KAAK,MAAMa,SAASpB,QAAS;gBAC3B+B,QAAQoB,IAAI,CAAC1B,IAAI,CAACL,MAAMvD,GAAG;gBAC3BK,QAAQkD,MAAMlD,IAAI;YACpB;QACF;QAEA,MAAMoF,sBAAsB,MAAMxG,cAAc+E,sBAAsB,CAAC;YACrE,GAAG7E,OAAO;YACVuD;QACF;QACAwB,QAAQoB,IAAI,CAAC1B,IAAI,IAAI6B,oBAAoBzF,GAAG,CAACsF,IAAI;QACjDjF,QAAQoF,oBAAoBpF,IAAI;QAEhCiC,QAAQ8C,MAAMM,oBAAoB;YAACD;QAAmB;QAEtD,OAAO;YAACzF,KAAKkE;YAAS7D;QAAI;IAC5B;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/typescript/typeGenerator.ts"],"sourcesContent":["/* eslint-disable unicorn/consistent-function-scoping */\nimport process from 'node:process'\n\nimport * as t from '@babel/types'\nimport {type WorkerChannel, type WorkerChannelReporter} from '@sanity/worker-channels'\nimport {type SchemaType} from 'groq-js'\nimport {createSelector} from 'reselect'\n\nimport {resultSuffix} from '../casing.js'\nimport {\n ALL_SANITY_SCHEMA_TYPES,\n ARRAY_OF,\n INTERNAL_REFERENCE_SYMBOL,\n SANITY_QUERIES,\n} from './constants.js'\nimport {\n computeOnce,\n generateCode,\n getUniqueIdentifierForName,\n normalizePrintablePath,\n tsDeclareGlobal,\n tsDeclareModule,\n} from './helpers.js'\nimport {SchemaTypeGenerator} from './schemaTypeGenerator.js'\nimport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n QueryEvaluationError,\n type QueryExtractionError,\n} from './types.js'\n\n/** @public */\nexport type TypegenWorkerChannel = WorkerChannel.Definition<{\n evaluatedModules: WorkerChannel.Stream<EvaluatedModule>\n generatedQueryTypes: WorkerChannel.Event<{\n queryMapDeclaration: {ast: t.Program; code: string}\n }>\n generatedSchemaTypes: WorkerChannel.Event<{\n allSanitySchemaTypesDeclaration: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n internalReferenceSymbol: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n }\n schemaTypeDeclarations: {\n ast: t.ExportNamedDeclaration\n code: string\n id: t.Identifier\n name: string\n tsType: t.TSType\n }[]\n }>\n}>\n\n/** @public */\nexport interface GenerateTypesOptions {\n schema: SchemaType\n\n overloadClientMethods?: boolean\n queries?: AsyncIterable<ExtractedModule>\n reporter?: WorkerChannelReporter<TypegenWorkerChannel>\n root?: string\n schemaPath?: string\n}\n\ntype GetEvaluatedModulesOptions = GenerateTypesOptions & {\n schemaTypeDeclarations: ReturnType<TypeGenerator['getSchemaTypeDeclarations']>\n schemaTypeGenerator: SchemaTypeGenerator\n}\ntype GetQueryMapDeclarationOptions = GenerateTypesOptions & {\n evaluatedModules: EvaluatedModule[]\n}\n\n/**\n * A class used to generate TypeScript types from a given schema\n * @beta\n */\nexport class TypeGenerator {\n private getSchemaTypeGenerator = createSelector(\n [(options: GenerateTypesOptions) => options.schema],\n\n (schema) => new SchemaTypeGenerator(schema),\n )\n\n private getSchemaTypeDeclarations = createSelector(\n [\n (options: GenerateTypesOptions) => options.root,\n (options: GenerateTypesOptions) => options.schemaPath,\n this.getSchemaTypeGenerator,\n ],\n\n (root = process.cwd(), schemaPath, schema) =>\n [...schema].map(({id, name, tsType}, index) => {\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n let ast = t.exportNamedDeclaration(typeAlias)\n\n if (index === 0 && schemaPath) {\n ast = t.addComments(ast, 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, schemaPath)}`},\n ])\n }\n const code = generateCode(ast)\n return {ast, code, id, name, tsType}\n }),\n )\n\n private getAllSanitySchemaTypesDeclaration = createSelector(\n [this.getSchemaTypeDeclarations],\n (schemaTypes) => {\n const ast = t.exportNamedDeclaration(\n t.tsTypeAliasDeclaration(\n ALL_SANITY_SCHEMA_TYPES,\n null,\n schemaTypes.length > 0\n ? t.tsUnionType(schemaTypes.map(({id}) => t.tsTypeReference(id)))\n : t.tsNeverKeyword(),\n ),\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ALL_SANITY_SCHEMA_TYPES}\n },\n )\n\n private getArrayOfDeclaration = computeOnce(() => {\n // Creates: type ArrayOf<T> = Array<T & { _key: string }>;\n const typeParam = t.tsTypeParameter(null, null, 'T')\n const intersectionType = t.tsIntersectionType([\n t.tsTypeReference(t.identifier('T')),\n t.tsTypeLiteral([\n t.tsPropertySignature(t.identifier('_key'), t.tsTypeAnnotation(t.tsStringKeyword())),\n ]),\n ])\n const arrayType = t.tsTypeReference(\n t.identifier('Array'),\n t.tsTypeParameterInstantiation([intersectionType]),\n )\n\n const ast = t.tsTypeAliasDeclaration(\n ARRAY_OF,\n t.tsTypeParameterDeclaration([typeParam]),\n arrayType,\n )\n const code = generateCode(ast)\n\n return {ast, code, id: ARRAY_OF}\n })\n\n private getInternalReferenceSymbolDeclaration = computeOnce(() => {\n const typeOperator = t.tsTypeOperator(t.tsSymbolKeyword(), 'unique')\n\n const id = INTERNAL_REFERENCE_SYMBOL\n id.typeAnnotation = t.tsTypeAnnotation(typeOperator)\n\n const declaration = t.variableDeclaration('const', [t.variableDeclarator(id)])\n declaration.declare = true\n const ast = t.exportNamedDeclaration(declaration)\n const code = generateCode(ast)\n\n return {ast, code, id}\n })\n\n private static async getEvaluatedModules({\n queries: extractedModules,\n reporter: report,\n root = process.cwd(),\n schemaTypeDeclarations,\n schemaTypeGenerator,\n }: GetEvaluatedModulesOptions) {\n if (!extractedModules) {\n report?.stream.evaluatedModules.end()\n return []\n }\n\n const currentIdentifiers = new Set<string>(schemaTypeDeclarations.map(({id}) => id.name))\n const evaluatedModuleResults: EvaluatedModule[] = []\n\n for await (const {filename, ...extractedModule} of extractedModules) {\n const queries: EvaluatedQuery[] = []\n const errors: (QueryEvaluationError | QueryExtractionError)[] = [...extractedModule.errors]\n\n for (const extractedQuery of extractedModule.queries) {\n const {variable} = extractedQuery\n try {\n const {stats, tsType} = schemaTypeGenerator.evaluateQuery(extractedQuery)\n const id = getUniqueIdentifierForName(resultSuffix(variable.id.name), currentIdentifiers)\n const typeAlias = t.tsTypeAliasDeclaration(id, null, tsType)\n const trimmedQuery = extractedQuery.query.replaceAll(/(\\r\\n|\\n|\\r)/gm, '').trim()\n const ast = t.addComments(t.exportNamedDeclaration(typeAlias), 'leading', [\n {type: 'CommentLine', value: ` Source: ${normalizePrintablePath(root, filename)}`},\n {type: 'CommentLine', value: ` Variable: ${variable.id.name}`},\n {type: 'CommentLine', value: ` Query: ${trimmedQuery}`},\n ])\n\n const evaluatedQueryResult: EvaluatedQuery = {\n ast,\n code: generateCode(ast),\n id,\n stats,\n tsType,\n ...extractedQuery,\n }\n\n currentIdentifiers.add(id.name)\n queries.push(evaluatedQueryResult)\n } catch (cause) {\n errors.push(new QueryEvaluationError({cause, filename, variable}))\n }\n }\n\n const evaluatedModule: EvaluatedModule = {\n errors,\n filename,\n queries,\n }\n report?.stream.evaluatedModules.emit(evaluatedModule)\n evaluatedModuleResults.push(evaluatedModule)\n }\n report?.stream.evaluatedModules.end()\n\n return evaluatedModuleResults\n }\n\n private static async getQueryMapDeclaration({\n evaluatedModules,\n overloadClientMethods = true,\n }: GetQueryMapDeclarationOptions) {\n if (!overloadClientMethods) return {ast: t.program([]), code: ''}\n\n const queries = evaluatedModules.flatMap((module) => module.queries)\n if (queries.length === 0) return {ast: t.program([]), code: ''}\n\n const typesByQuerystring: {[query: string]: string[]} = {}\n for (const {id, query} of queries) {\n typesByQuerystring[query] ??= []\n typesByQuerystring[query].push(id.name)\n }\n\n const queryReturnInterface = t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [],\n t.tsInterfaceBody(\n Object.entries(typesByQuerystring).map(([query, types]) => {\n return t.tsPropertySignature(\n t.stringLiteral(query),\n t.tsTypeAnnotation(\n t.tsUnionType(types.map((type) => t.tsTypeReference(t.identifier(type)))),\n ),\n )\n }),\n ),\n )\n\n const globalRegistry = t.addComments(tsDeclareGlobal([queryReturnInterface]), 'leading', [\n {type: 'CommentLine', value: ' Query TypeMap'},\n ])\n\n // The client-side global registry: https://github.com/sanity-io/client/pull/1319 (8.x) and\n // https://github.com/sanity-io/client/pull/1320 (7.x)\n const bridge = t.addComments(\n tsDeclareModule('@sanity/client', [\n t.tsInterfaceDeclaration(\n SANITY_QUERIES,\n null,\n [\n t.tsExpressionWithTypeArguments(\n t.tsQualifiedName(t.identifier('globalThis'), SANITY_QUERIES),\n ),\n ],\n t.tsInterfaceBody([]),\n ),\n ]),\n 'leading',\n [\n {\n type: 'CommentLine',\n value: ' Lets @sanity/client releases that predate the global registry read it too',\n },\n ],\n )\n\n const ast = t.program([globalRegistry, bridge])\n const code = generateCode(ast)\n return {ast, code}\n }\n\n async generateTypes(options: GenerateTypesOptions) {\n const {reporter: report} = options\n const internalReferenceSymbol = this.getInternalReferenceSymbolDeclaration()\n const schemaTypeGenerator = this.getSchemaTypeGenerator(options)\n const schemaTypeDeclarations = this.getSchemaTypeDeclarations(options)\n const allSanitySchemaTypesDeclaration = this.getAllSanitySchemaTypesDeclaration(options)\n\n report?.event.generatedSchemaTypes({\n allSanitySchemaTypesDeclaration,\n internalReferenceSymbol,\n schemaTypeDeclarations,\n })\n\n // Queries can produce `inline` type nodes that the schema-side generator\n // never sees (e.g. filtering a tagged-union array down to its inline\n // members). Evaluate modules before deciding whether the ArrayOf helper is\n // needed, so query-only usage still triggers the declaration.\n const evaluatedModules = await TypeGenerator.getEvaluatedModules({\n ...options,\n schemaTypeDeclarations,\n schemaTypeGenerator,\n })\n\n const program = t.program([])\n let code = ''\n\n program.body.push(internalReferenceSymbol.ast)\n code += internalReferenceSymbol.code\n\n if (schemaTypeGenerator.isArrayOfUsed()) {\n const arrayOfDeclaration = this.getArrayOfDeclaration()\n program.body.push(arrayOfDeclaration.ast)\n code += arrayOfDeclaration.code\n }\n\n for (const declaration of schemaTypeDeclarations) {\n program.body.push(declaration.ast)\n code += declaration.code\n }\n\n program.body.push(allSanitySchemaTypesDeclaration.ast)\n code += allSanitySchemaTypesDeclaration.code\n\n for (const {queries} of evaluatedModules) {\n for (const query of queries) {\n program.body.push(query.ast)\n code += query.code\n }\n }\n\n const queryMapDeclaration = await TypeGenerator.getQueryMapDeclaration({\n ...options,\n evaluatedModules,\n })\n program.body.push(...queryMapDeclaration.ast.body)\n code += queryMapDeclaration.code\n\n report?.event.generatedQueryTypes({queryMapDeclaration})\n\n return {ast: program, code}\n }\n}\n"],"names":["process","t","createSelector","resultSuffix","ALL_SANITY_SCHEMA_TYPES","ARRAY_OF","INTERNAL_REFERENCE_SYMBOL","SANITY_QUERIES","computeOnce","generateCode","getUniqueIdentifierForName","normalizePrintablePath","tsDeclareGlobal","tsDeclareModule","SchemaTypeGenerator","QueryEvaluationError","TypeGenerator","getSchemaTypeGenerator","options","schema","getSchemaTypeDeclarations","root","schemaPath","cwd","map","id","name","tsType","index","typeAlias","tsTypeAliasDeclaration","ast","exportNamedDeclaration","addComments","type","value","code","getAllSanitySchemaTypesDeclaration","schemaTypes","length","tsUnionType","tsTypeReference","tsNeverKeyword","getArrayOfDeclaration","typeParam","tsTypeParameter","intersectionType","tsIntersectionType","identifier","tsTypeLiteral","tsPropertySignature","tsTypeAnnotation","tsStringKeyword","arrayType","tsTypeParameterInstantiation","tsTypeParameterDeclaration","getInternalReferenceSymbolDeclaration","typeOperator","tsTypeOperator","tsSymbolKeyword","typeAnnotation","declaration","variableDeclaration","variableDeclarator","declare","getEvaluatedModules","queries","extractedModules","reporter","report","schemaTypeDeclarations","schemaTypeGenerator","stream","evaluatedModules","end","currentIdentifiers","Set","evaluatedModuleResults","filename","extractedModule","errors","extractedQuery","variable","stats","evaluateQuery","trimmedQuery","query","replaceAll","trim","evaluatedQueryResult","add","push","cause","evaluatedModule","emit","getQueryMapDeclaration","overloadClientMethods","program","flatMap","module","typesByQuerystring","queryReturnInterface","tsInterfaceDeclaration","tsInterfaceBody","Object","entries","types","stringLiteral","globalRegistry","bridge","tsExpressionWithTypeArguments","tsQualifiedName","generateTypes","internalReferenceSymbol","allSanitySchemaTypesDeclaration","event","generatedSchemaTypes","body","isArrayOfUsed","arrayOfDeclaration","queryMapDeclaration","generatedQueryTypes"],"mappings":"AAAA,sDAAsD,GACtD,OAAOA,aAAa,eAAc;AAElC,YAAYC,OAAO,eAAc;AAGjC,SAAQC,cAAc,QAAO,WAAU;AAEvC,SAAQC,YAAY,QAAO,eAAc;AACzC,SACEC,uBAAuB,EACvBC,QAAQ,EACRC,yBAAyB,EACzBC,cAAc,QACT,iBAAgB;AACvB,SACEC,WAAW,EACXC,YAAY,EACZC,0BAA0B,EAC1BC,sBAAsB,EACtBC,eAAe,EACfC,eAAe,QACV,eAAc;AACrB,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAIEC,oBAAoB,QAEf,aAAY;AAgDnB;;;CAGC,GACD,OAAO,MAAMC;IACHC,yBAAyBf,eAC/B;QAAC,CAACgB,UAAkCA,QAAQC,MAAM;KAAC,EAEnD,CAACA,SAAW,IAAIL,oBAAoBK,SACrC;IAEOC,4BAA4BlB,eAClC;QACE,CAACgB,UAAkCA,QAAQG,IAAI;QAC/C,CAACH,UAAkCA,QAAQI,UAAU;QACrD,IAAI,CAACL,sBAAsB;KAC5B,EAED,CAACI,OAAOrB,QAAQuB,GAAG,EAAE,EAAED,YAAYH,SACjC;eAAIA;SAAO,CAACK,GAAG,CAAC,CAAC,EAACC,EAAE,EAAEC,IAAI,EAAEC,MAAM,EAAC,EAAEC;YACnC,MAAMC,YAAY5B,EAAE6B,sBAAsB,CAACL,IAAI,MA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B+B,QAAQoB,IAAI,CAAC1B,IAAI,CAACL,MAAMvD,GAAG;gBAC3BK,QAAQkD,MAAMlD,IAAI;YACpB;QACF;QAEA,MAAMoF,sBAAsB,MAAMxG,cAAc+E,sBAAsB,CAAC;YACrE,GAAG7E,OAAO;YACVuD;QACF;QACAwB,QAAQoB,IAAI,CAAC1B,IAAI,IAAI6B,oBAAoBzF,GAAG,CAACsF,IAAI;QACjDjF,QAAQoF,oBAAoBpF,IAAI;QAEhCiC,QAAQ8C,MAAMM,oBAAoB;YAACD;QAAmB;QAEtD,OAAO;YAACzF,KAAKkE;YAAS7D;QAAI;IAC5B;AACF"}
|
package/dist/utils/debug.js
CHANGED
package/dist/utils/debug.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/debug.ts"],"sourcesContent":["import createDebug from '
|
|
1
|
+
{"version":3,"sources":["../../src/utils/debug.ts"],"sourcesContent":["import {createDebug} from 'obug'\n\nexport const debug = createDebug('sanity:typegen:generate')\n"],"names":["createDebug","debug"],"mappings":"AAAA,SAAQA,WAAW,QAAO,OAAM;AAEhC,OAAO,MAAMC,QAAQD,YAAY,2BAA0B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/codegen",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.1.1",
|
|
4
4
|
"description": "Codegen toolkit for Sanity.io",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -47,41 +47,43 @@
|
|
|
47
47
|
"@sanity/telemetry": "^1.1.0",
|
|
48
48
|
"@sanity/worker-channels": "^2.0.0",
|
|
49
49
|
"chokidar": "^3.6.0",
|
|
50
|
-
"debug": "^4.4.3",
|
|
51
50
|
"globby": "^11.1.0",
|
|
52
51
|
"groq": "^6.0.0",
|
|
53
52
|
"groq-js": "^2.0.0",
|
|
54
53
|
"json5": "^2.2.3",
|
|
55
54
|
"lodash-es": "^4.18.1",
|
|
55
|
+
"obug": "^3.0.0",
|
|
56
56
|
"prettier": "^3.8.3",
|
|
57
57
|
"reselect": "^5.2.0",
|
|
58
58
|
"tsconfig-paths": "^4.2.0",
|
|
59
|
-
"
|
|
59
|
+
"valibot": "^1.4.2"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
62
|
"@eslint/compat": "^2.1.0",
|
|
63
63
|
"@sanity/eslint-config-cli": "^1.1.2",
|
|
64
64
|
"@sanity/pkg-utils": "^10.5.5",
|
|
65
|
+
"@size-limit/esbuild": "^13.0.3",
|
|
66
|
+
"@size-limit/file": "^13.0.3",
|
|
65
67
|
"@swc/cli": "^0.8.1",
|
|
66
68
|
"@swc/core": "^1.15.40",
|
|
67
69
|
"@types/babel__core": "^7.20.5",
|
|
68
70
|
"@types/babel__generator": "^7.27.0",
|
|
69
71
|
"@types/babel__register": "^7.17.3",
|
|
70
72
|
"@types/babel__traverse": "^7.28.0",
|
|
71
|
-
"@types/debug": "^4.1.13",
|
|
72
73
|
"@types/lodash-es": "^4.17.12",
|
|
73
|
-
"@types/node": "^24.13.
|
|
74
|
+
"@types/node": "^24.13.3",
|
|
74
75
|
"@vitest/coverage-istanbul": "^4.1.8",
|
|
75
76
|
"eslint": "^9.39.4",
|
|
76
77
|
"husky": "^9.1.7",
|
|
77
78
|
"lint-staged": "^16.4.0",
|
|
78
|
-
"oxfmt": "^0.
|
|
79
|
-
"pkg-pr-new": "^0.0.
|
|
79
|
+
"oxfmt": "^0.66.0",
|
|
80
|
+
"pkg-pr-new": "^0.0.88",
|
|
80
81
|
"prettier-plugin-packagejson": "^3.0.2",
|
|
81
82
|
"rimraf": "^5.0.10",
|
|
83
|
+
"size-limit": "^13.0.3",
|
|
82
84
|
"tinyglobby": "^0.2.17",
|
|
83
85
|
"typescript": "^5.9.3",
|
|
84
|
-
"vite": "^8.
|
|
86
|
+
"vite": "^8.2.2",
|
|
85
87
|
"vitest": "^4.1.8"
|
|
86
88
|
},
|
|
87
89
|
"peerDependencies": {
|
|
@@ -103,6 +105,7 @@
|
|
|
103
105
|
"build:types": "pkg-utils build --emitDeclarationOnly",
|
|
104
106
|
"clean": "rimraf dist coverage",
|
|
105
107
|
"lint": "eslint . --fix",
|
|
108
|
+
"size": "size-limit",
|
|
106
109
|
"pretest": "pnpm build",
|
|
107
110
|
"test": "vitest",
|
|
108
111
|
"watch": "swc src -d dist --strip-leading-paths --watch"
|