@sanity/cli 7.10.0 → 7.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +31 -22
  2. package/dist/actions/auth/ensureAuthenticated.js +2 -0
  3. package/dist/actions/auth/ensureAuthenticated.js.map +1 -1
  4. package/dist/actions/auth/login/loginInstructions.js +19 -0
  5. package/dist/actions/auth/login/loginInstructions.js.map +1 -0
  6. package/dist/actions/dataset/resolveDataset.js +7 -1
  7. package/dist/actions/dataset/resolveDataset.js.map +1 -1
  8. package/dist/actions/deploy/deployApp.js +17 -12
  9. package/dist/actions/deploy/deployApp.js.map +1 -1
  10. package/dist/actions/deploy/deployStudio.js +2 -0
  11. package/dist/actions/deploy/deployStudio.js.map +1 -1
  12. package/dist/actions/graphql/resolveApiGeneration.js +9 -6
  13. package/dist/actions/graphql/resolveApiGeneration.js.map +1 -1
  14. package/dist/actions/init/initAction.js +23 -15
  15. package/dist/actions/init/initAction.js.map +1 -1
  16. package/dist/actions/manifest/extractCoreAppManifest.js +5 -3
  17. package/dist/actions/manifest/extractCoreAppManifest.js.map +1 -1
  18. package/dist/actions/migration/constants.js +10 -0
  19. package/dist/actions/migration/constants.js.map +1 -0
  20. package/dist/actions/migration/ensureApiVersionFormat.js +16 -0
  21. package/dist/actions/migration/ensureApiVersionFormat.js.map +1 -0
  22. package/dist/actions/migration/fileExists.js +13 -0
  23. package/dist/actions/migration/fileExists.js.map +1 -0
  24. package/dist/actions/migration/prettyMutationFormatter.js +155 -0
  25. package/dist/actions/migration/prettyMutationFormatter.js.map +1 -0
  26. package/dist/actions/migration/resolveMigrationScript.js +75 -0
  27. package/dist/actions/migration/resolveMigrationScript.js.map +1 -0
  28. package/dist/actions/migration/resolveMigrations.js +50 -0
  29. package/dist/actions/migration/resolveMigrations.js.map +1 -0
  30. package/dist/actions/migration/templates/index.js +7 -0
  31. package/dist/actions/migration/templates/index.js.map +1 -0
  32. package/dist/actions/migration/templates/minimalAdvanced.js +21 -0
  33. package/dist/actions/migration/templates/minimalAdvanced.js.map +1 -0
  34. package/dist/actions/migration/templates/minimalSimple.js +61 -0
  35. package/dist/actions/migration/templates/minimalSimple.js.map +1 -0
  36. package/dist/actions/migration/templates/renameField.js +20 -0
  37. package/dist/actions/migration/templates/renameField.js.map +1 -0
  38. package/dist/actions/migration/templates/renameType.js +19 -0
  39. package/dist/actions/migration/templates/renameType.js.map +1 -0
  40. package/dist/actions/migration/templates/stringToPTE.js +32 -0
  41. package/dist/actions/migration/templates/stringToPTE.js.map +1 -0
  42. package/dist/actions/migration/tree.js +111 -0
  43. package/dist/actions/migration/tree.js.map +1 -0
  44. package/dist/actions/preview/previewAction.js +33 -1
  45. package/dist/actions/preview/previewAction.js.map +1 -1
  46. package/dist/actions/schema/listSchemas.js +6 -4
  47. package/dist/actions/schema/listSchemas.js.map +1 -1
  48. package/dist/actions/tokens/validateRole.js +2 -1
  49. package/dist/actions/tokens/validateRole.js.map +1 -1
  50. package/dist/actions/undeploy/runUndeploy.js +13 -4
  51. package/dist/actions/undeploy/runUndeploy.js.map +1 -1
  52. package/dist/commands/backups/disable.js +5 -1
  53. package/dist/commands/backups/disable.js.map +1 -1
  54. package/dist/commands/backups/download.js +30 -6
  55. package/dist/commands/backups/download.js.map +1 -1
  56. package/dist/commands/backups/enable.js +5 -1
  57. package/dist/commands/backups/enable.js.map +1 -1
  58. package/dist/commands/backups/list.js +5 -1
  59. package/dist/commands/backups/list.js.map +1 -1
  60. package/dist/commands/cors/add.js +15 -7
  61. package/dist/commands/cors/add.js.map +1 -1
  62. package/dist/commands/cors/delete.js +6 -1
  63. package/dist/commands/cors/delete.js.map +1 -1
  64. package/dist/commands/datasets/alias/create.js +25 -18
  65. package/dist/commands/datasets/alias/create.js.map +1 -1
  66. package/dist/commands/datasets/alias/delete.js +15 -8
  67. package/dist/commands/datasets/alias/delete.js.map +1 -1
  68. package/dist/commands/datasets/alias/link.js +39 -17
  69. package/dist/commands/datasets/alias/link.js.map +1 -1
  70. package/dist/commands/datasets/alias/unlink.js +23 -2
  71. package/dist/commands/datasets/alias/unlink.js.map +1 -1
  72. package/dist/commands/datasets/copy.js +18 -2
  73. package/dist/commands/datasets/copy.js.map +1 -1
  74. package/dist/commands/datasets/create.js +8 -2
  75. package/dist/commands/datasets/create.js.map +1 -1
  76. package/dist/commands/datasets/delete.js +14 -17
  77. package/dist/commands/datasets/delete.js.map +1 -1
  78. package/dist/commands/datasets/embeddings/disable.js +3 -0
  79. package/dist/commands/datasets/embeddings/disable.js.map +1 -1
  80. package/dist/commands/datasets/embeddings/enable.js +5 -2
  81. package/dist/commands/datasets/embeddings/enable.js.map +1 -1
  82. package/dist/commands/datasets/embeddings/status.js +3 -0
  83. package/dist/commands/datasets/embeddings/status.js.map +1 -1
  84. package/dist/commands/datasets/export.js +27 -15
  85. package/dist/commands/datasets/export.js.map +1 -1
  86. package/dist/commands/datasets/import.js +3 -3
  87. package/dist/commands/datasets/import.js.map +1 -1
  88. package/dist/commands/datasets/visibility/get.js +2 -2
  89. package/dist/commands/datasets/visibility/get.js.map +1 -1
  90. package/dist/commands/datasets/visibility/set.js +2 -2
  91. package/dist/commands/datasets/visibility/set.js.map +1 -1
  92. package/dist/commands/docs/read.js +3 -3
  93. package/dist/commands/docs/read.js.map +1 -1
  94. package/dist/commands/documents/create.js +18 -13
  95. package/dist/commands/documents/create.js.map +1 -1
  96. package/dist/commands/documents/delete.js +3 -3
  97. package/dist/commands/documents/delete.js.map +1 -1
  98. package/dist/commands/documents/get.js +3 -3
  99. package/dist/commands/documents/get.js.map +1 -1
  100. package/dist/commands/documents/query.js +3 -3
  101. package/dist/commands/documents/query.js.map +1 -1
  102. package/dist/commands/documents/validate.js +29 -26
  103. package/dist/commands/documents/validate.js.map +1 -1
  104. package/dist/commands/graphql/deploy.js +20 -16
  105. package/dist/commands/graphql/deploy.js.map +1 -1
  106. package/dist/commands/graphql/undeploy.js +15 -18
  107. package/dist/commands/graphql/undeploy.js.map +1 -1
  108. package/dist/commands/hooks/delete.js +2 -2
  109. package/dist/commands/hooks/delete.js.map +1 -1
  110. package/dist/commands/hooks/logs.js +2 -2
  111. package/dist/commands/hooks/logs.js.map +1 -1
  112. package/dist/commands/login.js +2 -1
  113. package/dist/commands/login.js.map +1 -1
  114. package/dist/commands/media/create-aspect.js +20 -8
  115. package/dist/commands/media/create-aspect.js.map +1 -1
  116. package/dist/commands/media/delete-aspect.js +31 -16
  117. package/dist/commands/media/delete-aspect.js.map +1 -1
  118. package/dist/commands/media/deploy-aspect.js +10 -5
  119. package/dist/commands/media/deploy-aspect.js.map +1 -1
  120. package/dist/commands/media/export.js +9 -4
  121. package/dist/commands/media/export.js.map +1 -1
  122. package/dist/commands/media/import.js +6 -1
  123. package/dist/commands/media/import.js.map +1 -1
  124. package/dist/commands/migrations/create.js +150 -0
  125. package/dist/commands/migrations/create.js.map +1 -0
  126. package/dist/commands/migrations/list.js +64 -0
  127. package/dist/commands/migrations/list.js.map +1 -0
  128. package/dist/commands/migrations/run.js +306 -0
  129. package/dist/commands/migrations/run.js.map +1 -0
  130. package/dist/commands/preview.js +1 -0
  131. package/dist/commands/preview.js.map +1 -1
  132. package/dist/commands/projects/create.js +2 -1
  133. package/dist/commands/projects/create.js.map +1 -1
  134. package/dist/commands/schemas/delete.js +23 -2
  135. package/dist/commands/schemas/delete.js.map +1 -1
  136. package/dist/commands/schemas/deploy.js +6 -4
  137. package/dist/commands/schemas/deploy.js.map +1 -1
  138. package/dist/commands/schemas/extract.js +22 -1
  139. package/dist/commands/schemas/extract.js.map +1 -1
  140. package/dist/commands/schemas/list.js +8 -8
  141. package/dist/commands/schemas/list.js.map +1 -1
  142. package/dist/commands/tokens/{add.js → create.js} +25 -18
  143. package/dist/commands/tokens/create.js.map +1 -0
  144. package/dist/commands/tokens/delete.js +41 -23
  145. package/dist/commands/tokens/delete.js.map +1 -1
  146. package/dist/commands/undeploy.js +2 -7
  147. package/dist/commands/undeploy.js.map +1 -1
  148. package/dist/commands/users/invite.js +25 -3
  149. package/dist/commands/users/invite.js.map +1 -1
  150. package/dist/topicAliases.js +3 -0
  151. package/dist/topicAliases.js.map +1 -1
  152. package/dist/util/formatCliErrorMessages.js +5 -0
  153. package/dist/util/formatCliErrorMessages.js.map +1 -0
  154. package/oclif.config.js +5 -1
  155. package/oclif.manifest.json +326 -121
  156. package/package.json +7 -7
  157. package/dist/commands/tokens/add.js.map +0 -1
