@sanity/codegen 5.7.0-next.9 → 5.7.0
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/bin/run.js +31 -0
- package/dist/_exports/index.js +11 -0
- package/dist/_exports/index.js.map +1 -0
- package/dist/actions/generatedFileWarning.js +15 -0
- package/dist/actions/generatedFileWarning.js.map +1 -0
- package/dist/actions/typegenGenerate.worker.js +54 -0
- package/dist/actions/typegenGenerate.worker.js.map +1 -0
- package/dist/actions/types.js +3 -0
- package/dist/actions/types.js.map +1 -0
- package/dist/casing.js +27 -0
- package/dist/casing.js.map +1 -0
- package/dist/commands/typegen/generate.js +237 -0
- package/dist/commands/typegen/generate.js.map +1 -0
- package/dist/getBabelConfig.js +37 -0
- package/dist/getBabelConfig.js.map +1 -0
- package/dist/index.d.ts +459 -0
- package/dist/readConfig.js +38 -0
- package/dist/readConfig.js.map +1 -0
- package/dist/readSchema.js +14 -0
- package/dist/readSchema.js.map +1 -0
- package/dist/safeParseQuery.js +37 -0
- package/dist/safeParseQuery.js.map +1 -0
- package/dist/typeUtils.js +37 -0
- package/dist/typeUtils.js.map +1 -0
- package/dist/typescript/constants.js +12 -0
- package/dist/typescript/constants.js.map +1 -0
- package/dist/typescript/expressionResolvers.js +356 -0
- package/dist/typescript/expressionResolvers.js.map +1 -0
- package/dist/typescript/findQueriesInPath.js +69 -0
- package/dist/typescript/findQueriesInPath.js.map +1 -0
- package/dist/typescript/findQueriesInSource.js +175 -0
- package/dist/typescript/findQueriesInSource.js.map +1 -0
- package/dist/typescript/helpers.js +86 -0
- package/dist/typescript/helpers.js.map +1 -0
- package/dist/typescript/moduleResolver.js +33 -0
- package/dist/typescript/moduleResolver.js.map +1 -0
- package/dist/typescript/parseSource.js +75 -0
- package/dist/typescript/parseSource.js.map +1 -0
- package/dist/typescript/registerBabel.js +23 -0
- package/dist/typescript/registerBabel.js.map +1 -0
- package/dist/typescript/schemaTypeGenerator.js +323 -0
- package/dist/typescript/schemaTypeGenerator.js.map +1 -0
- package/dist/typescript/typeGenerator.js +240 -0
- package/dist/typescript/typeGenerator.js.map +1 -0
- package/dist/typescript/types.js +31 -0
- package/dist/typescript/types.js.map +1 -0
- package/dist/utils/count.js +6 -0
- package/dist/utils/count.js.map +1 -0
- package/dist/utils/formatPath.js +8 -0
- package/dist/utils/formatPath.js.map +1 -0
- package/dist/utils/getMessage.js +3 -0
- package/dist/utils/getMessage.js.map +1 -0
- package/dist/utils/percent.js +8 -0
- package/dist/utils/percent.js.map +1 -0
- package/oclif.manifest.json +39 -0
- package/package.json +49 -23
- package/lib/index.d.ts +0 -433
- package/lib/index.js +0 -1011
- package/lib/index.js.map +0 -1
package/bin/run.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {execute} from '@oclif/core'
|
|
3
|
+
|
|
4
|
+
const err = '\u001B[31m\u001B[1mERROR:\u001B[22m\u001B[39m '
|
|
5
|
+
const nodeVersionParts = process.version.replace(/^v/i, '').split('.').map(Number)
|
|
6
|
+
|
|
7
|
+
const majorVersion = nodeVersionParts[0]
|
|
8
|
+
const minorVersion = nodeVersionParts[1]
|
|
9
|
+
const patchVersion = nodeVersionParts[2]
|
|
10
|
+
|
|
11
|
+
function isSupportedNodeVersion(major, minor, patch) {
|
|
12
|
+
if (major === 20) {
|
|
13
|
+
if (minor > 19) return true
|
|
14
|
+
if (minor === 19 && patch >= 1) return true
|
|
15
|
+
return false
|
|
16
|
+
}
|
|
17
|
+
if (major === 21) return true
|
|
18
|
+
if (major === 22 && minor >= 12) return true
|
|
19
|
+
if (major > 22) return true
|
|
20
|
+
return false
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (!isSupportedNodeVersion(majorVersion, minorVersion, patchVersion)) {
|
|
24
|
+
console.error(
|
|
25
|
+
`${err}Node.js version >=20.19.1 <22 or >=22.12 required. You are running ${process.version}`,
|
|
26
|
+
)
|
|
27
|
+
console.error('')
|
|
28
|
+
process.exit(1)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
await execute({dir: import.meta.url})
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { configDefinition, readConfig } from '../readConfig.js';
|
|
2
|
+
export { readSchema } from '../readSchema.js';
|
|
3
|
+
export { safeParseQuery } from '../safeParseQuery.js';
|
|
4
|
+
export { findQueriesInPath } from '../typescript/findQueriesInPath.js';
|
|
5
|
+
export { findQueriesInSource } from '../typescript/findQueriesInSource.js';
|
|
6
|
+
export { getResolver } from '../typescript/moduleResolver.js';
|
|
7
|
+
export { registerBabel } from '../typescript/registerBabel.js';
|
|
8
|
+
export { TypeGenerator } from '../typescript/typeGenerator.js';
|
|
9
|
+
export { QueryExtractionError } from '../typescript/types.js';
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export {\n type CodegenConfig,\n configDefinition,\n readConfig,\n type TypeGenConfig,\n} from '../readConfig.js'\nexport {readSchema} from '../readSchema.js'\nexport {safeParseQuery} from '../safeParseQuery.js'\nexport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nexport {findQueriesInSource} from '../typescript/findQueriesInSource.js'\nexport {getResolver} from '../typescript/moduleResolver.js'\nexport {registerBabel} from '../typescript/registerBabel.js'\nexport {\n type GenerateTypesOptions,\n TypeGenerator,\n type TypegenWorkerChannel,\n} from '../typescript/typeGenerator.js'\nexport {\n type EvaluatedModule,\n type EvaluatedQuery,\n type ExtractedModule,\n type ExtractedQuery,\n QueryExtractionError,\n} from '../typescript/types.js'\nexport {type FilterByType, type Get} from '../typeUtils.js'\n"],"names":["configDefinition","readConfig","readSchema","safeParseQuery","findQueriesInPath","findQueriesInSource","getResolver","registerBabel","TypeGenerator","QueryExtractionError"],"mappings":"AAAA,SAEEA,gBAAgB,EAChBC,UAAU,QAEL,mBAAkB;AACzB,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,cAAc,QAAO,uBAAsB;AACnD,SAAQC,iBAAiB,QAAO,qCAAoC;AACpE,SAAQC,mBAAmB,QAAO,uCAAsC;AACxE,SAAQC,WAAW,QAAO,kCAAiC;AAC3D,SAAQC,aAAa,QAAO,iCAAgC;AAC5D,SAEEC,aAAa,QAER,iCAAgC;AACvC,SAKEC,oBAAoB,QACf,yBAAwB"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const generatedFileWarning = `/**
|
|
2
|
+
* ---------------------------------------------------------------------------------
|
|
3
|
+
* This file has been generated by Sanity TypeGen.
|
|
4
|
+
* Command: \`sanity typegen generate\`
|
|
5
|
+
*
|
|
6
|
+
* Any modifications made directly to this file will be overwritten the next time
|
|
7
|
+
* the TypeScript definitions are generated. Please make changes to the Sanity
|
|
8
|
+
* schema definitions and/or GROQ queries if you need to update these types.
|
|
9
|
+
*
|
|
10
|
+
* For more information on how to use Sanity TypeGen, visit the official documentation:
|
|
11
|
+
* https://www.sanity.io/docs/sanity-typegen
|
|
12
|
+
* ---------------------------------------------------------------------------------
|
|
13
|
+
*/\n\n`;
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=generatedFileWarning.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/actions/generatedFileWarning.ts"],"sourcesContent":["export const generatedFileWarning = `/**\n * ---------------------------------------------------------------------------------\n * This file has been generated by Sanity TypeGen.\n * Command: \\`sanity typegen generate\\`\n *\n * Any modifications made directly to this file will be overwritten the next time\n * the TypeScript definitions are generated. Please make changes to the Sanity\n * schema definitions and/or GROQ queries if you need to update these types.\n *\n * For more information on how to use Sanity TypeGen, visit the official documentation:\n * https://www.sanity.io/docs/sanity-typegen\n * ---------------------------------------------------------------------------------\n */\\n\\n`\n"],"names":["generatedFileWarning"],"mappings":"AAAA,OAAO,MAAMA,uBAAuB,CAAC;;;;;;;;;;;;OAY9B,CAAC,CAAA"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { stat } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
4
|
+
import { WorkerChannelReporter } from '@sanity/worker-channels';
|
|
5
|
+
import { readSchema } from '../readSchema.js';
|
|
6
|
+
import { findQueriesInPath } from '../typescript/findQueriesInPath.js';
|
|
7
|
+
import { getResolver } from '../typescript/moduleResolver.js';
|
|
8
|
+
import { registerBabel } from '../typescript/registerBabel.js';
|
|
9
|
+
import { TypeGenerator } from '../typescript/typeGenerator.js';
|
|
10
|
+
if (isMainThread || !parentPort) {
|
|
11
|
+
throw new Error('This module must be run as a worker thread');
|
|
12
|
+
}
|
|
13
|
+
registerBabel();
|
|
14
|
+
async function main({ overloadClientMethods, schemaPath, searchPath, workDir }) {
|
|
15
|
+
const report = WorkerChannelReporter.from(parentPort);
|
|
16
|
+
const fullPath = path.join(workDir, schemaPath);
|
|
17
|
+
try {
|
|
18
|
+
const schemaStats = await stat(fullPath);
|
|
19
|
+
if (!schemaStats.isFile()) {
|
|
20
|
+
throw new Error(`Schema path is not a file: ${schemaPath}`);
|
|
21
|
+
}
|
|
22
|
+
} catch (err) {
|
|
23
|
+
if (err instanceof Error && 'code' in err && err.code === 'ENOENT') {
|
|
24
|
+
// If the user has not provided a specific schema path (eg we're using the default), give some help
|
|
25
|
+
const hint = schemaPath === './schema.json' ? ` - did you run "sanity schema extract"?` : '';
|
|
26
|
+
throw new Error(`Schema file not found: ${fullPath}${hint}`, {
|
|
27
|
+
cause: err
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
throw err;
|
|
31
|
+
}
|
|
32
|
+
const schema = await readSchema(fullPath);
|
|
33
|
+
report.event.loadedSchema();
|
|
34
|
+
const typeGenerator = new TypeGenerator();
|
|
35
|
+
const { files, queries } = findQueriesInPath({
|
|
36
|
+
path: searchPath,
|
|
37
|
+
resolver: getResolver(workDir)
|
|
38
|
+
});
|
|
39
|
+
report.event.typegenStarted({
|
|
40
|
+
expectedFileCount: files.length
|
|
41
|
+
});
|
|
42
|
+
const result = await typeGenerator.generateTypes({
|
|
43
|
+
overloadClientMethods,
|
|
44
|
+
queries,
|
|
45
|
+
reporter: report,
|
|
46
|
+
root: workDir,
|
|
47
|
+
schema,
|
|
48
|
+
schemaPath
|
|
49
|
+
});
|
|
50
|
+
report.event.typegenComplete(result);
|
|
51
|
+
}
|
|
52
|
+
await main(workerData);
|
|
53
|
+
|
|
54
|
+
//# sourceMappingURL=typegenGenerate.worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/actions/typegenGenerate.worker.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport path from 'node:path'\nimport {isMainThread, parentPort, workerData} from 'node:worker_threads'\n\nimport {WorkerChannelReporter} from '@sanity/worker-channels'\n\nimport {readSchema} from '../readSchema.js'\nimport {findQueriesInPath} from '../typescript/findQueriesInPath.js'\nimport {getResolver} from '../typescript/moduleResolver.js'\nimport {registerBabel} from '../typescript/registerBabel.js'\nimport {TypeGenerator} from '../typescript/typeGenerator.js'\nimport {TypegenGenerateTypesWorkerData, TypegenWorkerChannel} from './types.js'\n\nif (isMainThread || !parentPort) {\n throw new Error('This module must be run as a worker thread')\n}\n\nregisterBabel()\n\nasync function main({\n overloadClientMethods,\n schemaPath,\n searchPath,\n workDir,\n}: TypegenGenerateTypesWorkerData) {\n const report = WorkerChannelReporter.from<TypegenWorkerChannel>(parentPort)\n\n const fullPath = path.join(workDir, schemaPath)\n\n try {\n const schemaStats = await stat(fullPath)\n if (!schemaStats.isFile()) {\n throw new Error(`Schema path is not a file: ${schemaPath}`)\n }\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT') {\n // If the user has not provided a specific schema path (eg we're using the default), give some help\n const hint = schemaPath === './schema.json' ? ` - did you run \"sanity schema extract\"?` : ''\n throw new Error(`Schema file not found: ${fullPath}${hint}`, {cause: err})\n }\n throw err\n }\n\n const schema = await readSchema(fullPath)\n\n report.event.loadedSchema()\n\n const typeGenerator = new TypeGenerator()\n\n const {files, queries} = findQueriesInPath({\n path: searchPath,\n resolver: getResolver(workDir),\n })\n report.event.typegenStarted({expectedFileCount: files.length})\n\n const result = await typeGenerator.generateTypes({\n overloadClientMethods,\n queries,\n reporter: report,\n root: workDir,\n schema,\n schemaPath,\n })\n report.event.typegenComplete(result)\n}\n\nawait main(workerData)\n"],"names":["stat","path","isMainThread","parentPort","workerData","WorkerChannelReporter","readSchema","findQueriesInPath","getResolver","registerBabel","TypeGenerator","Error","main","overloadClientMethods","schemaPath","searchPath","workDir","report","from","fullPath","join","schemaStats","isFile","err","code","hint","cause","schema","event","loadedSchema","typeGenerator","files","queries","resolver","typegenStarted","expectedFileCount","length","result","generateTypes","reporter","root","typegenComplete"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,YAAY,EAAEC,UAAU,EAAEC,UAAU,QAAO,sBAAqB;AAExE,SAAQC,qBAAqB,QAAO,0BAAyB;AAE7D,SAAQC,UAAU,QAAO,mBAAkB;AAC3C,SAAQC,iBAAiB,QAAO,qCAAoC;AACpE,SAAQC,WAAW,QAAO,kCAAiC;AAC3D,SAAQC,aAAa,QAAO,iCAAgC;AAC5D,SAAQC,aAAa,QAAO,iCAAgC;AAG5D,IAAIR,gBAAgB,CAACC,YAAY;IAC/B,MAAM,IAAIQ,MAAM;AAClB;AAEAF;AAEA,eAAeG,KAAK,EAClBC,qBAAqB,EACrBC,UAAU,EACVC,UAAU,EACVC,OAAO,EACwB;IAC/B,MAAMC,SAASZ,sBAAsBa,IAAI,CAAuBf;IAEhE,MAAMgB,WAAWlB,KAAKmB,IAAI,CAACJ,SAASF;IAEpC,IAAI;QACF,MAAMO,cAAc,MAAMrB,KAAKmB;QAC/B,IAAI,CAACE,YAAYC,MAAM,IAAI;YACzB,MAAM,IAAIX,MAAM,CAAC,2BAA2B,EAAEG,YAAY;QAC5D;IACF,EAAE,OAAOS,KAAK;QACZ,IAAIA,eAAeZ,SAAS,UAAUY,OAAOA,IAAIC,IAAI,KAAK,UAAU;YAClE,mGAAmG;YACnG,MAAMC,OAAOX,eAAe,kBAAkB,CAAC,uCAAuC,CAAC,GAAG;YAC1F,MAAM,IAAIH,MAAM,CAAC,uBAAuB,EAAEQ,WAAWM,MAAM,EAAE;gBAACC,OAAOH;YAAG;QAC1E;QACA,MAAMA;IACR;IAEA,MAAMI,SAAS,MAAMrB,WAAWa;IAEhCF,OAAOW,KAAK,CAACC,YAAY;IAEzB,MAAMC,gBAAgB,IAAIpB;IAE1B,MAAM,EAACqB,KAAK,EAAEC,OAAO,EAAC,GAAGzB,kBAAkB;QACzCN,MAAMc;QACNkB,UAAUzB,YAAYQ;IACxB;IACAC,OAAOW,KAAK,CAACM,cAAc,CAAC;QAACC,mBAAmBJ,MAAMK,MAAM;IAAA;IAE5D,MAAMC,SAAS,MAAMP,cAAcQ,aAAa,CAAC;QAC/CzB;QACAmB;QACAO,UAAUtB;QACVuB,MAAMxB;QACNW;QACAb;IACF;IACAG,OAAOW,KAAK,CAACa,eAAe,CAACJ;AAC/B;AAEA,MAAMzB,KAAKR"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/actions/types.ts"],"sourcesContent":["import {WorkerChannel} from '@sanity/worker-channels'\n\nimport {type TypegenWorkerChannel as CodegenTypegenWorkerChannel} from '../typescript/typeGenerator.js'\n\nexport interface TypegenGenerateTypesWorkerData {\n schemaPath: string\n searchPath: string | string[]\n workDir: string\n\n overloadClientMethods?: boolean\n}\n\nexport type TypegenWorkerChannel = WorkerChannel.Definition<\n CodegenTypegenWorkerChannel['__definition'] & {\n loadedSchema: WorkerChannel.Event\n typegenComplete: WorkerChannel.Event<{code: string}>\n typegenStarted: WorkerChannel.Event<{expectedFileCount: number}>\n }\n>\n"],"names":[],"mappings":"AAYA,WAMC"}
|
package/dist/casing.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* resultSuffix takes a variable name and appends "result" in the same casing style.
|
|
3
|
+
* Supported: camelCase, PascalCase, snake_case, UPPER_SNAKE.
|
|
4
|
+
* Falls back to camelCase-style suffix when casing is unknown.
|
|
5
|
+
*/ export function resultSuffix(variableName) {
|
|
6
|
+
if (!variableName) return 'result';
|
|
7
|
+
const isUpperSnake = /^[A-Z0-9_]+$/.test(variableName) // VALUE, USER_NAME
|
|
8
|
+
;
|
|
9
|
+
const isSnake = /^[a-z0-9_]+$/.test(variableName) && variableName.includes('_') // user_name
|
|
10
|
+
;
|
|
11
|
+
const isCamel = /^[a-z][A-Za-z0-9]*$/.test(variableName) // userName
|
|
12
|
+
;
|
|
13
|
+
if (isCamel) {
|
|
14
|
+
return `${variableName}Result`;
|
|
15
|
+
}
|
|
16
|
+
if (isUpperSnake) {
|
|
17
|
+
return `${variableName}_RESULT`;
|
|
18
|
+
}
|
|
19
|
+
if (isSnake) {
|
|
20
|
+
return `${variableName}_result`;
|
|
21
|
+
}
|
|
22
|
+
// Fallback: clean weird chars and use camel-style suffix
|
|
23
|
+
const cleaned = variableName.replaceAll(/[^A-Za-z0-9]/g, '');
|
|
24
|
+
return `${cleaned}Result`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=casing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/casing.ts"],"sourcesContent":["/*\n * resultSuffix takes a variable name and appends \"result\" in the same casing style.\n * Supported: camelCase, PascalCase, snake_case, UPPER_SNAKE.\n * Falls back to camelCase-style suffix when casing is unknown.\n */\nexport function resultSuffix(variableName: string): string {\n if (!variableName) return 'result'\n\n const isUpperSnake = /^[A-Z0-9_]+$/.test(variableName) // VALUE, USER_NAME\n const isSnake = /^[a-z0-9_]+$/.test(variableName) && variableName.includes('_') // user_name\n const isCamel = /^[a-z][A-Za-z0-9]*$/.test(variableName) // userName\n\n if (isCamel) {\n return `${variableName}Result`\n }\n\n if (isUpperSnake) {\n return `${variableName}_RESULT`\n }\n\n if (isSnake) {\n return `${variableName}_result`\n }\n\n // Fallback: clean weird chars and use camel-style suffix\n const cleaned = variableName.replaceAll(/[^A-Za-z0-9]/g, '')\n\n return `${cleaned}Result`\n}\n"],"names":["resultSuffix","variableName","isUpperSnake","test","isSnake","includes","isCamel","cleaned","replaceAll"],"mappings":"AAAA;;;;CAIC,GACD,OAAO,SAASA,aAAaC,YAAoB;IAC/C,IAAI,CAACA,cAAc,OAAO;IAE1B,MAAMC,eAAe,eAAeC,IAAI,CAACF,cAAc,mBAAmB;;IAC1E,MAAMG,UAAU,eAAeD,IAAI,CAACF,iBAAiBA,aAAaI,QAAQ,CAAC,KAAK,YAAY;;IAC5F,MAAMC,UAAU,sBAAsBH,IAAI,CAACF,cAAc,WAAW;;IAEpE,IAAIK,SAAS;QACX,OAAO,GAAGL,aAAa,MAAM,CAAC;IAChC;IAEA,IAAIC,cAAc;QAChB,OAAO,GAAGD,aAAa,OAAO,CAAC;IACjC;IAEA,IAAIG,SAAS;QACX,OAAO,GAAGH,aAAa,OAAO,CAAC;IACjC;IAEA,yDAAyD;IACzD,MAAMM,UAAUN,aAAaO,UAAU,CAAC,iBAAiB;IAEzD,OAAO,GAAGD,QAAQ,MAAM,CAAC;AAC3B"}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { mkdir, stat, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
3
|
+
import { env } from 'node:process';
|
|
4
|
+
import { Worker } from 'node:worker_threads';
|
|
5
|
+
import { Flags } from '@oclif/core';
|
|
6
|
+
import { SanityCommand, subdebug } from '@sanity/cli-core';
|
|
7
|
+
import { chalk, spinner } from '@sanity/cli-core/ux';
|
|
8
|
+
import { WorkerChannelReceiver } from '@sanity/worker-channels';
|
|
9
|
+
import { generatedFileWarning } from '../../actions/generatedFileWarning.js';
|
|
10
|
+
import { configDefinition, readConfig } from '../../readConfig.js';
|
|
11
|
+
import { count } from '../../utils/count.js';
|
|
12
|
+
import { formatPath } from '../../utils/formatPath.js';
|
|
13
|
+
import { getMessage } from '../../utils/getMessage.js';
|
|
14
|
+
import { percent } from '../../utils/percent.js';
|
|
15
|
+
const description = `Sanity TypeGen (Beta)
|
|
16
|
+
This command is currently in beta and may undergo significant changes. Feedback is welcome!
|
|
17
|
+
|
|
18
|
+
${chalk.bold('Configuration:')}
|
|
19
|
+
This command can utilize configuration settings defined in a \`sanity-typegen.json\` file. These settings include:
|
|
20
|
+
|
|
21
|
+
- "path": Specifies a glob pattern to locate your TypeScript or JavaScript files.
|
|
22
|
+
Default: "./src/**/*.{ts,tsx,js,jsx}"
|
|
23
|
+
|
|
24
|
+
- "schema": Defines the path to your Sanity schema file. This file should be generated using the \`sanity schema extract\` command.
|
|
25
|
+
Default: "schema.json"
|
|
26
|
+
|
|
27
|
+
- "generates": Indicates the path where the generated TypeScript type definitions will be saved.
|
|
28
|
+
Default: "./sanity.types.ts"
|
|
29
|
+
|
|
30
|
+
The default configuration values listed above are used if not overridden in your \`sanity-typegen.json\` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.
|
|
31
|
+
|
|
32
|
+
${chalk.bold('Note:')}
|
|
33
|
+
- The \`sanity schema extract\` command is a prerequisite for extracting your Sanity Studio schema into a \`schema.json\` file, which is then used by the \`sanity typegen generate\` command to generate type definitions.
|
|
34
|
+
- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.`.trim();
|
|
35
|
+
const debug = subdebug('typegen:generate');
|
|
36
|
+
export class TypegenGenerateCommand extends SanityCommand {
|
|
37
|
+
static description = description;
|
|
38
|
+
static examples = [
|
|
39
|
+
{
|
|
40
|
+
command: '<%= config.bin %> <%= command.id %>',
|
|
41
|
+
description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \`sanity schema extract\` command.`
|
|
42
|
+
}
|
|
43
|
+
];
|
|
44
|
+
static flags = {
|
|
45
|
+
'config-path': Flags.string({
|
|
46
|
+
description: '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.'
|
|
47
|
+
})
|
|
48
|
+
};
|
|
49
|
+
async run() {
|
|
50
|
+
const { flags } = await this.parse(TypegenGenerateCommand);
|
|
51
|
+
const workDir = (await this.getProjectRoot()).directory;
|
|
52
|
+
// TODO: Add telemetry
|
|
53
|
+
// const trace = telemetry.trace(TypesGeneratedTrace)
|
|
54
|
+
// trace.start()
|
|
55
|
+
const spin = spinner({}).start('Loading config…');
|
|
56
|
+
let typegenConfig;
|
|
57
|
+
let configPath;
|
|
58
|
+
let typegenConfigMethod;
|
|
59
|
+
try {
|
|
60
|
+
const result = await this.getConfig(spin, flags['config-path']);
|
|
61
|
+
typegenConfig = result.config;
|
|
62
|
+
configPath = result.path;
|
|
63
|
+
typegenConfigMethod = result.type;
|
|
64
|
+
spin.succeed(`Config loaded from ${formatPath(configPath?.replace(workDir, '.') ?? '')}`);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
debug('error loading config', error);
|
|
67
|
+
spin.fail();
|
|
68
|
+
this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {
|
|
69
|
+
exit: 1
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
const { formatGeneratedCode, generates, overloadClientMethods, path: searchPath, schema: schemaPath } = typegenConfig;
|
|
73
|
+
const outputPath = isAbsolute(typegenConfig.generates) ? typegenConfig.generates : join(workDir, typegenConfig.generates);
|
|
74
|
+
const outputDir = dirname(outputPath);
|
|
75
|
+
await mkdir(outputDir, {
|
|
76
|
+
recursive: true
|
|
77
|
+
});
|
|
78
|
+
const workerPath = new URL('../../actions/typegenGenerate.worker.js', import.meta.url);
|
|
79
|
+
const workerData = {
|
|
80
|
+
overloadClientMethods,
|
|
81
|
+
schemaPath,
|
|
82
|
+
searchPath,
|
|
83
|
+
workDir
|
|
84
|
+
};
|
|
85
|
+
const worker = new Worker(workerPath, {
|
|
86
|
+
env,
|
|
87
|
+
workerData
|
|
88
|
+
});
|
|
89
|
+
const receiver = WorkerChannelReceiver.from(worker);
|
|
90
|
+
try {
|
|
91
|
+
spin.start(`Loading schema…`);
|
|
92
|
+
await receiver.event.loadedSchema();
|
|
93
|
+
spin.succeed(`Schema loaded from ${formatPath(schemaPath ?? '')}`);
|
|
94
|
+
spin.start('Generating schema types…');
|
|
95
|
+
const { expectedFileCount } = await receiver.event.typegenStarted();
|
|
96
|
+
const { schemaTypeDeclarations } = await receiver.event.generatedSchemaTypes();
|
|
97
|
+
const schemaTypesCount = schemaTypeDeclarations.length;
|
|
98
|
+
spin.succeed(`Generated ${count(schemaTypesCount, 'schema types')}`);
|
|
99
|
+
spin.start('Generating query types…');
|
|
100
|
+
let queriesCount = 0;
|
|
101
|
+
let evaluatedFiles = 0;
|
|
102
|
+
let filesWithErrors = 0;
|
|
103
|
+
let queryFilesCount = 0;
|
|
104
|
+
let typeNodesGenerated = 0;
|
|
105
|
+
let unknownTypeNodesGenerated = 0;
|
|
106
|
+
let emptyUnionTypeNodesGenerated = 0;
|
|
107
|
+
for await (const { errors, queries } of receiver.stream.evaluatedModules()){
|
|
108
|
+
evaluatedFiles++;
|
|
109
|
+
queriesCount += queries.length;
|
|
110
|
+
queryFilesCount += queries.length > 0 ? 1 : 0;
|
|
111
|
+
filesWithErrors += errors.length > 0 ? 1 : 0;
|
|
112
|
+
for (const { stats } of queries){
|
|
113
|
+
typeNodesGenerated += stats.allTypes;
|
|
114
|
+
unknownTypeNodesGenerated += stats.unknownTypes;
|
|
115
|
+
emptyUnionTypeNodesGenerated += stats.emptyUnions;
|
|
116
|
+
}
|
|
117
|
+
for (const error of errors){
|
|
118
|
+
spin.fail(getMessage(error));
|
|
119
|
+
}
|
|
120
|
+
spin.text = `Generating query types… (${percent(evaluatedFiles / expectedFileCount)})\n` + ` └─ Processed ${count(evaluatedFiles)} of ${count(expectedFileCount, 'files')}. ` + `Found ${count(queriesCount, 'queries', 'query')} from ${count(queryFilesCount, 'files')}.`;
|
|
121
|
+
}
|
|
122
|
+
const result = await receiver.event.typegenComplete();
|
|
123
|
+
const code = `${generatedFileWarning}${result.code}`;
|
|
124
|
+
await writeFile(outputPath, code);
|
|
125
|
+
spin.succeed(`Generated ${count(queriesCount, 'query types')} from ${count(queryFilesCount, 'files')} out of ${count(evaluatedFiles, 'scanned files')}`);
|
|
126
|
+
if (formatGeneratedCode) {
|
|
127
|
+
spin.start(`Formatting generated types with prettier…`);
|
|
128
|
+
try {
|
|
129
|
+
const prettier = await import('prettier');
|
|
130
|
+
const prettierConfig = await prettier.resolveConfig(outputPath);
|
|
131
|
+
const formattedCode = await prettier.format(code, {
|
|
132
|
+
...prettierConfig,
|
|
133
|
+
parser: 'typescript'
|
|
134
|
+
});
|
|
135
|
+
await writeFile(outputPath, formattedCode);
|
|
136
|
+
spin.succeed('Formatted generated types with prettier');
|
|
137
|
+
} catch (err) {
|
|
138
|
+
spin.warn(`Failed to format generated types with prettier: ${getMessage(err)}`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
debug('trace', {
|
|
142
|
+
configMethod: typegenConfigMethod,
|
|
143
|
+
configOverloadClientMethods: overloadClientMethods,
|
|
144
|
+
emptyUnionTypeNodesGenerated,
|
|
145
|
+
filesWithErrors,
|
|
146
|
+
outputSize: Buffer.byteLength(result.code),
|
|
147
|
+
queriesCount,
|
|
148
|
+
queryFilesCount,
|
|
149
|
+
schemaTypesCount,
|
|
150
|
+
typeNodesGenerated,
|
|
151
|
+
unknownTypeNodesGenerated,
|
|
152
|
+
unknownTypeNodesRatio: typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0
|
|
153
|
+
});
|
|
154
|
+
// trace.log({
|
|
155
|
+
// configMethod: typegenConfigMethod,
|
|
156
|
+
// configOverloadClientMethods: overloadClientMethods,
|
|
157
|
+
// emptyUnionTypeNodesGenerated,
|
|
158
|
+
// filesWithErrors,
|
|
159
|
+
// outputSize: Buffer.byteLength(result.code),
|
|
160
|
+
// queriesCount,
|
|
161
|
+
// queryFilesCount,
|
|
162
|
+
// schemaTypesCount,
|
|
163
|
+
// typeNodesGenerated,
|
|
164
|
+
// unknownTypeNodesGenerated,
|
|
165
|
+
// unknownTypeNodesRatio:
|
|
166
|
+
// typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,
|
|
167
|
+
// })
|
|
168
|
+
if (filesWithErrors > 0) {
|
|
169
|
+
spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`);
|
|
170
|
+
}
|
|
171
|
+
spin.succeed(`Successfully generated types to ${formatPath(generates)}`);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
// trace.error(err)
|
|
174
|
+
debug('error generating types', err);
|
|
175
|
+
this.error(err instanceof Error ? err.message : 'Unknown error', {
|
|
176
|
+
exit: 1
|
|
177
|
+
});
|
|
178
|
+
} finally{
|
|
179
|
+
receiver.unsubscribe();
|
|
180
|
+
// trace.complete()
|
|
181
|
+
await worker.terminate();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
async getConfig(spin, configPath) {
|
|
185
|
+
const rootDir = await this.getProjectRoot();
|
|
186
|
+
const config = await this.getCliConfig();
|
|
187
|
+
// check if the legacy config exist
|
|
188
|
+
const legacyConfigPath = configPath || 'sanity-typegen.json';
|
|
189
|
+
let hasLegacyConfig = false;
|
|
190
|
+
try {
|
|
191
|
+
const file = await stat(legacyConfigPath);
|
|
192
|
+
hasLegacyConfig = file.isFile();
|
|
193
|
+
} catch (err) {
|
|
194
|
+
if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {
|
|
195
|
+
throw new Error(`Typegen config file not found: ${configPath}`, {
|
|
196
|
+
cause: err
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {
|
|
200
|
+
throw new Error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {
|
|
201
|
+
cause: err
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// we have both legacy and cli config with typegen
|
|
206
|
+
if (config?.typegen && hasLegacyConfig) {
|
|
207
|
+
spin.warn(chalk.yellow(`You've specified typegen in your Sanity CLI config, but also have a typegen config.
|
|
208
|
+
|
|
209
|
+
The config from the Sanity CLI config is used.
|
|
210
|
+
`));
|
|
211
|
+
return {
|
|
212
|
+
config: configDefinition.parse(config.typegen || {}),
|
|
213
|
+
path: rootDir.path,
|
|
214
|
+
type: 'cli'
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
// we only have legacy typegen config
|
|
218
|
+
if (hasLegacyConfig) {
|
|
219
|
+
spin.warn(chalk.yellow(`The separate typegen config has been deprecated. Use \`typegen\` in the sanity CLI config instead.
|
|
220
|
+
|
|
221
|
+
See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`));
|
|
222
|
+
return {
|
|
223
|
+
config: await readConfig(legacyConfigPath),
|
|
224
|
+
path: legacyConfigPath,
|
|
225
|
+
type: 'legacy'
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
// we only have cli config
|
|
229
|
+
return {
|
|
230
|
+
config: configDefinition.parse(config.typegen || {}),
|
|
231
|
+
path: rootDir.path,
|
|
232
|
+
type: 'cli'
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
//# sourceMappingURL=generate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/typegen/generate.ts"],"sourcesContent":["import {mkdir, stat, writeFile} from 'node:fs/promises'\nimport {dirname, isAbsolute, join} from 'node:path'\nimport {env} from 'node:process'\nimport {Worker} from 'node:worker_threads'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand, subdebug} from '@sanity/cli-core'\nimport {chalk, spinner} from '@sanity/cli-core/ux'\nimport {WorkerChannelReceiver} from '@sanity/worker-channels'\n\nimport {generatedFileWarning} from '../../actions/generatedFileWarning.js'\nimport {\n type TypegenGenerateTypesWorkerData,\n type TypegenWorkerChannel,\n} from '../../actions/types.js'\nimport {configDefinition, readConfig, type TypeGenConfig} from '../../readConfig.js'\nimport {count} from '../../utils/count.js'\nimport {formatPath} from '../../utils/formatPath.js'\nimport {getMessage} from '../../utils/getMessage.js'\nimport {percent} from '../../utils/percent.js'\n\nconst description = `Sanity TypeGen (Beta)\nThis command is currently in beta and may undergo significant changes. Feedback is welcome!\n\n${chalk.bold('Configuration:')}\nThis command can utilize configuration settings defined in a \\`sanity-typegen.json\\` file. These settings include:\n\n- \"path\": Specifies a glob pattern to locate your TypeScript or JavaScript files.\n Default: \"./src/**/*.{ts,tsx,js,jsx}\"\n\n- \"schema\": Defines the path to your Sanity schema file. This file should be generated using the \\`sanity schema extract\\` command.\n Default: \"schema.json\"\n\n- \"generates\": Indicates the path where the generated TypeScript type definitions will be saved.\n Default: \"./sanity.types.ts\"\n\nThe default configuration values listed above are used if not overridden in your \\`sanity-typegen.json\\` configuration file. To customize the behavior of the type generation, adjust these properties in the configuration file according to your project's needs.\n\n${chalk.bold('Note:')}\n- The \\`sanity schema extract\\` command is a prerequisite for extracting your Sanity Studio schema into a \\`schema.json\\` file, which is then used by the \\`sanity typegen generate\\` command to generate type definitions.\n- While this tool is in beta, we encourage you to experiment with these configurations and provide feedback to help improve its functionality and usability.`.trim()\n\nconst debug = subdebug('typegen:generate')\n\nexport class TypegenGenerateCommand extends SanityCommand<typeof TypegenGenerateCommand> {\n static override description = description\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: `Generate TypeScript type definitions from a Sanity Studio schema extracted using the \\`sanity schema extract\\` command.`,\n },\n ]\n\n static override flags = {\n 'config-path': Flags.string({\n description:\n '[Default: sanity-typegen.json] Specifies the path to the typegen configuration file. This file should be a JSON file that contains settings for the type generation process.',\n }),\n }\n\n public async run() {\n const {flags} = await this.parse(TypegenGenerateCommand)\n const workDir = (await this.getProjectRoot()).directory\n\n // TODO: Add telemetry\n // const trace = telemetry.trace(TypesGeneratedTrace)\n // trace.start()\n\n const spin = spinner({}).start('Loading config…')\n\n let typegenConfig: TypeGenConfig\n let configPath: string | undefined\n let typegenConfigMethod: 'cli' | 'legacy'\n\n try {\n const result = await this.getConfig(spin, flags['config-path'])\n typegenConfig = result.config\n configPath = result.path\n typegenConfigMethod = result.type\n\n spin.succeed(`Config loaded from ${formatPath(configPath?.replace(workDir, '.') ?? '')}`)\n } catch (error) {\n debug('error loading config', error)\n spin.fail()\n this.error(`${error instanceof Error ? error.message : 'Unknown error'}`, {\n exit: 1,\n })\n }\n\n const {\n formatGeneratedCode,\n generates,\n overloadClientMethods,\n path: searchPath,\n schema: schemaPath,\n } = typegenConfig\n\n const outputPath = isAbsolute(typegenConfig.generates)\n ? typegenConfig.generates\n : join(workDir, typegenConfig.generates)\n\n const outputDir = dirname(outputPath)\n await mkdir(outputDir, {recursive: true})\n\n const workerPath = new URL('../../actions/typegenGenerate.worker.js', import.meta.url)\n const workerData: TypegenGenerateTypesWorkerData = {\n overloadClientMethods,\n schemaPath,\n searchPath,\n workDir,\n }\n\n const worker = new Worker(workerPath, {env, workerData})\n const receiver = WorkerChannelReceiver.from<TypegenWorkerChannel>(worker)\n\n try {\n spin.start(`Loading schema…`)\n await receiver.event.loadedSchema()\n spin.succeed(`Schema loaded from ${formatPath(schemaPath ?? '')}`)\n\n spin.start('Generating schema types…')\n const {expectedFileCount} = await receiver.event.typegenStarted()\n const {schemaTypeDeclarations} = await receiver.event.generatedSchemaTypes()\n const schemaTypesCount = schemaTypeDeclarations.length\n spin.succeed(`Generated ${count(schemaTypesCount, 'schema types')}`)\n\n spin.start('Generating query types…')\n let queriesCount = 0\n let evaluatedFiles = 0\n let filesWithErrors = 0\n let queryFilesCount = 0\n let typeNodesGenerated = 0\n let unknownTypeNodesGenerated = 0\n let emptyUnionTypeNodesGenerated = 0\n\n for await (const {errors, queries} of receiver.stream.evaluatedModules()) {\n evaluatedFiles++\n queriesCount += queries.length\n queryFilesCount += queries.length > 0 ? 1 : 0\n filesWithErrors += errors.length > 0 ? 1 : 0\n\n for (const {stats} of queries) {\n typeNodesGenerated += stats.allTypes\n unknownTypeNodesGenerated += stats.unknownTypes\n emptyUnionTypeNodesGenerated += stats.emptyUnions\n }\n\n for (const error of errors) {\n spin.fail(getMessage(error))\n }\n\n spin.text =\n `Generating query types… (${percent(evaluatedFiles / expectedFileCount)})\\n` +\n ` └─ Processed ${count(evaluatedFiles)} of ${count(expectedFileCount, 'files')}. ` +\n `Found ${count(queriesCount, 'queries', 'query')} from ${count(queryFilesCount, 'files')}.`\n }\n\n const result = await receiver.event.typegenComplete()\n const code = `${generatedFileWarning}${result.code}`\n await writeFile(outputPath, code)\n\n spin.succeed(\n `Generated ${count(queriesCount, 'query types')} from ${count(queryFilesCount, 'files')} out of ${count(evaluatedFiles, 'scanned files')}`,\n )\n\n if (formatGeneratedCode) {\n spin.start(`Formatting generated types with prettier…`)\n\n try {\n const prettier = await import('prettier')\n const prettierConfig = await prettier.resolveConfig(outputPath)\n const formattedCode = await prettier.format(code, {\n ...prettierConfig,\n parser: 'typescript' as const,\n })\n await writeFile(outputPath, formattedCode)\n\n spin.succeed('Formatted generated types with prettier')\n } catch (err) {\n spin.warn(`Failed to format generated types with prettier: ${getMessage(err)}`)\n }\n }\n\n debug('trace', {\n configMethod: typegenConfigMethod,\n configOverloadClientMethods: overloadClientMethods,\n emptyUnionTypeNodesGenerated,\n filesWithErrors,\n outputSize: Buffer.byteLength(result.code),\n queriesCount,\n queryFilesCount,\n schemaTypesCount,\n typeNodesGenerated,\n unknownTypeNodesGenerated,\n unknownTypeNodesRatio:\n typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n })\n // trace.log({\n // configMethod: typegenConfigMethod,\n // configOverloadClientMethods: overloadClientMethods,\n // emptyUnionTypeNodesGenerated,\n // filesWithErrors,\n // outputSize: Buffer.byteLength(result.code),\n // queriesCount,\n // queryFilesCount,\n // schemaTypesCount,\n // typeNodesGenerated,\n // unknownTypeNodesGenerated,\n // unknownTypeNodesRatio:\n // typeNodesGenerated > 0 ? unknownTypeNodesGenerated / typeNodesGenerated : 0,\n // })\n\n if (filesWithErrors > 0) {\n spin.warn(`Encountered errors in ${count(filesWithErrors, 'files')} while generating types`)\n }\n\n spin.succeed(`Successfully generated types to ${formatPath(generates)}`)\n } catch (err) {\n // trace.error(err)\n debug('error generating types', err)\n this.error(err instanceof Error ? err.message : 'Unknown error', {exit: 1})\n } finally {\n receiver.unsubscribe()\n // trace.complete()\n await worker.terminate()\n }\n }\n\n private async getConfig(\n spin: ReturnType<typeof spinner>,\n configPath?: string,\n ): Promise<{config: TypeGenConfig; path?: string; type: 'cli' | 'legacy'}> {\n const rootDir = await this.getProjectRoot()\n const config = await this.getCliConfig()\n\n // check if the legacy config exist\n const legacyConfigPath = configPath || 'sanity-typegen.json'\n let hasLegacyConfig = false\n try {\n const file = await stat(legacyConfigPath)\n hasLegacyConfig = file.isFile()\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT' && configPath) {\n throw new Error(`Typegen config file not found: ${configPath}`, {cause: err})\n }\n\n if (err instanceof Error && 'code' in err && err.code !== 'ENOENT') {\n throw new Error(`Error when checking if typegen config file exists: ${legacyConfigPath}`, {\n cause: err,\n })\n }\n }\n\n // we have both legacy and cli config with typegen\n if (config?.typegen && hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `You've specified typegen in your Sanity CLI config, but also have a typegen config.\n\n The config from the Sanity CLI config is used.\n `,\n ),\n )\n\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n }\n }\n\n // we only have legacy typegen config\n if (hasLegacyConfig) {\n spin.warn(\n chalk.yellow(\n `The separate typegen config has been deprecated. Use \\`typegen\\` in the sanity CLI config instead.\n\n See: https://www.sanity.io/docs/help/configuring-typegen-in-sanity-cli-config`,\n ),\n )\n return {\n config: await readConfig(legacyConfigPath),\n path: legacyConfigPath,\n type: 'legacy',\n }\n }\n\n // we only have cli config\n return {\n config: configDefinition.parse(config.typegen || {}),\n path: rootDir.path,\n type: 'cli',\n }\n }\n}\n"],"names":["mkdir","stat","writeFile","dirname","isAbsolute","join","env","Worker","Flags","SanityCommand","subdebug","chalk","spinner","WorkerChannelReceiver","generatedFileWarning","configDefinition","readConfig","count","formatPath","getMessage","percent","description","bold","trim","debug","TypegenGenerateCommand","examples","command","flags","string","run","parse","workDir","getProjectRoot","directory","spin","start","typegenConfig","configPath","typegenConfigMethod","result","getConfig","config","path","type","succeed","replace","error","fail","Error","message","exit","formatGeneratedCode","generates","overloadClientMethods","searchPath","schema","schemaPath","outputPath","outputDir","recursive","workerPath","URL","url","workerData","worker","receiver","from","event","loadedSchema","expectedFileCount","typegenStarted","schemaTypeDeclarations","generatedSchemaTypes","schemaTypesCount","length","queriesCount","evaluatedFiles","filesWithErrors","queryFilesCount","typeNodesGenerated","unknownTypeNodesGenerated","emptyUnionTypeNodesGenerated","errors","queries","stream","evaluatedModules","stats","allTypes","unknownTypes","emptyUnions","text","typegenComplete","code","prettier","prettierConfig","resolveConfig","formattedCode","format","parser","err","warn","configMethod","configOverloadClientMethods","outputSize","Buffer","byteLength","unknownTypeNodesRatio","unsubscribe","terminate","rootDir","getCliConfig","legacyConfigPath","hasLegacyConfig","file","isFile","cause","typegen","yellow"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,IAAI,EAAEC,SAAS,QAAO,mBAAkB;AACvD,SAAQC,OAAO,EAAEC,UAAU,EAAEC,IAAI,QAAO,YAAW;AACnD,SAAQC,GAAG,QAAO,eAAc;AAChC,SAAQC,MAAM,QAAO,sBAAqB;AAE1C,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACxD,SAAQC,KAAK,EAAEC,OAAO,QAAO,sBAAqB;AAClD,SAAQC,qBAAqB,QAAO,0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|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
5
|
+
/**
|
|
6
|
+
* Because of bundlers and compilers, knowing the exact path the babel configuration will be
|
|
7
|
+
* located at post - build is not always trivial. We traverse from the current directory upwards
|
|
8
|
+
* until we find the first `babel.config.json` and use that path.
|
|
9
|
+
*
|
|
10
|
+
* @param path - The path to start looking for the babel configuration
|
|
11
|
+
* @returns The path to the `babel.config.json` file
|
|
12
|
+
* @internal
|
|
13
|
+
*/ function findBabelConfig(path) {
|
|
14
|
+
const configPath = join(path, 'babel.config.json');
|
|
15
|
+
if (existsSync(configPath)) {
|
|
16
|
+
return configPath;
|
|
17
|
+
}
|
|
18
|
+
const parent = resolve(join(path, '..'));
|
|
19
|
+
if (parent && parent !== path) {
|
|
20
|
+
return findBabelConfig(parent);
|
|
21
|
+
}
|
|
22
|
+
throw new Error('Could not find `babel.config.json` in @sanity/codegen');
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Get the default babel configuration for `@sanity/codegen`
|
|
26
|
+
*
|
|
27
|
+
* @param path - The path to start looking for the babel configuration. Defaults to `__dirname`
|
|
28
|
+
* @returns A babel configuration object
|
|
29
|
+
* @internal
|
|
30
|
+
*/ export function getBabelConfig(path) {
|
|
31
|
+
const configPath = findBabelConfig(path || __dirname);
|
|
32
|
+
return {
|
|
33
|
+
extends: configPath
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
//# sourceMappingURL=getBabelConfig.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/getBabelConfig.ts"],"sourcesContent":["import {existsSync} from 'node:fs'\nimport {dirname, join, resolve} from 'node:path'\nimport {fileURLToPath} from 'node:url'\n\nimport {type TransformOptions} from '@babel/core'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\n/**\n * Because of bundlers and compilers, knowing the exact path the babel configuration will be\n * located at post - build is not always trivial. We traverse from the current directory upwards\n * until we find the first `babel.config.json` and use that path.\n *\n * @param path - The path to start looking for the babel configuration\n * @returns The path to the `babel.config.json` file\n * @internal\n */\nfunction findBabelConfig(path: string): string {\n const configPath = join(path, 'babel.config.json')\n if (existsSync(configPath)) {\n return configPath\n }\n\n const parent = resolve(join(path, '..'))\n if (parent && parent !== path) {\n return findBabelConfig(parent)\n }\n\n throw new Error('Could not find `babel.config.json` in @sanity/codegen')\n}\n\n/**\n * Get the default babel configuration for `@sanity/codegen`\n *\n * @param path - The path to start looking for the babel configuration. Defaults to `__dirname`\n * @returns A babel configuration object\n * @internal\n */\nexport function getBabelConfig(path?: string): TransformOptions {\n const configPath = findBabelConfig(path || __dirname)\n return {extends: configPath}\n}\n"],"names":["existsSync","dirname","join","resolve","fileURLToPath","__dirname","url","findBabelConfig","path","configPath","parent","Error","getBabelConfig","extends"],"mappings":"AAAA,SAAQA,UAAU,QAAO,UAAS;AAClC,SAAQC,OAAO,EAAEC,IAAI,EAAEC,OAAO,QAAO,YAAW;AAChD,SAAQC,aAAa,QAAO,WAAU;AAItC,MAAMC,YAAYJ,QAAQG,cAAc,YAAYE,GAAG;AAEvD;;;;;;;;CAQC,GACD,SAASC,gBAAgBC,IAAY;IACnC,MAAMC,aAAaP,KAAKM,MAAM;IAC9B,IAAIR,WAAWS,aAAa;QAC1B,OAAOA;IACT;IAEA,MAAMC,SAASP,QAAQD,KAAKM,MAAM;IAClC,IAAIE,UAAUA,WAAWF,MAAM;QAC7B,OAAOD,gBAAgBG;IACzB;IAEA,MAAM,IAAIC,MAAM;AAClB;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,eAAeJ,IAAa;IAC1C,MAAMC,aAAaF,gBAAgBC,QAAQH;IAC3C,OAAO;QAACQ,SAASJ;IAAU;AAC7B"}
|