@sanity/cli 7.11.0 → 7.12.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.
Files changed (171) hide show
  1. package/dist/actions/build/buildApp.js +10 -7
  2. package/dist/actions/build/buildApp.js.map +1 -1
  3. package/dist/actions/build/buildStudio.js +9 -6
  4. package/dist/actions/build/buildStudio.js.map +1 -1
  5. package/dist/actions/build/types.js.map +1 -1
  6. package/dist/actions/deploy/deployApp.js +205 -162
  7. package/dist/actions/deploy/deployApp.js.map +1 -1
  8. package/dist/actions/deploy/deployChecks.js +1 -1
  9. package/dist/actions/deploy/deployChecks.js.map +1 -1
  10. package/dist/actions/deploy/deployStudio.js +126 -87
  11. package/dist/actions/deploy/deployStudio.js.map +1 -1
  12. package/dist/actions/deploy/resolveDeployTarget.js +5 -9
  13. package/dist/actions/deploy/resolveDeployTarget.js.map +1 -1
  14. package/dist/actions/dev/devAction.js +1 -2
  15. package/dist/actions/dev/devAction.js.map +1 -1
  16. package/dist/actions/dev/servers/getDevServerConfig.js +8 -2
  17. package/dist/actions/dev/servers/getDevServerConfig.js.map +1 -1
  18. package/dist/actions/init/bootstrapLocalTemplate.js +18 -9
  19. package/dist/actions/init/bootstrapLocalTemplate.js.map +1 -1
  20. package/dist/actions/init/createAppCliConfig.js.map +1 -1
  21. package/dist/actions/init/createCliConfig.js.map +1 -1
  22. package/dist/commands/backups/disable.js +4 -4
  23. package/dist/commands/backups/disable.js.map +1 -1
  24. package/dist/commands/backups/download.js +7 -7
  25. package/dist/commands/backups/download.js.map +1 -1
  26. package/dist/commands/backups/enable.js +4 -4
  27. package/dist/commands/backups/enable.js.map +1 -1
  28. package/dist/commands/backups/list.js +7 -7
  29. package/dist/commands/backups/list.js.map +1 -1
  30. package/dist/commands/codemod.js +5 -5
  31. package/dist/commands/codemod.js.map +1 -1
  32. package/dist/commands/cors/add.js +1 -1
  33. package/dist/commands/cors/add.js.map +1 -1
  34. package/dist/commands/cors/delete.js +4 -4
  35. package/dist/commands/cors/delete.js.map +1 -1
  36. package/dist/commands/cors/list.js +2 -2
  37. package/dist/commands/cors/list.js.map +1 -1
  38. package/dist/commands/datasets/alias/create.js +5 -5
  39. package/dist/commands/datasets/alias/create.js.map +1 -1
  40. package/dist/commands/datasets/alias/delete.js +2 -2
  41. package/dist/commands/datasets/alias/delete.js.map +1 -1
  42. package/dist/commands/datasets/alias/link.js +5 -5
  43. package/dist/commands/datasets/alias/link.js.map +1 -1
  44. package/dist/commands/datasets/alias/unlink.js +3 -3
  45. package/dist/commands/datasets/alias/unlink.js.map +1 -1
  46. package/dist/commands/datasets/copy.js +7 -7
  47. package/dist/commands/datasets/copy.js.map +1 -1
  48. package/dist/commands/datasets/create.js +3 -3
  49. package/dist/commands/datasets/create.js.map +1 -1
  50. package/dist/commands/datasets/delete.js +2 -2
  51. package/dist/commands/datasets/delete.js.map +1 -1
  52. package/dist/commands/datasets/embeddings/disable.js +3 -3
  53. package/dist/commands/datasets/embeddings/disable.js.map +1 -1
  54. package/dist/commands/datasets/embeddings/enable.js +5 -5
  55. package/dist/commands/datasets/embeddings/enable.js.map +1 -1
  56. package/dist/commands/datasets/embeddings/status.js +3 -3
  57. package/dist/commands/datasets/embeddings/status.js.map +1 -1
  58. package/dist/commands/datasets/export.js +6 -6
  59. package/dist/commands/datasets/export.js.map +1 -1
  60. package/dist/commands/datasets/import.js +3 -3
  61. package/dist/commands/datasets/import.js.map +1 -1
  62. package/dist/commands/datasets/list.js +2 -2
  63. package/dist/commands/datasets/list.js.map +1 -1
  64. package/dist/commands/datasets/visibility/get.js +2 -2
  65. package/dist/commands/datasets/visibility/get.js.map +1 -1
  66. package/dist/commands/datasets/visibility/set.js +3 -3
  67. package/dist/commands/datasets/visibility/set.js.map +1 -1
  68. package/dist/commands/deploy.js +2 -2
  69. package/dist/commands/deploy.js.map +1 -1
  70. package/dist/commands/dev.js +2 -2
  71. package/dist/commands/dev.js.map +1 -1
  72. package/dist/commands/docs/read.js +1 -1
  73. package/dist/commands/docs/read.js.map +1 -1
  74. package/dist/commands/docs/search.js +3 -3
  75. package/dist/commands/docs/search.js.map +1 -1
  76. package/dist/commands/doctor.js +3 -3
  77. package/dist/commands/doctor.js.map +1 -1
  78. package/dist/commands/documents/create.js +3 -3
  79. package/dist/commands/documents/create.js.map +1 -1
  80. package/dist/commands/documents/delete.js +3 -3
  81. package/dist/commands/documents/delete.js.map +1 -1
  82. package/dist/commands/documents/get.js +2 -2
  83. package/dist/commands/documents/get.js.map +1 -1
  84. package/dist/commands/documents/query.js +2 -2
  85. package/dist/commands/documents/query.js.map +1 -1
  86. package/dist/commands/documents/validate.js +3 -3
  87. package/dist/commands/documents/validate.js.map +1 -1
  88. package/dist/commands/graphql/deploy.js +13 -13
  89. package/dist/commands/graphql/deploy.js.map +1 -1
  90. package/dist/commands/graphql/list.js +2 -2
  91. package/dist/commands/graphql/list.js.map +1 -1
  92. package/dist/commands/graphql/undeploy.js +2 -2
  93. package/dist/commands/graphql/undeploy.js.map +1 -1
  94. package/dist/commands/hooks/attempt.js +2 -2
  95. package/dist/commands/hooks/attempt.js.map +1 -1
  96. package/dist/commands/hooks/create.js +3 -3
  97. package/dist/commands/hooks/create.js.map +1 -1
  98. package/dist/commands/hooks/delete.js +4 -4
  99. package/dist/commands/hooks/delete.js.map +1 -1
  100. package/dist/commands/hooks/list.js +2 -2
  101. package/dist/commands/hooks/list.js.map +1 -1
  102. package/dist/commands/hooks/logs.js +5 -5
  103. package/dist/commands/hooks/logs.js.map +1 -1
  104. package/dist/commands/login.js +2 -2
  105. package/dist/commands/login.js.map +1 -1
  106. package/dist/commands/logout.js +2 -2
  107. package/dist/commands/logout.js.map +1 -1
  108. package/dist/commands/manifest/extract.js +3 -3
  109. package/dist/commands/manifest/extract.js.map +1 -1
  110. package/dist/commands/mcp/configure.js +4 -4
  111. package/dist/commands/mcp/configure.js.map +1 -1
  112. package/dist/commands/media/create-aspect.js +3 -3
  113. package/dist/commands/media/create-aspect.js.map +1 -1
  114. package/dist/commands/media/delete-aspect.js +1 -1
  115. package/dist/commands/media/delete-aspect.js.map +1 -1
  116. package/dist/commands/media/deploy-aspect.js +4 -4
  117. package/dist/commands/media/deploy-aspect.js.map +1 -1
  118. package/dist/commands/media/export.js +7 -7
  119. package/dist/commands/media/export.js.map +1 -1
  120. package/dist/commands/media/import.js +6 -6
  121. package/dist/commands/media/import.js.map +1 -1
  122. package/dist/commands/migrations/create.js +4 -4
  123. package/dist/commands/migrations/create.js.map +1 -1
  124. package/dist/commands/migrations/list.js +2 -2
  125. package/dist/commands/migrations/list.js.map +1 -1
  126. package/dist/commands/migrations/run.js +14 -14
  127. package/dist/commands/migrations/run.js.map +1 -1
  128. package/dist/commands/openapi/get.js +3 -3
  129. package/dist/commands/openapi/get.js.map +1 -1
  130. package/dist/commands/openapi/list.js +2 -2
  131. package/dist/commands/openapi/list.js.map +1 -1
  132. package/dist/commands/organizations/create.js +5 -5
  133. package/dist/commands/organizations/create.js.map +1 -1
  134. package/dist/commands/organizations/delete.js +6 -6
  135. package/dist/commands/organizations/delete.js.map +1 -1
  136. package/dist/commands/organizations/get.js +3 -3
  137. package/dist/commands/organizations/get.js.map +1 -1
  138. package/dist/commands/organizations/list.js +2 -2
  139. package/dist/commands/organizations/list.js.map +1 -1
  140. package/dist/commands/organizations/update.js +6 -6
  141. package/dist/commands/organizations/update.js.map +1 -1
  142. package/dist/commands/preview.js +2 -2
  143. package/dist/commands/preview.js.map +1 -1
  144. package/dist/commands/projects/create.js +2 -2
  145. package/dist/commands/projects/create.js.map +1 -1
  146. package/dist/commands/projects/list.js +2 -2
  147. package/dist/commands/projects/list.js.map +1 -1
  148. package/dist/commands/schemas/delete.js +2 -2
  149. package/dist/commands/schemas/delete.js.map +1 -1
  150. package/dist/commands/schemas/deploy.js +2 -2
  151. package/dist/commands/schemas/deploy.js.map +1 -1
  152. package/dist/commands/schemas/list.js +1 -1
  153. package/dist/commands/schemas/list.js.map +1 -1
  154. package/dist/commands/schemas/validate.js +2 -1
  155. package/dist/commands/schemas/validate.js.map +1 -1
  156. package/dist/commands/skills/install.js +2 -2
  157. package/dist/commands/skills/install.js.map +1 -1
  158. package/dist/commands/telemetry/disable.js +2 -2
  159. package/dist/commands/telemetry/disable.js.map +1 -1
  160. package/dist/commands/telemetry/enable.js +2 -2
  161. package/dist/commands/telemetry/enable.js.map +1 -1
  162. package/dist/commands/tokens/create.js +2 -2
  163. package/dist/commands/tokens/create.js.map +1 -1
  164. package/dist/commands/tokens/delete.js +2 -2
  165. package/dist/commands/tokens/delete.js.map +1 -1
  166. package/dist/commands/tokens/list.js +2 -2
  167. package/dist/commands/tokens/list.js.map +1 -1
  168. package/dist/commands/users/invite.js +3 -3
  169. package/dist/commands/users/invite.js.map +1 -1
  170. package/oclif.manifest.json +331 -331
  171. package/package.json +5 -5
@@ -124,7 +124,7 @@ export class CreateDocumentCommand extends SanityCommand {
124
124
  const err = error;
125
125
  createDocumentDebug(`Error creating documents from file ${file}`, err);
126
126
  this.error(`Failed to create documents: ${err.message}`, {
127
- exit: 1
127
+ exit: exitCodes.RUNTIME_ERROR
128
128
  });
129
129
  }
130
130
  }