@@ -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 {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 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 'No dataset specified. Either configure a dataset in sanity.cli.ts or use the --dataset flag',\n {exit: 1},\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 if (replace && missing) {\n this.error('Cannot use both --replace and --missing', {exit: 1})\n }\n\n if (id && file) {\n this.error('Cannot use --id when specifying a file path', {exit: 1})\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","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","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","error","exit","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,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAE7E,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,MAAMvB,KAAKwB,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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AAU;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,IAAIpC,2BAA2B2F,MAAM;oBACnC,OAAO;wBAACiB,mBAAmBjB;oBAAG;gBAChC;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAEzD,WAAW;YACnE;YAEA,IAAIA,cAAc,mBAAmB;gBACnC,IAAIpC,2BAA2B2F,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,CAAChB,MAAM,CAAC0F,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: 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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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,5 +1,5 @@
1
1
  import { Args } from '@oclif/core';
2
- import { getProjectCliClient, SanityCommand, subdebug } from '@sanity/cli-core';
2
+ import { exitCodes, getProjectCliClient, SanityCommand, subdebug } from '@sanity/cli-core';
3
3
  import { DOCUMENTS_API_VERSION } from '../../actions/documents/constants.js';
4
4
  import { promptForProject } from '../../prompts/promptForProject.js';
5
5
  import { getDatasetFlag, getProjectIdFlag } from '../../util/sharedFlags.js';
@@ -74,8 +74,8 @@ export class DeleteDocumentCommand extends SanityCommand {
74
74
  fallback: ()=>promptForProject({})
75
75
  });
76
76
  if (!cliConfig.api?.dataset && !dataset) {
77
- this.error('No dataset specified. Either configure a dataset in sanity.cli.ts or use the --dataset flag', {
78
- exit: 1
77
+ this.error('Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.', {
78
+ exit: exitCodes.USAGE_ERROR
79
79
  });
80
80
  }
81
81
  const targetDataset = dataset || cliConfig.api?.dataset;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/delete.ts"],"sourcesContent":["import {Args} from '@oclif/core'\nimport {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 'No dataset specified. Either configure a dataset in sanity.cli.ts or use the --dataset flag',\n {exit: 1},\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","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","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,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAE7E,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,IAAIX,KAAKY,MAAM,CAAC;YACdC,aAAa;YACbC,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/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,QAA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,CAAC,yBAAyB,EAAEO,IAAIuC,IAAI,CAAC,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,5 +1,5 @@
1
1
  import { Args, Flags } from '@oclif/core';
2
- import { colorizeJson, getProjectCliClient, SanityCommand, subdebug } from '@sanity/cli-core';
2
+ import { colorizeJson, exitCodes, getProjectCliClient, SanityCommand, subdebug } from '@sanity/cli-core';
3
3
  import { DOCUMENTS_API_VERSION } from '../../actions/documents/constants.js';
4
4
  import { promptForProject } from '../../prompts/promptForProject.js';
5
5
  import { getDatasetFlag, getProjectIdFlag } from '../../util/sharedFlags.js';
@@ -56,8 +56,8 @@ export class GetDocumentCommand extends SanityCommand {
56
56
  fallback: ()=>promptForProject({})
57
57
  });
58
58
  if (!cliConfig.api?.dataset && !dataset) {
59
- this.error('No dataset specified. Either configure a dataset in sanity.cli.ts or use the --dataset flag', {
60
- exit: 1
59
+ this.error('Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.', {
60
+ exit: exitCodes.USAGE_ERROR
61
61
  });
62
62
  }
63
63
  const targetDataset = dataset || cliConfig.api?.dataset;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/get.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {colorizeJson, 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 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 'No dataset specified. Either configure a dataset in sanity.cli.ts or use the --dataset flag',\n {exit: 1},\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","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","targetDataset","projectClient","apiVersion","requireUser","doc","getDocument","log","JSON","stringify","err","message"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,YAAY,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAE3F,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,YAAYb,KAAKc,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,QAAQpB,MAAMqB,OAAO,CAAC;YACpBC,SAAS;YACTR,aAAa;QACf;IACF,EAAC;IAED,OAAgBS,gBAA0B;QAAC;KAAe,CAAA;IAE1D,MAAaC,MAAqB;QAChC,MAAM,EAACb,IAAI,EAAEO,KAAK,EAAC,GAAG,MAAM,IAAI,CAACO,KAAK,CAACf;QACvC,MAAM,EAACE,UAAU,EAAC,GAAGD;QACrB,MAAM,EAACe,OAAO,EAAEN,MAAM,EAAC,GAAGF;QAE1B,MAAMS,YAAY,MAAM,IAAI,CAACC,eAAe;QAE5C,MAAMC,YAAY,MAAM,IAAI,CAACC,YAAY,CAAC;YAACC,UAAU,IAAMzB,iBAAiB,CAAC;QAAE;QAE/E,IAAI,CAACqB,UAAUK,GAAG,EAAEN,WAAW,CAACA,SAAS;YACvC,IAAI,CAACO,KAAK,CACR,+FACA;gBAACC,MAAM;YAAC;QAEZ;QAEA,MAAMC,gBAAgBT,WAAWC,UAAUK,GAAG,EAAEN;QAEhD,IAAI;YACF,MAAMU,gBAAgB,MAAMlC,oBAAoB;gBAC9CmC,YAAYhC;gBACZqB,SAASS;gBACTN;gBACAS,aAAa;YACf;YAEA,MAAMC,MAAM,MAAMH,cAAcI,WAAW,CAAC5B;YAE5C,IAAI,CAAC2B,KAAK;gBACR,IAAI,CAACN,KAAK,CAAC,CAAC,UAAU,EAAErB,WAAW,wBAAwB,EAAEuB,cAAc,CAAC,CAAC,EAAE;oBAACD,MAAM;gBAAC;YACzF;YAEA,sBAAsB;YACtB,IAAId,QAAQ;gBACV,IAAI,CAACqB,GAAG,CAACxC,aAAasC;YACxB,OAAO;gBACL,IAAI,CAACE,GAAG,CAACC,KAAKC,SAAS,CAACJ,KAAK,MAAM;YACrC;QACF,EAAE,OAAON,OAAO;YACd,MAAMW,MAAMX;YAEZxB,iBAAiB,CAAC,wBAAwB,EAAEG,YAAY,EAAEgC;YAC1D,IAAI,CAACX,KAAK,CAAC,CAAC,0BAA0B,EAAEW,IAAIC,OAAO,EAAE,EAAE;gBAACX,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}\"`, {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,MAAMsB,OAAO,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,EAAE;gBAACZ,MAAM;YAAC;QACjE;IACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { Args, Flags } from '@oclif/core';
2
- import { colorizeJson, getProjectCliClient, SanityCommand, subdebug } from '@sanity/cli-core';
2
+ import { colorizeJson, exitCodes, getProjectCliClient, SanityCommand, subdebug } from '@sanity/cli-core';
3
3
  import { DOCUMENTS_API_VERSION } from '../../actions/documents/constants.js';
4
4
  import { promptForProject } from '../../prompts/promptForProject.js';
5
5
  import { getDatasetFlag, getProjectIdFlag } from '../../util/sharedFlags.js';
@@ -73,8 +73,8 @@ export class QueryDocumentCommand extends SanityCommand {
73
73
  });
74
74
  const requireUser = !anonymous;
75
75
  if (!cliConfig.api?.dataset && !dataset) {
76
- this.error('No dataset specified. Either configure a dataset in sanity.cli.ts or use the --dataset flag', {
77
- exit: 1
76
+ this.error('Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.', {
77
+ exit: exitCodes.USAGE_ERROR
78
78
  });
79
79
  }
80
80
  const targetDataset = dataset || cliConfig.api?.dataset;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/query.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {colorizeJson, 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 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 'No dataset specified. Either configure a dataset in sanity.cli.ts or use the --dataset flag',\n {exit: 1},\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","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","targetDataset","targetApiVersion","warn","projectClient","docs","fetch","log","JSON","stringify","err","errorMsg","message","toLowerCase","includes"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,YAAY,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAE3F,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,qBAAqBL,SAAS;AAEpC,OAAO,MAAMM,6BAA6BP;IACxC,OAAgBQ,OAAO;QACrBC,OAAOb,KAAKc,MAAM,CAAC;YACjBC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,sBAAqB;IAEnD,OAAgBE,WAAW;QACzB;YACEC,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SACE;YACFH,aAAa;QACf;QACA;YACEG,SACE;YAC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AAI,CAAC,CAAC,qCAAqC,EAAEzC,sBAAsB,EAAE,CAAC;QAC7E;QAEA,IAAI;YACF,MAAM0C,gBAAgB,MAAM7C,oBAAoB;gBAC9C8B,YAAYa;gBACZZ,SAASW;gBACTR;gBACAI;YACF;YAEA,MAAMQ,OAAO,MAAMD,cAAcE,KAAK,CAACrC;YAEvC,IAAI,CAACoC,MAAM;gBACT,IAAI,CAACN,KAAK,CAAC,6BAA6B;oBAACC,MAAM;gBAAC;YAClD;YAEA,2BAA2B;YAC3B,IAAInB,QAAQ;gBACV,IAAI,CAAC0B,GAAG,CAACjD,aAAa+C;YACxB,OAAO;gBACL,IAAI,CAACE,GAAG,CAACC,KAAKC,SAAS,CAACJ,MAAM,MAAM;YACtC;QACF,EAAE,OAAON,OAAO;YACd,MAAMW,MAAMX;YAEZjC,mBAAmB,CAAC,qBAAqB,EAAEG,OAAO,EAAEyC;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,CAACb,KAAK,CAAC,GAAGY,SAAS,SAAS,EAAE1C,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: 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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;QAErB,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"}
@@ -2,6 +2,7 @@ import { stat } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { styleText } from 'node:util';
4
4
  import { Flags } from '@oclif/core';
5
+ import { exitCodes } from '@sanity/cli-core';
5
6
  import { ProjectRootNotFoundError } from '@sanity/cli-core/errors';
6
7
  import { SanityCommand } from '@sanity/cli-core/SanityCommand';
7
8
  import { confirm, logSymbols } from '@sanity/cli-core/ux';
@@ -42,10 +43,15 @@ export class ValidateDocumentsCommand extends SanityCommand {
42
43
  semantics: 'specify'
43
44
  }),
44
45
  file: Flags.string({
45
- description: 'Provide a path to either an .ndjson file or a tarball containing an .ndjson file'
46
+ description: 'Path to an NDJSON file or tar archive containing an NDJSON file (optionally gzip-compressed)'
46
47
  }),
47
48
  format: Flags.string({
48
- description: 'The output format used to print the found validation markers and report progress'
49
+ description: 'The output format used to print the found validation markers and report progress',
50
+ options: [
51
+ 'json',
52
+ 'ndjson',
53
+ 'pretty'
54
+ ]
49
55
  }),
50
56
  level: Flags.custom({
51
57
  default: 'warning',
@@ -79,7 +85,7 @@ export class ValidateDocumentsCommand extends SanityCommand {
79
85
  async run() {
80
86
  const { flags } = await this.parse(ValidateDocumentsCommand);
81
87
  const { dataset, file, format, level, 'max-custom-validation-concurrency': maxCustomValidationConcurrency, 'max-fetch-concurrency': maxFetchConcurrency, 'project-id': projectId, workspace } = flags;
82
- const unattendedMode = Boolean(flags.yes);
88
+ const unattendedMode = this.isUnattended();
83
89
  let workDir;
84
90
  let cliConfig;
85
91
  try {
@@ -94,6 +100,24 @@ export class ValidateDocumentsCommand extends SanityCommand {
94
100
  }
95
101
  throw err;
96
102
  }
103
+ let ndjsonFilePath;
104
+ if (file) {
105
+ const filePath = path.resolve(workDir, file);
106
+ let fileStat;
107
+ try {
108
+ fileStat = await stat(filePath);
109
+ } catch {
110
+ return this.output.error(`File not found: ${file}. Pass an existing NDJSON file or tar archive with \`--file <path>\`.`, {
111
+ exit: exitCodes.USAGE_ERROR
112
+ });
113
+ }
114
+ if (!fileStat.isFile()) {
115
+ return this.output.error(`Invalid file path: ${file} is not a file. Pass an NDJSON file or tar archive with \`--file <path>\`.`, {
116
+ exit: exitCodes.USAGE_ERROR
117
+ });
118
+ }
119
+ ndjsonFilePath = filePath;
120
+ }
97
121
  if (!unattendedMode) {
98
122
  this.output.log(`${styleText('yellow', `${logSymbols.warning} Warning:`)} This command ${file ? 'reads all documents from your input file' : 'downloads all documents from your dataset'} and processes them through your local schema within a ` + `simulated browser environment.\n`);
99
123
  this.output.log(`Potential pitfalls:\n`);
@@ -109,31 +133,10 @@ export class ValidateDocumentsCommand extends SanityCommand {
109
133
  message: `Are you sure you want to continue?`
110
134
  });
111
135
  if (!confirmed) {
112
- return this.output.error('User aborted', {
113
- exit: 1
114
- });
136
+ this.output.log('Validation cancelled');
137
+ return this.exit(exitCodes.USER_ABORT);
115
138
  }
116
139
  }
117
- if (format && !(format in reporters)) {
118
- const formatter = new Intl.ListFormat('en-US', {
119
- style: 'long',
120
- type: 'conjunction'
121
- });
122
- return this.output.error(`Did not recognize format '${format}'. Available formats are ${formatter.format(Object.keys(reporters).map((key)=>`'${key}'`))}`, {
123
- exit: 1
124
- });
125
- }
126
- let ndjsonFilePath;
127
- if (file) {
128
- const filePath = path.resolve(workDir, file);
129
- const st = await stat(filePath);
130
- if (!st.isFile()) {
131
- return this.output.error(`'--file' must point to a valid ndjson file or tarball`, {
132
- exit: 1
133
- });
134
- }
135
- ndjsonFilePath = filePath;
136
- }
137
140
  try {
138
141
  const overallLevel = await validateDocuments({
139
142
  dataset,
@@ -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 {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 'Provide a path to either an .ndjson file or a tarball containing an .ndjson file',\n }),\n format: Flags.string({\n description:\n 'The output format used to print the found validation markers and report progress',\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 = Boolean(flags.yes)\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 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 return this.output.error('User aborted', {exit: 1})\n }\n }\n\n if (format && !(format in reporters)) {\n const formatter = new Intl.ListFormat('en-US', {\n style: 'long',\n type: 'conjunction',\n })\n return this.output.error(\n `Did not recognize format '${format}'. Available formats are ${formatter.format(\n Object.keys(reporters).map((key) => `'${key}'`),\n )}`,\n {exit: 1},\n )\n }\n\n let ndjsonFilePath\n if (file) {\n const filePath = path.resolve(workDir, file)\n\n const st = await stat(filePath)\n if (!st.isFile()) {\n return this.output.error(`'--file' must point to a valid ndjson file or tarball`, {exit: 1})\n }\n\n ndjsonFilePath = filePath\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","ProjectRootNotFoundError","SanityCommand","confirm","logSymbols","validateDocuments","reporters","getDatasetFlag","getProjectIdFlag","ValidateDocumentsCommand","description","examples","command","flags","semantics","file","string","format","level","custom","default","options","integer","workspace","yes","boolean","char","hiddenAliases","run","parse","dataset","maxCustomValidationConcurrency","maxFetchConcurrency","projectId","unattendedMode","Boolean","workDir","cliConfig","root","getProjectRoot","directory","getCliConfig","err","output","error","exit","log","warning","confirmed","message","formatter","Intl","ListFormat","style","type","Object","keys","map","key","ndjsonFilePath","filePath","resolve","st","isFile","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,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,aA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C,IAC7C,EACH;gBAACb,MAAM;YAAC;QAEZ;QAEA,IAAIc;QACJ,IAAI5C,MAAM;YACR,MAAM6C,WAAW9D,KAAK+D,OAAO,CAACzB,SAASrB;YAEvC,MAAM+C,KAAK,MAAMjE,KAAK+D;YACtB,IAAI,CAACE,GAAGC,MAAM,IAAI;gBAChB,OAAO,IAAI,CAACpB,MAAM,CAACC,KAAK,CAAC,CAAC,qDAAqD,CAAC,EAAE;oBAACC,MAAM;gBAAC;YAC5F;YAEAc,iBAAiBC;QACnB;QAEA,IAAI;YACF,MAAMI,eAAe,MAAM3D,kBAAkB;gBAC3CyB;gBACAZ;gBACAa;gBACAC;gBACA2B;gBACA1B;gBACAgC,UAAU,CAACC;oBACT,MAAMD,WACJhD,UAAUA,UAAUX,YAChBA,SAAS,CAACW,OAAiC,GAC3CX,UAAU6D,MAAM;oBAEtB,OAAOF,SAAS;wBAACpD;wBAAO8B,QAAQ,IAAI,CAACA,MAAM;wBAAEuB;oBAAM;gBACrD;gBACAE,YAAY/B,UAAU+B,UAAU;gBAChChC;gBACAb;YACF;YAEA,IAAIyC,iBAAiB,SAAS;gBAC5B,OAAO,IAAI,CAACnB,IAAI,CAAC;YACnB;QACF,EAAE,OAAOH,KAAK;YACZ,OAAO,IAAI,CAACC,MAAM,CAACC,KAAK,CAACF,eAAe2B,QAAQ3B,IAAIO,OAAO,GAAGqB,OAAO5B,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: 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;I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,CAAC,iGAAiG,CAAC;YAErG,IAAI,CAACT,MAAM,CAACS,GAAG,CACb,CAAC,qFAAqF,CAAC;YAEzF,IAAIrC,MAAM;gBACR,IAAI,CAAC4B,MAAM,CAACS,GAAG,CACb,CAAC,4FAA4F,CAAC;YAElG;YAEA,MAAME,YAAY,MAAMnD,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,5 +1,5 @@
1
1
  import { Flags } from '@oclif/core';
2
- import { isInteractive, SanityCommand } from '@sanity/cli-core';
2
+ import { exitCodes, SanityCommand } from '@sanity/cli-core';
3
3
  import { confirm, spinner } from '@sanity/cli-core/ux';
4
4
  import get from 'lodash-es/get.js';
5
5
  import { extractGraphQLAPIs } from '../../actions/graphql/extractGraphQLAPIs.js';
@@ -119,15 +119,18 @@ export class GraphQLDeployCommand extends SanityCommand {
119
119
  this.warn(`This will use the specified flag(s) for ALL APIs, overriding config!`);
120
120
  if (flags.force) {
121
121
  this.warn(`--force specified, continuing...`);
122
+ } else if (this.isUnattended()) {
123
+ this.error('Flag overrides for multiple APIs require confirmation. Pass `--force` to continue.', {
124
+ exit: exitCodes.USAGE_ERROR
125
+ });
122
126
  } else {
123
127
  const confirmed = await confirm({
124
128
  default: false,
125
129
  message: 'Continue with flag overrides for all APIs?'
126
130
  });
127
131
  if (!confirmed) {
128
- this.error('Operation cancelled', {
129
- exit: 1
130
- });
132
+ this.log('GraphQL deployment cancelled');
133
+ this.exit(exitCodes.USER_ABORT);
131
134
  }
132
135
  }
133
136
  }
@@ -181,8 +184,8 @@ export class GraphQLDeployCommand extends SanityCommand {
181
184
  spin = spinner(`Generating GraphQL API: ${apiName}`).start();
182
185
  if (!dataset) {
183
186
  spin.fail();
184
- this.error(`No dataset specified for API at index ${index}`, {
185
- exit: 1
187
+ this.error(`Dataset is required for API at index ${index}. Pass it with \`--dataset <name>\` or configure a dataset for the API.`, {
188
+ exit: exitCodes.USAGE_ERROR
186
189
  });
187
190
  }
188
191
  // Handle extraction errors early (computed in worker), before network calls and prompts.
@@ -226,12 +229,13 @@ export class GraphQLDeployCommand extends SanityCommand {
226
229
  force: flags.force,
227
230
  index,
228
231
  output: this.output,
229
- specifiedGeneration
232
+ specifiedGeneration,
233
+ unattended: this.isUnattended()
230
234
  });
231
235
  if (!generation) {
232
- // User cancelled
233
- spin.fail();
234
- continue;
236
+ spin.stop();
237
+ this.log('GraphQL deployment cancelled');
238
+ this.exit(exitCodes.USER_ABORT);
235
239
  }
236
240
  if (!this.isRecognizedApiGeneration(generation)) {
237
241
  spin.fail();
@@ -289,11 +293,11 @@ export class GraphQLDeployCommand extends SanityCommand {
289
293
  hasErrors = true;
290
294
  continue;
291
295
  }
292
- if (!isInteractive()) {
296
+ if (this.isUnattended()) {
293
297
  spin.fail();
294
298
  this.renderBreakingChanges(valid);
295
- this.error('Dangerous changes found - falling back. Re-run the command with the `--force` flag to force deployment.', {
296
- exit: 1
299
+ this.error('GraphQL deployment requires confirmation because the schema contains dangerous changes. Pass `--force` to continue.', {
300
+ exit: exitCodes.USAGE_ERROR
297
301
  });
298
302
  }
299
303
  spin.stop();
@@ -303,8 +307,8 @@ export class GraphQLDeployCommand extends SanityCommand {
303
307
  message: 'Do you want to deploy a new API despite the dangerous changes?'
304
308
  });
305
309
  if (!shouldDeploy) {
306
- spin.fail();
307
- continue;
310
+ this.log('GraphQL deployment cancelled');
311
+ this.exit(exitCodes.USER_ABORT);
308
312
  }
309
313
  spin.succeed();
310
314
  } else if (dryRun) {
@@ -439,7 +443,7 @@ export class GraphQLDeployCommand extends SanityCommand {
439
443
  return playgroundCurrentlyEnabled;
440
444
  }
441
445
  // If no API is deployed, default to true if non-interactive
442
- if (!isInteractive()) {
446
+ if (this.isUnattended()) {
443
447
  return true;
444
448
  }
445
449
  // Interactive environment, so prompt the user