@@ -193,7 +193,7 @@ export class CreateDocumentCommand extends SanityCommand {
193
193
  const err = error;
194
194
  createDocumentDebug('Error in editor workflow', err);
195
195
  this.error(`Failed to create documents: ${err.message}`, {
196
- exit: 1
196
+ exit: exitCodes.RUNTIME_ERROR
197
197
  });
198
198
  }
199
199
  }
@@ -258,7 +258,7 @@ export class CreateDocumentCommand extends SanityCommand {
258
258
  errorMessage += '\nPerhaps you want to use `--replace` or `--missing`?';
259
259
  }
260
260
  this.error(errorMessage, {
261
- exit: 1
261
+ exit: exitCodes.RUNTIME_ERROR
262
262
  });
263
263
  }
264
264
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/create.ts"],"sourcesContent":["import {randomUUID} from 'node:crypto'\nimport fs from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {type MultipleMutationResult, type Mutation} from '@sanity/client'\nimport {watch as chokidarWatch} from 'chokidar'\nimport {execa, execaSync} from 'execa'\nimport json5 from 'json5'\nimport isEqual from 'lodash-es/isEqual.js'\nimport isPlainObject from 'lodash-es/isPlainObject.js'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {getEditor, registerUnlinkOnSigInt} from '../../actions/documents/editor.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {isIdentifiedSanityDocument, isSanityDocumentish} from '../../util/isSanityDocumentish.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nexport type MutationOperationName = 'create' | 'createIfNotExists' | 'createOrReplace'\n\nconst createDocumentDebug = subdebug('documents:create')\n\nexport class CreateDocumentCommand extends SanityCommand<typeof CreateDocumentCommand> {\n static override args = {\n file: Args.string({\n description: 'JSON file to create document(s) from',\n required: false,\n }),\n }\n\n static override description = 'Create one or more documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json',\n description: 'Create the document specified in \"myDocument.json\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Open configured $EDITOR and create the specified document(s)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --replace',\n description:\n 'Fetch document with the ID \"myDocId\" and open configured $EDITOR with the current document content (if any). Replace document with the edited version when the editor closes',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --watch --replace --json5',\n description:\n 'Open configured $EDITOR and replace the document with the given content on each save. Use JSON5 file extension and parser for simplified syntax.',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json --project-id abc123',\n description: 'Create documents in a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to create document(s) in',\n semantics: 'override',\n }),\n ...getDatasetFlag({\n description: 'Dataset to create document(s) in',\n semantics: 'override',\n }),\n id: Flags.string({\n description:\n 'Specify a document ID to use. Will fetch remote document ID and populate editor.',\n }),\n json5: Flags.boolean({\n description: 'Use JSON5 file type to allow a \"simplified\" version of JSON',\n }),\n missing: Flags.boolean({\n description: \"On duplicate document IDs, don't modify the target document(s)\",\n }),\n replace: Flags.boolean({\n description:\n 'On duplicate document IDs, replace existing document with specified document(s)',\n }),\n watch: Flags.boolean({\n description: 'Write the documents whenever the target file or buffer changes',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:create']\n\n private client!: Awaited<ReturnType<typeof getProjectCliClient>>\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(CreateDocumentCommand)\n const {file} = args\n const {dataset, id, json5: useJson5, missing, replace, watch} = flags\n\n if (!file && this.isUnattended()) {\n this.error(\n 'Document input is required in unattended mode. Pass it as the `<file>` argument.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n if (replace && missing) {\n this.error(\n 'Cannot use `--replace` and `--missing` together. Remove one flag and try again.',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n if (id && file) {\n this.error(\n 'Cannot use `--id` with the `<file>` argument. Remove `--id` or omit `<file>` and try again.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n this.client = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n let operation: MutationOperationName = 'create'\n if (replace || missing) {\n operation = replace ? 'createOrReplace' : 'createIfNotExists'\n }\n\n if (file) {\n try {\n const contentPath = path.resolve(process.cwd(), file)\n const content = json5.parse(await fs.readFile(contentPath, 'utf8'))\n const result = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(result, operation))\n return\n } catch (error) {\n const err = error as Error\n createDocumentDebug(`Error creating documents from file ${file}`, err)\n this.error(`Failed to create documents: ${err.message}`, {exit: 1})\n }\n }\n\n try {\n // Create a temporary file and use that as source, opening an editor on it\n const docId = id || randomUUID()\n const ext = useJson5 ? 'json5' : 'json'\n // Add UUID prefix to prevent predictable file names and potential conflicts\n const tmpFile = path.join(os.tmpdir(), 'sanity-cli', `${randomUUID()}-${docId}.${ext}`)\n const stringify = useJson5 ? json5.stringify : JSON.stringify\n const defaultValue = (id && (await this.client.getDocument(id))) || {\n _id: docId,\n _type: 'specify-me',\n }\n\n // Create temp directory with restricted permissions (owner only)\n const tempDir = path.join(os.tmpdir(), 'sanity-cli')\n await fs.mkdir(tempDir, {\n mode: 0o700, // rwx------ (owner read/write/execute only)\n recursive: true,\n })\n\n // Write file with restricted permissions (owner read/write only)\n await fs.writeFile(tmpFile, stringify(defaultValue, null, 2), {\n encoding: 'utf8',\n mode: 0o600, // rw------- (owner read/write only)\n })\n\n const editor = getEditor()\n const readAndPerformCreatesFromFile = this.readAndPerformCreatesFromFile.bind(this, operation)\n\n if (watch) {\n // If we're in watch mode, we want to run the creation on each change (if it validates)\n registerUnlinkOnSigInt(tmpFile)\n this.log(`Watch mode: ${tmpFile}`)\n this.log('Watch mode: Will write documents on each save.')\n this.log('Watch mode: Press Ctrl + C to cancel watch mode.')\n\n // Add race condition protection\n let isProcessing = false\n chokidarWatch(tmpFile).on('change', async () => {\n if (isProcessing) {\n return // Skip if already processing\n }\n isProcessing = true\n\n this.log('')\n try {\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n } finally {\n isProcessing = false\n }\n })\n execa(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n } else {\n // While in normal mode, we just want to wait for the editor to close and run the thing once\n execaSync(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n await fs.unlink(tmpFile).catch(() => {})\n }\n } catch (error) {\n const err = error as Error\n createDocumentDebug('Error in editor workflow', err)\n this.error(`Failed to create documents: ${err.message}`, {exit: 1})\n }\n }\n\n private getErrorMessage(message: string, index: number, isSingle: boolean): string {\n return isSingle ? `Document ${message}` : `Document at index ${index} ${message}`\n }\n\n /**\n * Formats the result message for document operations\n */\n private getResultMessage(\n result: MultipleMutationResult,\n operation: MutationOperationName,\n ): string {\n const joiner = '\\n - '\n if (operation === 'createOrReplace') {\n return `Upserted:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n if (operation === 'create') {\n return `Created:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n // \"Missing\" (createIfNotExists)\n const created: string[] = []\n const skipped: string[] = []\n for (const res of result.results) {\n if (res.operation === 'update') {\n skipped.push(res.id)\n } else {\n created.push(res.id)\n }\n }\n\n if (created.length > 0 && skipped.length > 0) {\n return [\n `Created:\\n - ${created.join(joiner)}`,\n `Skipped (already exists):${joiner}${skipped.join(joiner)}`,\n ].join('\\n\\n')\n } else if (created.length > 0) {\n return `Created:\\n - ${created.join(joiner)}`\n }\n\n return `Skipped (already exists):\\n - ${skipped.join(joiner)}`\n }\n\n /**\n * Reads and processes documents from a file for creation\n */\n private async readAndPerformCreatesFromFile(\n operation: MutationOperationName,\n filePath: string,\n defaultValue: unknown,\n ): Promise<void> {\n let content\n try {\n content = json5.parse(await fs.readFile(filePath, 'utf8'))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to read input file ${filePath}`, error)\n this.log(`Failed to read input: ${error.message}`)\n return\n }\n\n if (isEqual(content, defaultValue)) {\n this.log('Value not modified, doing nothing.')\n this.log('Modify document to trigger creation.')\n return\n }\n\n try {\n const writeResult = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(writeResult, operation))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to write documents`, error)\n let errorMessage = `Failed to write documents: ${error.message}`\n if (error.message.includes('already exists')) {\n errorMessage += '\\nPerhaps you want to use `--replace` or `--missing`?'\n }\n this.error(errorMessage, {exit: 1})\n }\n }\n\n /**\n * Validates a document for Sanity requirements\n */\n private validateDocument(doc: unknown, index: number, arr: unknown[]): void {\n const isSingle = arr.length === 1\n\n if (!isPlainObject(doc)) {\n throw new Error(this.getErrorMessage('must be an object', index, isSingle))\n }\n\n if (!isSanityDocumentish(doc)) {\n throw new Error(\n this.getErrorMessage('must have a `_type` property of type string', index, isSingle),\n )\n }\n\n // Enhanced validations for Sanity document constraints\n const docObj = doc as Record<string, unknown>\n\n // Validate _type is non-empty\n const typeValue = docObj._type?.toString().trim()\n if (!typeValue) {\n throw new Error(this.getErrorMessage('_type cannot be empty', index, isSingle))\n }\n\n // Validate _type format (alphanumeric, underscore, hyphen, dot)\n if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(typeValue)) {\n throw new Error(\n this.getErrorMessage(\n '_type must start with a letter and contain only alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Validate _id format if present\n if (docObj._id && typeof docObj._id === 'string') {\n const idValue = docObj._id.trim()\n if (!idValue) {\n throw new Error(this.getErrorMessage('_id cannot be empty', index, isSingle))\n }\n\n // Sanity document IDs can contain alphanumeric chars, hyphens, underscores, and dots\n if (!/^[a-zA-Z0-9_.-]+$/.test(idValue)) {\n throw new Error(\n this.getErrorMessage(\n '_id can only contain alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Check length constraints (Sanity has reasonable limits)\n if (idValue.length > 200) {\n throw new Error(\n this.getErrorMessage('_id cannot be longer than 200 characters', index, isSingle),\n )\n }\n }\n\n // Warn about reserved fields (these are managed by Sanity)\n const reservedFields = ['_rev', '_updatedAt', '_createdAt']\n for (const field of reservedFields) {\n if (field in docObj) {\n // Note: We don't throw an error here as these might be present in fetched documents\n // that are being re-uploaded, but we could add a debug warning\n createDocumentDebug(\n `Warning: Document ${index} contains reserved field '${field}' which will be ignored by Sanity`,\n )\n }\n }\n }\n\n /**\n * Writes documents to Sanity using the specified operation\n */\n private async writeDocuments(\n documents: {_id?: string; _type: string} | {_id?: string; _type: string}[],\n operation: MutationOperationName,\n ): Promise<MultipleMutationResult> {\n const docs = Array.isArray(documents) ? documents : [documents]\n if (docs.length === 0) {\n throw new Error('No documents provided')\n }\n\n const mutations = docs.map((doc, index): Mutation => {\n this.validateDocument(doc, index, docs)\n if (operation === 'create') {\n return {create: doc}\n }\n\n if (operation === 'createIfNotExists') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createIfNotExists: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n if (operation === 'createOrReplace') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createOrReplace: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n throw new Error(`Unsupported operation ${operation}`)\n })\n\n return this.client.transaction(mutations).commit()\n }\n}\n"],"names":["randomUUID","fs","os","path","Args","Flags","exitCodes","getProjectCliClient","SanityCommand","subdebug","watch","chokidarWatch","execa","execaSync","json5","isEqual","isPlainObject","DOCUMENTS_API_VERSION","getEditor","registerUnlinkOnSigInt","promptForProject","isIdentifiedSanityDocument","isSanityDocumentish","getDatasetFlag","getProjectIdFlag","createDocumentDebug","CreateDocumentCommand","args","file","string","description","required","examples","command","flags","semantics","id","boolean","missing","replace","hiddenAliases","client","run","parse","dataset","useJson5","isUnattended","error","exit","USAGE_ERROR","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","targetDataset","apiVersion","requireUser","operation","contentPath","resolve","process","cwd","content","readFile","result","writeDocuments","log","getResultMessage","err","message","docId","ext","tmpFile","join","tmpdir","stringify","JSON","defaultValue","getDocument","_id","_type","tempDir","mkdir","mode","recursive","writeFile","encoding","editor","readAndPerformCreatesFromFile","bind","isProcessing","on","bin","stdio","unlink","catch","getErrorMessage","index","isSingle","joiner","results","map","res","created","skipped","push","length","filePath","writeResult","errorMessage","includes","validateDocument","doc","arr","Error","docObj","typeValue","toString","trim","test","idValue","reservedFields","field","documents","docs","Array","isArray","mutations","create","createIfNotExists","createOrReplace","transaction","commit"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AACtC,OAAOC,QAAQ,mBAAkB;AACjC,OAAOC,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAE5B,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAExF,SAAQC,SAASC,aAAa,QAAO,WAAU;AAC/C,SAAQC,KAAK,EAAEC,SAAS,QAAO,QAAO;AACtC,OAAOC,WAAW,QAAO;AACzB,OAAOC,aAAa,uBAAsB;AAC1C,OAAOC,mBAAmB,6BAA4B;AAEtD,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,SAAS,EAAEC,sBAAsB,QAAO,oCAAmC;AACnF,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,0BAA0B,EAAEC,mBAAmB,QAAO,oCAAmC;AACjG,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAI1E,MAAMC,sBAAsBhB,SAAS;AAErC,OAAO,MAAMiB,8BAA8BlB;IACzC,OAAgBmB,OAAO;QACrBC,MAAMxB,KAAKyB,MAAM,CAAC;YAChBC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,+BAA8B;IAE5D,OAAgBE,WAAW;QACzB;YACEC,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SAAS;YACTH,aACE;QACJ;QACA;YACEG,SAAS;YACTH,aACE;QACJ;QACA;YACEG,SAAS;YACTH,aAAa;QACf;KACD,CAAA;IAED,OAAgBI,QAAQ;QACtB,GAAGV,iBAAiB;YAClBM,aAAa;YACbK,WAAW;QACb,EAAE;QACF,GAAGZ,eAAe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AACH,aAAaA,YAAY;YAACA;SAAU;QAC/D,IAAIC,KAAKlB,MAAM,KAAK,GAAG;YACrB,MAAM,IAAIQ,MAAM;QAClB;QAEA,MAAMa,YAAYH,KAAKvB,GAAG,CAAC,CAACW,KAAKf;YAC/B,IAAI,CAACc,gBAAgB,CAACC,KAAKf,OAAO2B;YAClC,IAAInE,cAAc,UAAU;gBAC1B,OAAO;oBAACuE,QAAQhB;gBAAG;YACrB;YAEA,IAAIvD,cAAc,qBAAqB;gBACrC,IAAItC,2BAA2B6F,MAAM;oBACnC,OAAO;wBAACiB,mBAAmBjB;oBAAG;gBAChC;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAEzD,WAAW;YACnE;YAEA,IAAIA,cAAc,mBAAmB;gBACnC,IAAItC,2BAA2B6F,MAAM;oBACnC,OAAO;wBAACkB,iBAAiBlB;oBAAG;gBAC9B;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAEzD,WAAW;YACnE;YAEA,MAAM,IAAIyD,MAAM,CAAC,sBAAsB,EAAEzD,WAAW;QACtD;QAEA,OAAO,IAAI,CAAClB,MAAM,CAAC4F,WAAW,CAACJ,WAAWK,MAAM;IAClD;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/documents/create.ts"],"sourcesContent":["import {randomUUID} from 'node:crypto'\nimport fs from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {type MultipleMutationResult, type Mutation} from '@sanity/client'\nimport {watch as chokidarWatch} from 'chokidar'\nimport {execa, execaSync} from 'execa'\nimport json5 from 'json5'\nimport isEqual from 'lodash-es/isEqual.js'\nimport isPlainObject from 'lodash-es/isPlainObject.js'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {getEditor, registerUnlinkOnSigInt} from '../../actions/documents/editor.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {isIdentifiedSanityDocument, isSanityDocumentish} from '../../util/isSanityDocumentish.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nexport type MutationOperationName = 'create' | 'createIfNotExists' | 'createOrReplace'\n\nconst createDocumentDebug = subdebug('documents:create')\n\nexport class CreateDocumentCommand extends SanityCommand<typeof CreateDocumentCommand> {\n static override args = {\n file: Args.string({\n description: 'JSON file to create document(s) from',\n required: false,\n }),\n }\n\n static override description = 'Create one or more documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json',\n description: 'Create the document specified in \"myDocument.json\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Open configured $EDITOR and create the specified document(s)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --replace',\n description:\n 'Fetch document with the ID \"myDocId\" and open configured $EDITOR with the current document content (if any). Replace document with the edited version when the editor closes',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --watch --replace --json5',\n description:\n 'Open configured $EDITOR and replace the document with the given content on each save. Use JSON5 file extension and parser for simplified syntax.',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json --project-id abc123',\n description: 'Create documents in a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to create document(s) in',\n semantics: 'override',\n }),\n ...getDatasetFlag({\n description: 'Dataset to create document(s) in',\n semantics: 'override',\n }),\n id: Flags.string({\n description:\n 'Specify a document ID to use. Will fetch remote document ID and populate editor.',\n }),\n json5: Flags.boolean({\n description: 'Use JSON5 file type to allow a \"simplified\" version of JSON',\n }),\n missing: Flags.boolean({\n description: \"On duplicate document IDs, don't modify the target document(s)\",\n }),\n replace: Flags.boolean({\n description:\n 'On duplicate document IDs, replace existing document with specified document(s)',\n }),\n watch: Flags.boolean({\n description: 'Write the documents whenever the target file or buffer changes',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:create']\n\n private client!: Awaited<ReturnType<typeof getProjectCliClient>>\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(CreateDocumentCommand)\n const {file} = args\n const {dataset, id, json5: useJson5, missing, replace, watch} = flags\n\n if (!file && this.isUnattended()) {\n this.error(\n 'Document input is required in unattended mode. Pass it as the `<file>` argument.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n if (replace && missing) {\n this.error(\n 'Cannot use `--replace` and `--missing` together. Remove one flag and try again.',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n if (id && file) {\n this.error(\n 'Cannot use `--id` with the `<file>` argument. Remove `--id` or omit `<file>` and try again.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n this.client = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n let operation: MutationOperationName = 'create'\n if (replace || missing) {\n operation = replace ? 'createOrReplace' : 'createIfNotExists'\n }\n\n if (file) {\n try {\n const contentPath = path.resolve(process.cwd(), file)\n const content = json5.parse(await fs.readFile(contentPath, 'utf8'))\n const result = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(result, operation))\n return\n } catch (error) {\n const err = error as Error\n createDocumentDebug(`Error creating documents from file ${file}`, err)\n this.error(`Failed to create documents: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n try {\n // Create a temporary file and use that as source, opening an editor on it\n const docId = id || randomUUID()\n const ext = useJson5 ? 'json5' : 'json'\n // Add UUID prefix to prevent predictable file names and potential conflicts\n const tmpFile = path.join(os.tmpdir(), 'sanity-cli', `${randomUUID()}-${docId}.${ext}`)\n const stringify = useJson5 ? json5.stringify : JSON.stringify\n const defaultValue = (id && (await this.client.getDocument(id))) || {\n _id: docId,\n _type: 'specify-me',\n }\n\n // Create temp directory with restricted permissions (owner only)\n const tempDir = path.join(os.tmpdir(), 'sanity-cli')\n await fs.mkdir(tempDir, {\n mode: 0o700, // rwx------ (owner read/write/execute only)\n recursive: true,\n })\n\n // Write file with restricted permissions (owner read/write only)\n await fs.writeFile(tmpFile, stringify(defaultValue, null, 2), {\n encoding: 'utf8',\n mode: 0o600, // rw------- (owner read/write only)\n })\n\n const editor = getEditor()\n const readAndPerformCreatesFromFile = this.readAndPerformCreatesFromFile.bind(this, operation)\n\n if (watch) {\n // If we're in watch mode, we want to run the creation on each change (if it validates)\n registerUnlinkOnSigInt(tmpFile)\n this.log(`Watch mode: ${tmpFile}`)\n this.log('Watch mode: Will write documents on each save.')\n this.log('Watch mode: Press Ctrl + C to cancel watch mode.')\n\n // Add race condition protection\n let isProcessing = false\n chokidarWatch(tmpFile).on('change', async () => {\n if (isProcessing) {\n return // Skip if already processing\n }\n isProcessing = true\n\n this.log('')\n try {\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n } finally {\n isProcessing = false\n }\n })\n execa(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n } else {\n // While in normal mode, we just want to wait for the editor to close and run the thing once\n execaSync(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n await fs.unlink(tmpFile).catch(() => {})\n }\n } catch (error) {\n const err = error as Error\n createDocumentDebug('Error in editor workflow', err)\n this.error(`Failed to create documents: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n private getErrorMessage(message: string, index: number, isSingle: boolean): string {\n return isSingle ? `Document ${message}` : `Document at index ${index} ${message}`\n }\n\n /**\n * Formats the result message for document operations\n */\n private getResultMessage(\n result: MultipleMutationResult,\n operation: MutationOperationName,\n ): string {\n const joiner = '\\n - '\n if (operation === 'createOrReplace') {\n return `Upserted:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n if (operation === 'create') {\n return `Created:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n // \"Missing\" (createIfNotExists)\n const created: string[] = []\n const skipped: string[] = []\n for (const res of result.results) {\n if (res.operation === 'update') {\n skipped.push(res.id)\n } else {\n created.push(res.id)\n }\n }\n\n if (created.length > 0 && skipped.length > 0) {\n return [\n `Created:\\n - ${created.join(joiner)}`,\n `Skipped (already exists):${joiner}${skipped.join(joiner)}`,\n ].join('\\n\\n')\n } else if (created.length > 0) {\n return `Created:\\n - ${created.join(joiner)}`\n }\n\n return `Skipped (already exists):\\n - ${skipped.join(joiner)}`\n }\n\n /**\n * Reads and processes documents from a file for creation\n */\n private async readAndPerformCreatesFromFile(\n operation: MutationOperationName,\n filePath: string,\n defaultValue: unknown,\n ): Promise<void> {\n let content\n try {\n content = json5.parse(await fs.readFile(filePath, 'utf8'))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to read input file ${filePath}`, error)\n this.log(`Failed to read input: ${error.message}`)\n return\n }\n\n if (isEqual(content, defaultValue)) {\n this.log('Value not modified, doing nothing.')\n this.log('Modify document to trigger creation.')\n return\n }\n\n try {\n const writeResult = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(writeResult, operation))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to write documents`, error)\n let errorMessage = `Failed to write documents: ${error.message}`\n if (error.message.includes('already exists')) {\n errorMessage += '\\nPerhaps you want to use `--replace` or `--missing`?'\n }\n this.error(errorMessage, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n /**\n * Validates a document for Sanity requirements\n */\n private validateDocument(doc: unknown, index: number, arr: unknown[]): void {\n const isSingle = arr.length === 1\n\n if (!isPlainObject(doc)) {\n throw new Error(this.getErrorMessage('must be an object', index, isSingle))\n }\n\n if (!isSanityDocumentish(doc)) {\n throw new Error(\n this.getErrorMessage('must have a `_type` property of type string', index, isSingle),\n )\n }\n\n // Enhanced validations for Sanity document constraints\n const docObj = doc as Record<string, unknown>\n\n // Validate _type is non-empty\n const typeValue = docObj._type?.toString().trim()\n if (!typeValue) {\n throw new Error(this.getErrorMessage('_type cannot be empty', index, isSingle))\n }\n\n // Validate _type format (alphanumeric, underscore, hyphen, dot)\n if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(typeValue)) {\n throw new Error(\n this.getErrorMessage(\n '_type must start with a letter and contain only alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Validate _id format if present\n if (docObj._id && typeof docObj._id === 'string') {\n const idValue = docObj._id.trim()\n if (!idValue) {\n throw new Error(this.getErrorMessage('_id cannot be empty', index, isSingle))\n }\n\n // Sanity document IDs can contain alphanumeric chars, hyphens, underscores, and dots\n if (!/^[a-zA-Z0-9_.-]+$/.test(idValue)) {\n throw new Error(\n this.getErrorMessage(\n '_id can only contain alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Check length constraints (Sanity has reasonable limits)\n if (idValue.length > 200) {\n throw new Error(\n this.getErrorMessage('_id cannot be longer than 200 characters', index, isSingle),\n )\n }\n }\n\n // Warn about reserved fields (these are managed by Sanity)\n const reservedFields = ['_rev', '_updatedAt', '_createdAt']\n for (const field of reservedFields) {\n if (field in docObj) {\n // Note: We don't throw an error here as these might be present in fetched documents\n // that are being re-uploaded, but we could add a debug warning\n createDocumentDebug(\n `Warning: Document ${index} contains reserved field '${field}' which will be ignored by Sanity`,\n )\n }\n }\n }\n\n /**\n * Writes documents to Sanity using the specified operation\n */\n private async writeDocuments(\n documents: {_id?: string; _type: string} | {_id?: string; _type: string}[],\n operation: MutationOperationName,\n ): Promise<MultipleMutationResult> {\n const docs = Array.isArray(documents) ? documents : [documents]\n if (docs.length === 0) {\n throw new Error('No documents provided')\n }\n\n const mutations = docs.map((doc, index): Mutation => {\n this.validateDocument(doc, index, docs)\n if (operation === 'create') {\n return {create: doc}\n }\n\n if (operation === 'createIfNotExists') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createIfNotExists: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n if (operation === 'createOrReplace') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createOrReplace: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n throw new Error(`Unsupported operation ${operation}`)\n })\n\n return this.client.transaction(mutations).commit()\n }\n}\n"],"names":["randomUUID","fs","os","path","Args","Flags","exitCodes","getProjectCliClient","SanityCommand","subdebug","watch","chokidarWatch","execa","execaSync","json5","isEqual","isPlainObject","DOCUMENTS_API_VERSION","getEditor","registerUnlinkOnSigInt","promptForProject","isIdentifiedSanityDocument","isSanityDocumentish","getDatasetFlag","getProjectIdFlag","createDocumentDebug","CreateDocumentCommand","args","file","string","description","required","examples","command","flags","semantics","id","boolean","missing","replace","hiddenAliases","client","run","parse","dataset","useJson5","isUnattended","error","exit","USAGE_ERROR","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","targetDataset","apiVersion","requireUser","operation","contentPath","resolve","process","cwd","content","readFile","result","writeDocuments","log","getResultMessage","err","message","RUNTIME_ERROR","docId","ext","tmpFile","join","tmpdir","stringify","JSON","defaultValue","getDocument","_id","_type","tempDir","mkdir","mode","recursive","writeFile","encoding","editor","readAndPerformCreatesFromFile","bind","isProcessing","on","bin","stdio","unlink","catch","getErrorMessage","index","isSingle","joiner","results","map","res","created","skipped","push","length","filePath","writeResult","errorMessage","includes","validateDocument","doc","arr","Error","docObj","typeValue","toString","trim","test","idValue","reservedFields","field","documents","docs","Array","isArray","mutations","create","createIfNotExists","createOrReplace","transaction","commit"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AACtC,OAAOC,QAAQ,mBAAkB;AACjC,OAAOC,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAE5B,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACv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pE,cAAc,UAAU;gBAC1B,OAAO;oBAACwE,QAAQhB;gBAAG;YACrB;YAEA,IAAIxD,cAAc,qBAAqB;gBACrC,IAAItC,2BAA2B8F,MAAM;oBACnC,OAAO;wBAACiB,mBAAmBjB;oBAAG;gBAChC;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAE1D,WAAW;YACnE;YAEA,IAAIA,cAAc,mBAAmB;gBACnC,IAAItC,2BAA2B8F,MAAM;oBACnC,OAAO;wBAACkB,iBAAiBlB;oBAAG;gBAC9B;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAE1D,WAAW;YACnE;YAEA,MAAM,IAAI0D,MAAM,CAAC,sBAAsB,EAAE1D,WAAW;QACtD;QAEA,OAAO,IAAI,CAAClB,MAAM,CAAC6F,WAAW,CAACJ,WAAWK,MAAM;IAClD;AACF"}
@@ -65,7 +65,7 @@ export class DeleteDocumentCommand extends SanityCommand {
65
65
  ].filter(Boolean);
66
66
  if (ids.length === 0) {
67
67
  this.error('Document ID must be specified', {
68
- exit: 1
68
+ exit: exitCodes.RUNTIME_ERROR
69
69
  });
70
70
  }
71
71
  // Get project configuration (may not exist when running outside a project directory)
@@ -98,14 +98,14 @@ export class DeleteDocumentCommand extends SanityCommand {
98
98
  }
99
99
  if (notFound.length > 0) {
100
100
  this.error(`${notFound.length === 1 ? 'Document' : 'Documents'} not found: ${notFound.join(', ')}`, {
101
- exit: 1
101
+ exit: exitCodes.RUNTIME_ERROR
102
102
  });
103
103
  }
104
104
  } catch (error) {
105
105
  const err = error;
106
106
  deleteDocumentDebug(`Error deleting documents ${ids.join(', ')}`, err);
107
107
  this.error(`Failed to delete ${ids.length} ${ids.length === 1 ? 'document' : 'documents'}: ${err.message}`, {
108
- exit: 1
108
+ exit: exitCodes.RUNTIME_ERROR
109
109
  });
110
110
  }
111
111
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/delete.ts"],"sourcesContent":["import {Args} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst deleteDocumentDebug = subdebug('documents:delete')\n\nexport class DeleteDocumentCommand extends SanityCommand<typeof DeleteDocumentCommand> {\n static override args = {\n id: Args.string({\n description: 'Document ID to delete',\n required: true,\n }),\n ids: Args.string({\n description: 'Additional document IDs to delete',\n required: false,\n }),\n }\n\n static override description = \"Delete one or more documents from the project's configured dataset\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Delete the document with the ID \"myDocId\"',\n },\n {\n command: \"<%= config.bin %> <%= command.id %> 'myDocId'\",\n description: 'ID wrapped in double or single quote works equally well',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dataset=blog someDocId',\n description: 'Delete document with ID \"someDocId\" from dataset \"blog\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> doc1 doc2',\n description: 'Delete the document with ID \"doc1\" and \"doc2\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project-id abc123',\n description: 'Delete a document from a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to delete from', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to delete from', semantics: 'override'}),\n }\n\n static override hiddenAliases: string[] = ['document:delete']\n\n // Disable strict mode to allow for more flexible input\n // This is needed for supporting multiple document IDs\n static override strict = false\n\n public async run(): Promise<void> {\n const {args, argv, flags} = await this.parse(DeleteDocumentCommand)\n const {id} = args\n const {dataset} = flags\n\n // Collect all document IDs from args and argv\n const ids = [id, ...argv.slice(1)].filter(Boolean) as string[]\n\n if (ids.length === 0) {\n this.error('Document ID must be specified', {exit: 1})\n }\n\n // Get project configuration (may not exist when running outside a project directory)\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n const transaction = projectClient.transaction()\n for (const id of ids) {\n transaction.delete(id)\n }\n const {results} = await transaction.commit()\n const deleted = results.filter((res) => res.operation === 'delete').map((res) => res.id)\n const notFound = ids.filter((id) => !deleted.includes(id))\n\n if (deleted.length > 0) {\n this.log(`Deleted ${deleted.length} ${deleted.length === 1 ? 'document' : 'documents'}`)\n }\n\n if (notFound.length > 0) {\n this.error(\n `${notFound.length === 1 ? 'Document' : 'Documents'} not found: ${notFound.join(', ')}`,\n {\n exit: 1,\n },\n )\n }\n } catch (error) {\n const err = error as Error\n deleteDocumentDebug(`Error deleting documents ${ids.join(', ')}`, err)\n this.error(\n `Failed to delete ${ids.length} ${ids.length === 1 ? 'document' : 'documents'}: ${err.message}`,\n {\n exit: 1,\n },\n )\n }\n }\n}\n"],"names":["Args","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","deleteDocumentDebug","DeleteDocumentCommand","args","id","string","description","required","ids","examples","command","flags","semantics","hiddenAliases","strict","run","argv","parse","dataset","slice","filter","Boolean","length","error","exit","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","USAGE_ERROR","targetDataset","projectClient","apiVersion","requireUser","transaction","delete","results","commit","deleted","res","operation","map","notFound","includes","log","join","err","message"],"mappings":"AAAA,SAAQA,IAAI,QAAO,cAAa;AAChC,SAAQC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAExF,SAAQC,qBAAqB,QAAO,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AAC,OAAO,EAAEC;YAClE,IAAI,CAACzB,KAAK,CACR,CAAC,iBAAiB,EAAEf,IAAIc,MAAM,CAAC,CAAC,EAAEd,IAAIc,MAAM,KAAK,IAAI,aAAa,YAAY,EAAE,EAAE0B,IAAIC,OAAO,EAAE,EAC/F;gBACEzB,MAAM;YACR;QAEJ;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/documents/delete.ts"],"sourcesContent":["import {Args} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst deleteDocumentDebug = subdebug('documents:delete')\n\nexport class DeleteDocumentCommand extends SanityCommand<typeof DeleteDocumentCommand> {\n static override args = {\n id: Args.string({\n description: 'Document ID to delete',\n required: true,\n }),\n ids: Args.string({\n description: 'Additional document IDs to delete',\n required: false,\n }),\n }\n\n static override description = \"Delete one or more documents from the project's configured dataset\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Delete the document with the ID \"myDocId\"',\n },\n {\n command: \"<%= config.bin %> <%= command.id %> 'myDocId'\",\n description: 'ID wrapped in double or single quote works equally well',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dataset=blog someDocId',\n description: 'Delete document with ID \"someDocId\" from dataset \"blog\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> doc1 doc2',\n description: 'Delete the document with ID \"doc1\" and \"doc2\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project-id abc123',\n description: 'Delete a document from a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to delete from', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to delete from', semantics: 'override'}),\n }\n\n static override hiddenAliases: string[] = ['document:delete']\n\n // Disable strict mode to allow for more flexible input\n // This is needed for supporting multiple document IDs\n static override strict = false\n\n public async run(): Promise<void> {\n const {args, argv, flags} = await this.parse(DeleteDocumentCommand)\n const {id} = args\n const {dataset} = flags\n\n // Collect all document IDs from args and argv\n const ids = [id, ...argv.slice(1)].filter(Boolean) as string[]\n\n if (ids.length === 0) {\n this.error('Document ID must be specified', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n // Get project configuration (may not exist when running outside a project directory)\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n const transaction = projectClient.transaction()\n for (const id of ids) {\n transaction.delete(id)\n }\n const {results} = await transaction.commit()\n const deleted = results.filter((res) => res.operation === 'delete').map((res) => res.id)\n const notFound = ids.filter((id) => !deleted.includes(id))\n\n if (deleted.length > 0) {\n this.log(`Deleted ${deleted.length} ${deleted.length === 1 ? 'document' : 'documents'}`)\n }\n\n if (notFound.length > 0) {\n this.error(\n `${notFound.length === 1 ? 'Document' : 'Documents'} not found: ${notFound.join(', ')}`,\n {\n exit: exitCodes.RUNTIME_ERROR,\n },\n )\n }\n } catch (error) {\n const err = error as Error\n deleteDocumentDebug(`Error deleting documents ${ids.join(', ')}`, err)\n this.error(\n `Failed to delete ${ids.length} ${ids.length === 1 ? 'document' : 'documents'}: ${err.message}`,\n {\n exit: exitCodes.RUNTIME_ERROR,\n },\n )\n }\n }\n}\n"],"names":["Args","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","deleteDocumentDebug","DeleteDocumentCommand","args","id","string","description","required","ids","examples","command","flags","semantics","hiddenAliases","strict","run","argv","parse","dataset","slice","filter","Boolean","length","error","exit","RUNTIME_ERROR","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","USAGE_ERROR","targetDataset","projectClient","apiVersion","requireUser","transaction","delete","results","commit","deleted","res","operation","map","notFound","includes","log","join","err","message"],"mappings":"AAAA,SAAQA,IAAI,QAAO,cAAa;AAChC,SAAQC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAExF,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,sBAAsBL,SAAS;AAErC,OAAO,MAAMM,8BAA8BP;IACzC,OAAgBQ,OAAO;QACrBC,IAAIZ,KAAKa,MAAM,CAAC;YACdC,aAAa;YACbC,UAAU;QACZ;QACAC,KAAKhB,KAAKa,MAAM,CAAC;YACfC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,qEAAoE;IAElG,OAAgBG,WAAW;QACzB;YACEC,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;KACD,CAAA;IAED,OAAgBK,QAAQ;QACtB,GAAGX,iBAAiB;YAACM,aAAa;YAA6BM,WAAW;QAAU,EAAE;QACtF,GAAGb,eAAe;YAACO,aAAa;YAA0BM,WAAW;QAAU,EAAE;IACnF,EAAC;IAED,OAAgBC,gBAA0B;QAAC;KAAkB,CAAA;IAE7D,uDAAuD;IACvD,sDAAsD;IACtD,OAAgBC,SAAS,MAAK;IAE9B,MAAaC,MAAqB;QAChC,MAAM,EAACZ,IAAI,EAAEa,IAAI,EAAEL,KAAK,EAAC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,EAAEN,QAAQnB,MAAM,CAAC,CAAC,EAAEmB,QAAQnB,MAAM,KAAK,IAAI,aAAa,aAAa;YACzF;YAEA,IAAIuB,SAASvB,MAAM,GAAG,GAAG;gBACvB,IAAI,CAACC,KAAK,CACR,GAAGsB,SAASvB,MAAM,KAAK,IAAI,aAAa,YAAY,YAAY,EAAEuB,SAASG,IAAI,CAAC,OAAO,EACvF;oBACExB,MAAM/B,UAAUgC,aAAa;gBAC/B;YAEJ;QACF,EAAE,OAAOF,OAAO;YACd,MAAM0B,MAAM1B;YACZtB,oBAAoB,CAAC,yBAAyB,EAAEO,IAAIwC,IAAI,CAAC,OAAO,EAAEC;YAClE,IAAI,CAAC1B,KAAK,CACR,CAAC,iBAAiB,EAAEf,IAAIc,MAAM,CAAC,CAAC,EAAEd,IAAIc,MAAM,KAAK,IAAI,aAAa,YAAY,EAAE,EAAE2B,IAAIC,OAAO,EAAE,EAC/F;gBACE1B,MAAM/B,UAAUgC,aAAa;YAC/B;QAEJ;IACF;AACF"}
@@ -71,7 +71,7 @@ export class GetDocumentCommand extends SanityCommand {
71
71
  const doc = await projectClient.getDocument(documentId);
72
72
  if (!doc) {
73
73
  this.error(`Document "${documentId}" not found in dataset "${targetDataset}"`, {
74
- exit: 1
74
+ exit: exitCodes.RUNTIME_ERROR
75
75
  });
76
76
  }
77
77
  // Output the document
@@ -84,7 +84,7 @@ export class GetDocumentCommand extends SanityCommand {
84
84
  const err = error;
85
85
  getDocumentDebug(`Error fetching document ${documentId}`, err);
86
86
  this.error(`Failed to fetch document: ${err.message}`, {
87
- exit: 1
87
+ exit: exitCodes.RUNTIME_ERROR
88
88
  });
89
89
  }
90
90
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/get.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {\n colorizeJson,\n exitCodes,\n getProjectCliClient,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst getDocumentDebug = subdebug('documents:get')\n\nexport class GetDocumentCommand extends SanityCommand<typeof GetDocumentCommand> {\n static override args = {\n documentId: Args.string({\n description: 'Document ID to retrieve',\n required: true,\n }),\n }\n\n static override description = 'Get and print a document by ID'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Get the document with ID \"myDocId\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --pretty',\n description: 'Get document with colorized JSON output',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --dataset production',\n description: 'Get document from a specific dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project-id abc123',\n description: 'Get a document from a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to get document from',\n semantics: 'override',\n }),\n ...getDatasetFlag({description: 'Dataset to get document from', semantics: 'override'}),\n pretty: Flags.boolean({\n default: false,\n description: 'Colorize JSON output',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:get']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(GetDocumentCommand)\n const {documentId} = args\n const {dataset, pretty} = flags\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n const doc = await projectClient.getDocument(documentId)\n\n if (!doc) {\n this.error(`Document \"${documentId}\" not found in dataset \"${targetDataset}\"`, {exit: 1})\n }\n\n // Output the document\n if (pretty) {\n this.log(colorizeJson(doc))\n } else {\n this.log(JSON.stringify(doc, null, 2))\n }\n } catch (error) {\n const err = error as Error\n\n getDocumentDebug(`Error fetching document ${documentId}`, err)\n this.error(`Failed to fetch document: ${err.message}`, {exit: 1})\n }\n }\n}\n"],"names":["Args","Flags","colorizeJson","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","getDocumentDebug","GetDocumentCommand","args","documentId","string","description","required","examples","command","flags","semantics","pretty","boolean","default","hiddenAliases","run","parse","dataset","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","error","exit","USAGE_ERROR","targetDataset","projectClient","apiVersion","requireUser","doc","getDocument","log","JSON","stringify","err","message"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SACEC,YAAY,EACZC,SAAS,EACTC,mBAAmB,EACnBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AAEzB,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,mBAAmBL,SAAS;AAElC,OAAO,MAAMM,2BAA2BP;IACtC,OAAgBQ,OAAO;QACrBC,YAAYd,KAAKe,MAAM,CAAC;YACtBC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,iCAAgC;IAE9D,OAAgBE,WAAW;QACzB;YACEC,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SAAS;YACTH,aAAa;QACf;KACD,CAAA;IAED,OAAgBI,QAAQ;QACtB,GAAGV,iBAAiB;YAClBM,aAAa;YACbK,WAAW;QACb,EAAE;QACF,GAAGZ,eAAe;YAACO,aAAa;YAAgCK,WAAW;QAAU,EAAE;QACvFC,QAAQrB,M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C,OAAO,EAAE,EAAE;gBAACZ,MAAM;YAAC;QACjE;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/documents/get.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {\n colorizeJson,\n exitCodes,\n getProjectCliClient,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst getDocumentDebug = subdebug('documents:get')\n\nexport class GetDocumentCommand extends SanityCommand<typeof GetDocumentCommand> {\n static override args = {\n documentId: Args.string({\n description: 'Document ID to retrieve',\n required: true,\n }),\n }\n\n static override description = 'Get and print a document by ID'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Get the document with ID \"myDocId\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --pretty',\n description: 'Get document with colorized JSON output',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --dataset production',\n description: 'Get document from a specific dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project-id abc123',\n description: 'Get a document from a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to get document from',\n semantics: 'override',\n }),\n ...getDatasetFlag({description: 'Dataset to get document from', semantics: 'override'}),\n pretty: Flags.boolean({\n default: false,\n description: 'Colorize JSON output',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:get']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(GetDocumentCommand)\n const {documentId} = args\n const {dataset, pretty} = flags\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n const doc = await projectClient.getDocument(documentId)\n\n if (!doc) {\n this.error(`Document \"${documentId}\" not found in dataset \"${targetDataset}\"`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // Output the document\n if (pretty) {\n this.log(colorizeJson(doc))\n } else {\n this.log(JSON.stringify(doc, null, 2))\n }\n } catch (error) {\n const err = error as Error\n\n getDocumentDebug(`Error fetching document ${documentId}`, err)\n this.error(`Failed to fetch document: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Args","Flags","colorizeJson","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","getDocumentDebug","GetDocumentCommand","args","documentId","string","description","required","examples","command","flags","semantics","pretty","boolean","default","hiddenAliases","run","parse","dataset","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","error","exit","USAGE_ERROR","targetDataset","projectClient","apiVersion","requireUser","doc","getDocument","RUNTIME_ERROR","log","JSON","stringify","err","message"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SACEC,YAAY,EACZC,SAAS,EACTC,mBAAmB,EACnBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AAEzB,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,mBAAmBL,SAAS;AAElC,OAAO,MAAMM,2BAA2BP;IACtC,OAAgBQ,OAAO;QACrBC,YAAYd,KAAKe,MAAM,CAAC;YACtBC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,iCAAgC;IAE9D,OAAgBE,WAAW;Q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;YACF;YAEA,sBAAsB;YACtB,IAAItB,QAAQ;gBACV,IAAI,CAACuB,GAAG,CAAC3C,aAAawC;YACxB,OAAO;gBACL,IAAI,CAACG,GAAG,CAACC,KAAKC,SAAS,CAACL,KAAK,MAAM;YACrC;QACF,EAAE,OAAOP,OAAO;YACd,MAAMa,MAAMb;YAEZxB,iBAAiB,CAAC,wBAAwB,EAAEG,YAAY,EAAEkC;YAC1D,IAAI,CAACb,KAAK,CAAC,CAAC,0BAA0B,EAAEa,IAAIC,OAAO,EAAE,EAAE;gBAACb,MAAMjC,UAAUyC,aAAa;YAAA;QACvF;IACF;AACF"}
@@ -92,7 +92,7 @@ export class QueryDocumentCommand extends SanityCommand {
92
92
  const docs = await projectClient.fetch(query);
93
93
  if (!docs) {
94
94
  this.error('Query returned no results', {
95
- exit: 1
95
+ exit: exitCodes.RUNTIME_ERROR
96
96
  });
97
97
  }
98
98
  // Output the query results
@@ -107,7 +107,7 @@ export class QueryDocumentCommand extends SanityCommand {
107
107
  // Provide more context in error messages
108
108
  const errorMsg = err.message.toLowerCase().includes('syntax') ? `Invalid GROQ query syntax: ${err.message}` : `Failed to run query: ${err.message}`;
109
109
  this.error(`${errorMsg}\nQuery: ${query}`, {
110
- exit: 1
110
+ exit: exitCodes.RUNTIME_ERROR
111
111
  });
112
112
  }
113
113
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/query.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {\n colorizeJson,\n exitCodes,\n getProjectCliClient,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst queryDocumentDebug = subdebug('documents:query')\n\nexport class QueryDocumentCommand extends SanityCommand<typeof QueryDocumentCommand> {\n static override args = {\n query: Args.string({\n description: 'GROQ query to run against the dataset',\n required: true,\n }),\n }\n\n static override description = 'Query for documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"][0..4]\\'',\n description: 'Fetch 5 documents of type \"movie\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"]|order(releaseDate asc)[0]{title}\\' --dataset staging',\n description: 'Fetch title of the oldest movie in the dataset named \"staging\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_id == \"header\"] { \"headerText\": pt::text(body) }\\' --api-version v2021-06-07',\n description: 'Use API version v2021-06-07 and do a query',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"post\"]\\' --project-id abc123 --dataset production',\n description: 'Query documents in a specific project and dataset',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to query', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to query', semantics: 'override'}),\n anonymous: Flags.boolean({\n default: false,\n description: 'Send the query without any authorization token',\n }),\n 'api-version': Flags.string({\n description: `API version to use (defaults to ${DOCUMENTS_API_VERSION})`,\n env: 'SANITY_CLI_QUERY_API_VERSION',\n }),\n pretty: Flags.boolean({\n default: false,\n description: 'Colorize JSON output',\n }),\n project: Flags.string({\n deprecated: {to: 'project-id'},\n description: 'Project ID to query',\n hidden: true,\n }),\n }\n\n static override hiddenAliases: string[] = ['document:query']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(QueryDocumentCommand)\n const {query} = args\n const {anonymous, 'api-version': apiVersion, dataset, pretty} = flags\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({\n deprecatedFlagName: 'project',\n fallback: () => promptForProject({}),\n })\n\n const requireUser = !anonymous\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n const targetApiVersion = apiVersion || DOCUMENTS_API_VERSION\n\n if (!apiVersion) {\n this.warn(`--api-version not specified, using \\`${DOCUMENTS_API_VERSION}\\``)\n }\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: targetApiVersion,\n dataset: targetDataset,\n projectId,\n requireUser,\n })\n\n const docs = await projectClient.fetch(query)\n\n if (!docs) {\n this.error('Query returned no results', {exit: 1})\n }\n\n // Output the query results\n if (pretty) {\n this.log(colorizeJson(docs))\n } else {\n this.log(JSON.stringify(docs, null, 2))\n }\n } catch (error) {\n const err = error as Error\n\n queryDocumentDebug(`Error running query: ${query}`, err)\n\n // Provide more context in error messages\n const errorMsg = err.message.toLowerCase().includes('syntax')\n ? `Invalid GROQ query syntax: ${err.message}`\n : `Failed to run query: ${err.message}`\n\n this.error(`${errorMsg}\\nQuery: ${query}`, {exit: 1})\n }\n }\n}\n"],"names":["Args","Flags","colorizeJson","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","queryDocumentDebug","QueryDocumentCommand","args","query","string","description","required","examples","command","flags","semantics","anonymous","boolean","default","env","pretty","project","deprecated","to","hidden","hiddenAliases","run","parse","apiVersion","dataset","cliConfig","tryGetCliConfig","projectId","getProjectId","deprecatedFlagName","fallback","requireUser","api","error","exit","USAGE_ERROR","targetDataset","targetApiVersion","warn","projectClient","docs","fetch","log","JSON","stringify","err","errorMsg","message","toLowerCase","includes"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SACEC,YAAY,EACZC,SAAS,EACTC,mBAAmB,EACnBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AAEzB,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,qBAAqBL,SAAS;AAEpC,OAAO,MAAMM,6BAA6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IAAI,CAACc,UAAUO,GAAG,EAAER,WAAW,CAACA,SAAS;YACvC,IAAI,CAACS,KAAK,CACR,4FACA;gBAACC,MAAM1C,UAAU2C,WAAW;YAAA;QAEhC;QAEA,MAAMC,gBAAgBZ,WAAWC,UAAUO,GAAG,EAAER;QAChD,MAAMa,mBAAmBd,cAAc3B;QAEvC,IAAI,CAAC2B,YAAY;YACf,IAAI,CAACe,IAAI,CAAC,CAAC,qCAAqC,EAAE1C,sBAAsB,EAAE,CAAC;QAC7E;QAEA,IAAI;YACF,MAAM2C,gBAAgB,MAAM9C,oBAAoB;gBAC9C8B,YAAYc;gBACZb,SAASY;gBACTT;gBACAI;YACF;YAEA,MAAMS,OAAO,MAAMD,cAAcE,KAAK,CAACtC;YAEvC,IAAI,CAACqC,MAAM;gBACT,IAAI,CAACP,KAAK,CAAC,6BAA6B;oBAACC,MAAM;gBAAC;YAClD;YAEA,2BAA2B;YAC3B,IAAInB,QAAQ;gBACV,IAAI,CAAC2B,GAAG,CAACnD,aAAaiD;YACxB,OAAO;gBACL,IAAI,CAACE,GAAG,CAACC,KAAKC,SAAS,CAACJ,MAAM,MAAM;YACtC;QACF,EAAE,OAAOP,OAAO;YACd,MAAMY,MAAMZ;YAEZjC,mBAAmB,CAAC,qBAAqB,EAAEG,OAAO,EAAE0C;YAEpD,yCAAyC;YACzC,MAAMC,WAAWD,IAAIE,OAAO,CAACC,WAAW,GAAGC,QAAQ,CAAC,YAChD,CAAC,2BAA2B,EAAEJ,IAAIE,OAAO,EAAE,GAC3C,CAAC,qBAAqB,EAAEF,IAAIE,OAAO,EAAE;YAEzC,IAAI,CAACd,KAAK,CAAC,GAAGa,SAAS,SAAS,EAAE3C,OAAO,EAAE;gBAAC+B,MAAM;YAAC;QACrD;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/documents/query.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {\n colorizeJson,\n exitCodes,\n getProjectCliClient,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst queryDocumentDebug = subdebug('documents:query')\n\nexport class QueryDocumentCommand extends SanityCommand<typeof QueryDocumentCommand> {\n static override args = {\n query: Args.string({\n description: 'GROQ query to run against the dataset',\n required: true,\n }),\n }\n\n static override description = 'Query for documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"][0..4]\\'',\n description: 'Fetch 5 documents of type \"movie\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"]|order(releaseDate asc)[0]{title}\\' --dataset staging',\n description: 'Fetch title of the oldest movie in the dataset named \"staging\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_id == \"header\"] { \"headerText\": pt::text(body) }\\' --api-version v2021-06-07',\n description: 'Use API version v2021-06-07 and do a query',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"post\"]\\' --project-id abc123 --dataset production',\n description: 'Query documents in a specific project and dataset',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to query', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to query', semantics: 'override'}),\n anonymous: Flags.boolean({\n default: false,\n description: 'Send the query without any authorization token',\n }),\n 'api-version': Flags.string({\n description: `API version to use (defaults to ${DOCUMENTS_API_VERSION})`,\n env: 'SANITY_CLI_QUERY_API_VERSION',\n }),\n pretty: Flags.boolean({\n default: false,\n description: 'Colorize JSON output',\n }),\n project: Flags.string({\n deprecated: {to: 'project-id'},\n description: 'Project ID to query',\n hidden: true,\n }),\n }\n\n static override hiddenAliases: string[] = ['document:query']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(QueryDocumentCommand)\n const {query} = args\n const {anonymous, 'api-version': apiVersion, dataset, pretty} = flags\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({\n deprecatedFlagName: 'project',\n fallback: () => promptForProject({}),\n })\n\n const requireUser = !anonymous\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n const targetApiVersion = apiVersion || DOCUMENTS_API_VERSION\n\n if (!apiVersion) {\n this.warn(`--api-version not specified, using \\`${DOCUMENTS_API_VERSION}\\``)\n }\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: targetApiVersion,\n dataset: targetDataset,\n projectId,\n requireUser,\n })\n\n const docs = await projectClient.fetch(query)\n\n if (!docs) {\n this.error('Query returned no results', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n // Output the query results\n if (pretty) {\n this.log(colorizeJson(docs))\n } else {\n this.log(JSON.stringify(docs, null, 2))\n }\n } catch (error) {\n const err = error as Error\n\n queryDocumentDebug(`Error running query: ${query}`, err)\n\n // Provide more context in error messages\n const errorMsg = err.message.toLowerCase().includes('syntax')\n ? `Invalid GROQ query syntax: ${err.message}`\n : `Failed to run query: ${err.message}`\n\n this.error(`${errorMsg}\\nQuery: ${query}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Args","Flags","colorizeJson","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","queryDocumentDebug","QueryDocumentCommand","args","query","string","description","required","examples","command","flags","semantics","anonymous","boolean","default","env","pretty","project","deprecated","to","hidden","hiddenAliases","run","parse","apiVersion","dataset","cliConfig","tryGetCliConfig","projectId","getProjectId","deprecatedFlagName","fallback","requireUser","api","error","exit","USAGE_ERROR","targetDataset","targetApiVersion","warn","projectClient","docs","fetch","RUNTIME_ERROR","log","JSON","stringify","err","errorMsg","message","toLowerCase","includes"],"mapp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C,2BAA2B,EAAEJ,IAAIE,OAAO,EAAE,GAC3C,CAAC,qBAAqB,EAAEF,IAAIE,OAAO,EAAE;YAEzC,IAAI,CAACf,KAAK,CAAC,GAAGc,SAAS,SAAS,EAAE5C,OAAO,EAAE;gBAAC+B,MAAM1C,UAAUkD,aAAa;YAAA;QAC3E;IACF;AACF"}
@@ -95,7 +95,7 @@ export class ValidateDocumentsCommand extends SanityCommand {
95
95
  } catch (err) {
96
96
  if (err instanceof ProjectRootNotFoundError) {
97
97
  return this.output.error('This command must be run from within a Sanity project directory (requires studio schema for validation)', {
98
- exit: 1
98
+ exit: exitCodes.RUNTIME_ERROR
99
99
  });
100
100
  }
101
101
  throw err;
@@ -158,11 +158,11 @@ export class ValidateDocumentsCommand extends SanityCommand {
158
158
  workspace
159
159
  });
160
160
  if (overallLevel === 'error') {
161
- return this.exit(1);
161
+ return this.exit(exitCodes.RUNTIME_ERROR);
162
162
  }
163
163
  } catch (err) {
164
164
  return this.output.error(err instanceof Error ? err.message : String(err), {
165
- exit: 1
165
+ exit: exitCodes.RUNTIME_ERROR
166
166
  });
167
167
  }
168
168
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/validate.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {exitCodes} from '@sanity/cli-core'\nimport {ProjectRootNotFoundError} from '@sanity/cli-core/errors'\nimport {SanityCommand} from '@sanity/cli-core/SanityCommand'\nimport {type CliConfig} from '@sanity/cli-core/types'\nimport {confirm, logSymbols} from '@sanity/cli-core/ux'\n\nimport {type Level} from '../../actions/documents/types.js'\nimport {validateDocuments} from '../../actions/documents/validate.js'\nimport {reporters} from '../../actions/documents/validation/reporters/index.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nexport class ValidateDocumentsCommand extends SanityCommand<typeof ValidateDocumentsCommand> {\n static description = 'Validate documents in a dataset against the studio schema'\n\n static examples = [\n {\n command: '<%= config.bin %> <%= command.id %> --workspace default',\n description: 'Validates all documents in a Sanity project with more than one workspace',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --workspace default --dataset staging',\n description: 'Override the dataset specified in the workspace',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --yes > report.txt',\n description: 'Save the results of the report into a file',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --level info',\n description: 'Report out info level validation markers too',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --project-id abc123 --dataset production',\n description: 'Validate documents in a specific project and dataset',\n },\n ]\n\n static flags = {\n ...getProjectIdFlag({\n description:\n 'Override the project ID used. By default, this is derived from the given workspace',\n semantics: 'specify',\n }),\n ...getDatasetFlag({\n description:\n 'Override the dataset used. By default, this is derived from the given workspace',\n semantics: 'specify',\n }),\n file: Flags.string({\n description:\n 'Path to an NDJSON file or tar archive containing an NDJSON file (optionally gzip-compressed)',\n }),\n format: Flags.string({\n description:\n 'The output format used to print the found validation markers and report progress',\n options: ['json', 'ndjson', 'pretty'],\n }),\n level: Flags.custom<Level>({\n default: 'warning',\n description: 'The minimum level reported. Defaults to warning',\n options: ['error', 'warning', 'info'],\n })(),\n 'max-custom-validation-concurrency': Flags.integer({\n default: 5,\n description: 'Specify how many custom validators can run concurrently',\n }),\n 'max-fetch-concurrency': Flags.integer({\n default: 25,\n description: 'Specify how many `client.fetch` requests are allowed to run concurrently',\n }),\n workspace: Flags.string({\n description: 'The name of the workspace to use when downloading and validating all documents',\n }),\n yes: Flags.boolean({\n char: 'y',\n default: false,\n description: 'Skips the first confirmation prompt',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:validate']\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(ValidateDocumentsCommand)\n const {\n dataset,\n file,\n format,\n level,\n 'max-custom-validation-concurrency': maxCustomValidationConcurrency,\n 'max-fetch-concurrency': maxFetchConcurrency,\n 'project-id': projectId,\n workspace,\n } = flags\n const unattendedMode = this.isUnattended()\n\n let workDir: string\n let cliConfig: CliConfig\n try {\n const root = await this.getProjectRoot()\n workDir = root.directory\n cliConfig = await this.getCliConfig()\n } catch (err) {\n if (err instanceof ProjectRootNotFoundError) {\n return this.output.error(\n 'This command must be run from within a Sanity project directory (requires studio schema for validation)',\n {exit: 1},\n )\n }\n throw err\n }\n\n let ndjsonFilePath\n if (file) {\n const filePath = path.resolve(workDir, file)\n\n let fileStat\n try {\n fileStat = await stat(filePath)\n } catch {\n return this.output.error(\n `File not found: ${file}. Pass an existing NDJSON file or tar archive with \\`--file <path>\\`.`,\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n if (!fileStat.isFile()) {\n return this.output.error(\n `Invalid file path: ${file} is not a file. Pass an NDJSON file or tar archive with \\`--file <path>\\`.`,\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n ndjsonFilePath = filePath\n }\n\n if (!unattendedMode) {\n this.output.log(\n `${styleText('yellow', `${logSymbols.warning} Warning:`)} This command ${\n file\n ? 'reads all documents from your input file'\n : 'downloads all documents from your dataset'\n } and processes them through your local schema within a ` +\n `simulated browser environment.\\n`,\n )\n this.output.log(`Potential pitfalls:\\n`)\n this.output.log(\n `- Processes all documents locally (excluding assets). Large datasets may require more resources.`,\n )\n this.output.log(\n `- Executes all custom validation functions. Some functions may need to be refactored for compatibility.`,\n )\n this.output.log(\n `- Not all standard browser features are available and may cause issues while loading your Studio.`,\n )\n this.output.log(\n `- Adheres to document permissions. Ensure this account can see all desired documents.`,\n )\n if (file) {\n this.output.log(\n `- Checks for missing document references against the live dataset if not found in your file.`,\n )\n }\n\n const confirmed = await confirm({\n default: true,\n message: `Are you sure you want to continue?`,\n })\n\n if (!confirmed) {\n this.output.log('Validation cancelled')\n return this.exit(exitCodes.USER_ABORT)\n }\n }\n\n try {\n const overallLevel = await validateDocuments({\n dataset,\n level,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n ndjsonFilePath,\n projectId,\n reporter: (worker) => {\n const reporter =\n format && format in reporters\n ? reporters[format as keyof typeof reporters]\n : reporters.pretty\n\n return reporter({flags, output: this.output, worker})\n },\n studioHost: cliConfig.studioHost,\n workDir,\n workspace,\n })\n\n if (overallLevel === 'error') {\n return this.exit(1)\n }\n } catch (err) {\n return this.output.error(err instanceof Error ? err.message : String(err), {exit: 1})\n }\n }\n}\n"],"names":["stat","path","styleText","Flags","exitCodes","ProjectRootNotFoundError","SanityCommand","confirm","logSymbols","validateDocuments","reporters","getDatasetFlag","getProjectIdFlag","ValidateDocumentsCommand","description","examples","command","flags","semantics","file","string","format","options","level","custom","default","integer","workspace","yes","boolean","char","hiddenAliases","run","parse","dataset","maxCustomValidationConcurrency","maxFetchConcurrency","projectId","unattendedMode","isUnattended","workDir","cliConfig","root","getProjectRoot","directory","getCliConfig","err","output","error","exit","ndjsonFilePath","filePath","resolve","fileStat","USAGE_ERROR","isFile","log","warning","confirmed","message","USER_ABORT","overallLevel","reporter","worker","pretty","studioHost","Error","String"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,SAAS,QAAO,mBAAkB;AAC1C,SAAQC,wBAAwB,QAAO,0BAAyB;AAChE,SAAQC,aAAa,QAAO,iCAAgC;AAE5D,SAAQC,OAAO,EAAEC,UAAU,QAAO,sBAAqB;AAGvD,SAAQC,iBAAiB,QAAO,sCAAqC;AACrE,SAAQC,SAAS,QAAO,wDAAuD;AAC/E,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,OAAO,MAAMC,iCAAiCP;IAC5C,OAAOQ,cAAc,4DAA2D;IAEhF,OAAOC,WAAW;QAChB;YACEC,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,S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nD,QAAQ;gBAC9BkB,SAAS;gBACTkC,SAAS,CAAC,kCAAkC,CAAC;YAC/C;YAEA,IAAI,CAACD,WAAW;gBACd,IAAI,CAACX,MAAM,CAACS,GAAG,CAAC;gBAChB,OAAO,IAAI,CAACP,IAAI,CAAC7C,UAAUwD,UAAU;YACvC;QACF;QAEA,IAAI;YACF,MAAMC,eAAe,MAAMpD,kBAAkB;gBAC3CyB;gBACAX;gBACAY;gBACAC;gBACAc;gBACAb;gBACAyB,UAAU,CAACC;oBACT,MAAMD,WACJzC,UAAUA,UAAUX,YAChBA,SAAS,CAACW,OAAiC,GAC3CX,UAAUsD,MAAM;oBAEtB,OAAOF,SAAS;wBAAC7C;wBAAO8B,QAAQ,IAAI,CAACA,MAAM;wBAAEgB;oBAAM;gBACrD;gBACAE,YAAYxB,UAAUwB,UAAU;gBAChCzB;gBACAb;YACF;YAEA,IAAIkC,iBAAiB,SAAS;gBAC5B,OAAO,IAAI,CAACZ,IAAI,CAAC;YACnB;QACF,EAAE,OAAOH,KAAK;YACZ,OAAO,IAAI,CAACC,MAAM,CAACC,KAAK,CAACF,eAAeoB,QAAQpB,IAAIa,OAAO,GAAGQ,OAAOrB,MAAM;gBAACG,MAAM;YAAC;QACrF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/documents/validate.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {exitCodes} from '@sanity/cli-core'\nimport {ProjectRootNotFoundError} from '@sanity/cli-core/errors'\nimport {SanityCommand} from '@sanity/cli-core/SanityCommand'\nimport {type CliConfig} from '@sanity/cli-core/types'\nimport {confirm, logSymbols} from '@sanity/cli-core/ux'\n\nimport {type Level} from '../../actions/documents/types.js'\nimport {validateDocuments} from '../../actions/documents/validate.js'\nimport {reporters} from '../../actions/documents/validation/reporters/index.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nexport class ValidateDocumentsCommand extends SanityCommand<typeof ValidateDocumentsCommand> {\n static description = 'Validate documents in a dataset against the studio schema'\n\n static examples = [\n {\n command: '<%= config.bin %> <%= command.id %> --workspace default',\n description: 'Validates all documents in a Sanity project with more than one workspace',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --workspace default --dataset staging',\n description: 'Override the dataset specified in the workspace',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --yes > report.txt',\n description: 'Save the results of the report into a file',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --level info',\n description: 'Report out info level validation markers too',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --project-id abc123 --dataset production',\n description: 'Validate documents in a specific project and dataset',\n },\n ]\n\n static flags = {\n ...getProjectIdFlag({\n description:\n 'Override the project ID used. By default, this is derived from the given workspace',\n semantics: 'specify',\n }),\n ...getDatasetFlag({\n description:\n 'Override the dataset used. By default, this is derived from the given workspace',\n semantics: 'specify',\n }),\n file: Flags.string({\n description:\n 'Path to an NDJSON file or tar archive containing an NDJSON file (optionally gzip-compressed)',\n }),\n format: Flags.string({\n description:\n 'The output format used to print the found validation markers and report progress',\n options: ['json', 'ndjson', 'pretty'],\n }),\n level: Flags.custom<Level>({\n default: 'warning',\n description: 'The minimum level reported. Defaults to warning',\n options: ['error', 'warning', 'info'],\n })(),\n 'max-custom-validation-concurrency': Flags.integer({\n default: 5,\n description: 'Specify how many custom validators can run concurrently',\n }),\n 'max-fetch-concurrency': Flags.integer({\n default: 25,\n description: 'Specify how many `client.fetch` requests are allowed to run concurrently',\n }),\n workspace: Flags.string({\n description: 'The name of the workspace to use when downloading and validating all documents',\n }),\n yes: Flags.boolean({\n char: 'y',\n default: false,\n description: 'Skips the first confirmation prompt',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:validate']\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(ValidateDocumentsCommand)\n const {\n dataset,\n file,\n format,\n level,\n 'max-custom-validation-concurrency': maxCustomValidationConcurrency,\n 'max-fetch-concurrency': maxFetchConcurrency,\n 'project-id': projectId,\n workspace,\n } = flags\n const unattendedMode = this.isUnattended()\n\n let workDir: string\n let cliConfig: CliConfig\n try {\n const root = await this.getProjectRoot()\n workDir = root.directory\n cliConfig = await this.getCliConfig()\n } catch (err) {\n if (err instanceof ProjectRootNotFoundError) {\n return this.output.error(\n 'This command must be run from within a Sanity project directory (requires studio schema for validation)',\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n throw err\n }\n\n let ndjsonFilePath\n if (file) {\n const filePath = path.resolve(workDir, file)\n\n let fileStat\n try {\n fileStat = await stat(filePath)\n } catch {\n return this.output.error(\n `File not found: ${file}. Pass an existing NDJSON file or tar archive with \\`--file <path>\\`.`,\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n if (!fileStat.isFile()) {\n return this.output.error(\n `Invalid file path: ${file} is not a file. Pass an NDJSON file or tar archive with \\`--file <path>\\`.`,\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n ndjsonFilePath = filePath\n }\n\n if (!unattendedMode) {\n this.output.log(\n `${styleText('yellow', `${logSymbols.warning} Warning:`)} This command ${\n file\n ? 'reads all documents from your input file'\n : 'downloads all documents from your dataset'\n } and processes them through your local schema within a ` +\n `simulated browser environment.\\n`,\n )\n this.output.log(`Potential pitfalls:\\n`)\n this.output.log(\n `- Processes all documents locally (excluding assets). Large datasets may require more resources.`,\n )\n this.output.log(\n `- Executes all custom validation functions. Some functions may need to be refactored for compatibility.`,\n )\n this.output.log(\n `- Not all standard browser features are available and may cause issues while loading your Studio.`,\n )\n this.output.log(\n `- Adheres to document permissions. Ensure this account can see all desired documents.`,\n )\n if (file) {\n this.output.log(\n `- Checks for missing document references against the live dataset if not found in your file.`,\n )\n }\n\n const confirmed = await confirm({\n default: true,\n message: `Are you sure you want to continue?`,\n })\n\n if (!confirmed) {\n this.output.log('Validation cancelled')\n return this.exit(exitCodes.USER_ABORT)\n }\n }\n\n try {\n const overallLevel = await validateDocuments({\n dataset,\n level,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n ndjsonFilePath,\n projectId,\n reporter: (worker) => {\n const reporter =\n format && format in reporters\n ? reporters[format as keyof typeof reporters]\n : reporters.pretty\n\n return reporter({flags, output: this.output, worker})\n },\n studioHost: cliConfig.studioHost,\n workDir,\n workspace,\n })\n\n if (overallLevel === 'error') {\n return this.exit(exitCodes.RUNTIME_ERROR)\n }\n } catch (err) {\n return this.output.error(err instanceof Error ? err.message : String(err), {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n}\n"],"names":["stat","path","styleText","Flags","exitCodes","ProjectRootNotFoundError","SanityCommand","confirm","logSymbols","validateDocuments","reporters","getDatasetFlag","getProjectIdFlag","ValidateDocumentsCommand","description","examples","command","flags","semantics","file","string","format","options","level","custom","default","integer","workspace","yes","boolean","char","hiddenAliases","run","parse","dataset","maxCustomValidationConcurrency","maxFetchConcurrency","projectId","unattendedMode","isUnattended","workDir","cliConfig","root","getProjectRoot","directory","getCliConfig","err","output","error","exit","RUNTIME_ERROR","ndjsonFilePath","filePath","resolve","fileStat","USAGE_ERROR","isFile","log","warning","confirmed","message","USER_ABORT","overallLevel","reporter","worker","pretty","studioHost","Error","String"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,SAAS,QAAO,mBAAkB;AAC1C,SAAQC,wBAAwB,QAAO,0BAAyB;AAChE,SAAQC,aAAa,QAAO,iCAAgC;AAE5D,SAAQC,OAAO,EAAEC,UAAU,QAAO,sBAAqB;AAGvD,SAAQC,iBAAiB,QAAO,sCAAqC;AACrE,SAAQC,SAAS,QAAO,wDAAuD;AAC/E,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,OAAO,MAAMC,iCAAiCP;IAC5C,OAAOQ,cAAc,4DAA2D;IAEhF,OAAOC,WAAW;QAChB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MAAM,CAACU,GAAG,CACb,CAAC,qFAAqF,CAAC;YAEzF,IAAItC,MAAM;gBACR,IAAI,CAAC4B,MAAM,CAACU,GAAG,CACb,CAAC,4FAA4F,CAAC;YAElG;YAEA,MAAME,YAAY,MAAMpD,QAAQ;gBAC9BkB,SAAS;gBACTmC,SAAS,CAAC,kCAAkC,CAAC;YAC/C;YAEA,IAAI,CAACD,WAAW;gBACd,IAAI,CAACZ,MAAM,CAACU,GAAG,CAAC;gBAChB,OAAO,IAAI,CAACR,IAAI,CAAC7C,UAAUyD,UAAU;YACvC;QACF;QAEA,IAAI;YACF,MAAMC,eAAe,MAAMrD,kBAAkB;gBAC3CyB;gBACAX;gBACAY;gBACAC;gBACAe;gBACAd;gBACA0B,UAAU,CAACC;oBACT,MAAMD,WACJ1C,UAAUA,UAAUX,YAChBA,SAAS,CAACW,OAAiC,GAC3CX,UAAUuD,MAAM;oBAEtB,OAAOF,SAAS;wBAAC9C;wBAAO8B,QAAQ,IAAI,CAACA,MAAM;wBAAEiB;oBAAM;gBACrD;gBACAE,YAAYzB,UAAUyB,UAAU;gBAChC1B;gBACAb;YACF;YAEA,IAAImC,iBAAiB,SAAS;gBAC5B,OAAO,IAAI,CAACb,IAAI,CAAC7C,UAAU8C,aAAa;YAC1C;QACF,EAAE,OAAOJ,KAAK;YACZ,OAAO,IAAI,CAACC,MAAM,CAACC,KAAK,CAACF,eAAeqB,QAAQrB,IAAIc,OAAO,GAAGQ,OAAOtB,MAAM;gBACzEG,MAAM7C,UAAU8C,aAAa;YAC/B;QACF;IACF;AACF"}
@@ -97,13 +97,13 @@ export class GraphQLDeployCommand extends SanityCommand {
97
97
  debug('Schema validation errors: %O', error.problemGroups);
98
98
  error.print(this.output);
99
99
  this.error('Fix the schema errors above and try again', {
100
- exit: 1
100
+ exit: exitCodes.RUNTIME_ERROR
101
101
  });
102
102
  }
103
103
  debug('Failed to resolve GraphQL APIs: %O', error);
104
104
  const message = error instanceof Error ? error.message : String(error);
105
105
  this.error(`Failed to resolve GraphQL APIs: ${message}`, {
106
- exit: 1
106
+ exit: exitCodes.RUNTIME_ERROR
107
107
  });
108
108
  }
109
109
  const hasMultipleApis = flags.api ? flags.api.length > 1 : apiDefs.length > 1;
@@ -139,7 +139,7 @@ export class GraphQLDeployCommand extends SanityCommand {
139
139
  for (const apiId of onlyApis || []){
140
140
  if (!apiDefs.some((apiDef)=>apiDef.id === apiId)) {
141
141
  this.error(`GraphQL API with id "${apiId}" not found`, {
142
- exit: 1
142
+ exit: exitCodes.RUNTIME_ERROR
143
143
  });
144
144
  }
145
145
  }
@@ -152,18 +152,18 @@ export class GraphQLDeployCommand extends SanityCommand {
152
152
  const { apiName } = this.getApiIdentifiers(apiDef, datasetFlag, tagFlag);
153
153
  if (apiNames.has(apiName)) {
154
154
  this.error(`Multiple GraphQL APIs with the same dataset and tag found (${apiName})`, {
155
- exit: 1
155
+ exit: exitCodes.RUNTIME_ERROR
156
156
  });
157
157
  }
158
158
  if (apiDef.id) {
159
159
  if (!apiIdRegex.test(apiDef.id)) {
160
160
  this.error(`Invalid GraphQL API id "${apiDef.id}" - only a-z, 0-9, underscore and dashes are allowed`, {
161
- exit: 1
161
+ exit: exitCodes.RUNTIME_ERROR
162
162
  });
163
163
  }
164
164
  if (apiIds.has(apiDef.id)) {
165
165
  this.error(`Multiple GraphQL APIs with the same ID found (${apiDef.id})`, {
166
- exit: 1
166
+ exit: exitCodes.RUNTIME_ERROR
167
167
  });
168
168
  }
169
169
  apiIds.add(apiDef.id);
@@ -219,7 +219,7 @@ export class GraphQLDeployCommand extends SanityCommand {
219
219
  debug('Failed to get current GraphQL schema properties', err);
220
220
  spin.fail();
221
221
  this.error('Failed to get current GraphQL schema properties', {
222
- exit: 1
222
+ exit: exitCodes.RUNTIME_ERROR
223
223
  });
224
224
  }
225
225
  // CLI flag takes precedence over configuration
@@ -240,7 +240,7 @@ export class GraphQLDeployCommand extends SanityCommand {
240
240
  if (!this.isRecognizedApiGeneration(generation)) {
241
241
  spin.fail();
242
242
  this.error(`Unknown API generation "${generation}" for API at index ${index}`, {
243
- exit: 1
243
+ exit: exitCodes.RUNTIME_ERROR
244
244
  });
245
245
  }
246
246
  const enablePlayground = await this.shouldEnablePlayground({
@@ -261,7 +261,7 @@ export class GraphQLDeployCommand extends SanityCommand {
261
261
  spin.fail();
262
262
  const message = err instanceof Error ? err.message : 'Unknown error';
263
263
  this.error(`Failed to generate schema: ${message}`, {
264
- exit: 1
264
+ exit: exitCodes.RUNTIME_ERROR
265
265
  });
266
266
  }
267
267
  let valid;
@@ -278,7 +278,7 @@ export class GraphQLDeployCommand extends SanityCommand {
278
278
  const validationError = get(err, 'response.body.validationError');
279
279
  spin.fail();
280
280
  this.error(validationError ?? 'Failed to validate GraphQL API', {
281
- exit: 1
281
+ exit: exitCodes.RUNTIME_ERROR
282
282
  });
283
283
  }
284
284
  // when the result is not valid and there are breaking changes afoot!
@@ -356,12 +356,12 @@ export class GraphQLDeployCommand extends SanityCommand {
356
356
  spin.fail();
357
357
  debug('Failed to deploy GraphQL API', error);
358
358
  this.error('Failed to deploy GraphQL API', {
359
- exit: 1
359
+ exit: exitCodes.RUNTIME_ERROR
360
360
  });
361
361
  }
362
362
  }
363
363
  if (hasErrors) {
364
- this.exit(1);
364
+ this.exit(exitCodes.RUNTIME_ERROR);
365
365
  }
366
366
  }
367
367
  filterChanges(valid) {
@@ -396,7 +396,7 @@ export class GraphQLDeployCommand extends SanityCommand {
396
396
  if (validationError) {
397
397
  spin.fail();
398
398
  this.error(`GraphQL schema is not valid:\n\n${validationError}`, {
399
- exit: 1
399
+ exit: exitCodes.RUNTIME_ERROR
400
400
  });
401
401
  }
402
402
  const { breakingChanges, dangerousChanges } = this.filterChanges(valid);