@sanity/cli 7.12.0 → 7.13.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 (177) hide show
  1. package/README.md +88 -0
  2. package/dist/actions/api/constants.js +13 -0
  3. package/dist/actions/api/constants.js.map +1 -0
  4. package/dist/actions/api/distillApiRoutes.js +106 -0
  5. package/dist/actions/api/distillApiRoutes.js.map +1 -0
  6. package/dist/actions/api/errors.js +18 -0
  7. package/dist/actions/api/errors.js.map +1 -0
  8. package/dist/actions/api/parseFields.js +183 -0
  9. package/dist/actions/api/parseFields.js.map +1 -0
  10. package/dist/actions/api/resolveEndpoint.js +159 -0
  11. package/dist/actions/api/resolveEndpoint.js.map +1 -0
  12. package/dist/actions/api/types.js +10 -0
  13. package/dist/actions/api/types.js.map +1 -0
  14. package/dist/actions/build/buildApp.js +4 -2
  15. package/dist/actions/build/buildApp.js.map +1 -1
  16. package/dist/actions/build/buildStudio.js +105 -14
  17. package/dist/actions/build/buildStudio.js.map +1 -1
  18. package/dist/actions/build/eventListenerFactory.js +70 -0
  19. package/dist/actions/build/eventListenerFactory.js.map +1 -0
  20. package/dist/actions/dev/servers/startStudioDevServer.js +5 -1
  21. package/dist/actions/dev/servers/startStudioDevServer.js.map +1 -1
  22. package/dist/commands/api.js +294 -0
  23. package/dist/commands/api.js.map +1 -0
  24. package/dist/commands/backups/disable.js +4 -4
  25. package/dist/commands/backups/disable.js.map +1 -1
  26. package/dist/commands/backups/download.js +7 -7
  27. package/dist/commands/backups/download.js.map +1 -1
  28. package/dist/commands/backups/enable.js +4 -4
  29. package/dist/commands/backups/enable.js.map +1 -1
  30. package/dist/commands/backups/list.js +7 -7
  31. package/dist/commands/backups/list.js.map +1 -1
  32. package/dist/commands/codemod.js +5 -5
  33. package/dist/commands/codemod.js.map +1 -1
  34. package/dist/commands/cors/add.js +1 -1
  35. package/dist/commands/cors/add.js.map +1 -1
  36. package/dist/commands/cors/delete.js +4 -4
  37. package/dist/commands/cors/delete.js.map +1 -1
  38. package/dist/commands/cors/list.js +2 -2
  39. package/dist/commands/cors/list.js.map +1 -1
  40. package/dist/commands/datasets/alias/create.js +5 -5
  41. package/dist/commands/datasets/alias/create.js.map +1 -1
  42. package/dist/commands/datasets/alias/delete.js +2 -2
  43. package/dist/commands/datasets/alias/delete.js.map +1 -1
  44. package/dist/commands/datasets/alias/link.js +5 -5
  45. package/dist/commands/datasets/alias/link.js.map +1 -1
  46. package/dist/commands/datasets/alias/unlink.js +3 -3
  47. package/dist/commands/datasets/alias/unlink.js.map +1 -1
  48. package/dist/commands/datasets/copy.js +7 -7
  49. package/dist/commands/datasets/copy.js.map +1 -1
  50. package/dist/commands/datasets/create.js +3 -3
  51. package/dist/commands/datasets/create.js.map +1 -1
  52. package/dist/commands/datasets/delete.js +2 -2
  53. package/dist/commands/datasets/delete.js.map +1 -1
  54. package/dist/commands/datasets/embeddings/disable.js +3 -3
  55. package/dist/commands/datasets/embeddings/disable.js.map +1 -1
  56. package/dist/commands/datasets/embeddings/enable.js +5 -5
  57. package/dist/commands/datasets/embeddings/enable.js.map +1 -1
  58. package/dist/commands/datasets/embeddings/status.js +3 -3
  59. package/dist/commands/datasets/embeddings/status.js.map +1 -1
  60. package/dist/commands/datasets/export.js +6 -6
  61. package/dist/commands/datasets/export.js.map +1 -1
  62. package/dist/commands/datasets/import.js +3 -3
  63. package/dist/commands/datasets/import.js.map +1 -1
  64. package/dist/commands/datasets/list.js +2 -2
  65. package/dist/commands/datasets/list.js.map +1 -1
  66. package/dist/commands/datasets/visibility/get.js +2 -2
  67. package/dist/commands/datasets/visibility/get.js.map +1 -1
  68. package/dist/commands/datasets/visibility/set.js +3 -3
  69. package/dist/commands/datasets/visibility/set.js.map +1 -1
  70. package/dist/commands/deploy.js +2 -2
  71. package/dist/commands/deploy.js.map +1 -1
  72. package/dist/commands/dev.js +2 -2
  73. package/dist/commands/dev.js.map +1 -1
  74. package/dist/commands/docs/read.js +1 -1
  75. package/dist/commands/docs/read.js.map +1 -1
  76. package/dist/commands/docs/search.js +3 -3
  77. package/dist/commands/docs/search.js.map +1 -1
  78. package/dist/commands/doctor.js +3 -3
  79. package/dist/commands/doctor.js.map +1 -1
  80. package/dist/commands/documents/create.js +3 -3
  81. package/dist/commands/documents/create.js.map +1 -1
  82. package/dist/commands/documents/delete.js +3 -3
  83. package/dist/commands/documents/delete.js.map +1 -1
  84. package/dist/commands/documents/get.js +2 -2
  85. package/dist/commands/documents/get.js.map +1 -1
  86. package/dist/commands/documents/query.js +2 -2
  87. package/dist/commands/documents/query.js.map +1 -1
  88. package/dist/commands/documents/validate.js +3 -3
  89. package/dist/commands/documents/validate.js.map +1 -1
  90. package/dist/commands/graphql/deploy.js +13 -13
  91. package/dist/commands/graphql/deploy.js.map +1 -1
  92. package/dist/commands/graphql/list.js +2 -2
  93. package/dist/commands/graphql/list.js.map +1 -1
  94. package/dist/commands/graphql/undeploy.js +2 -2
  95. package/dist/commands/graphql/undeploy.js.map +1 -1
  96. package/dist/commands/hooks/attempt.js +2 -2
  97. package/dist/commands/hooks/attempt.js.map +1 -1
  98. package/dist/commands/hooks/create.js +3 -3
  99. package/dist/commands/hooks/create.js.map +1 -1
  100. package/dist/commands/hooks/delete.js +4 -4
  101. package/dist/commands/hooks/delete.js.map +1 -1
  102. package/dist/commands/hooks/list.js +2 -2
  103. package/dist/commands/hooks/list.js.map +1 -1
  104. package/dist/commands/hooks/logs.js +5 -5
  105. package/dist/commands/hooks/logs.js.map +1 -1
  106. package/dist/commands/login.js +2 -2
  107. package/dist/commands/login.js.map +1 -1
  108. package/dist/commands/logout.js +2 -2
  109. package/dist/commands/logout.js.map +1 -1
  110. package/dist/commands/manifest/extract.js +3 -3
  111. package/dist/commands/manifest/extract.js.map +1 -1
  112. package/dist/commands/mcp/configure.js +4 -4
  113. package/dist/commands/mcp/configure.js.map +1 -1
  114. package/dist/commands/media/create-aspect.js +3 -3
  115. package/dist/commands/media/create-aspect.js.map +1 -1
  116. package/dist/commands/media/delete-aspect.js +1 -1
  117. package/dist/commands/media/delete-aspect.js.map +1 -1
  118. package/dist/commands/media/deploy-aspect.js +4 -4
  119. package/dist/commands/media/deploy-aspect.js.map +1 -1
  120. package/dist/commands/media/export.js +7 -7
  121. package/dist/commands/media/export.js.map +1 -1
  122. package/dist/commands/media/import.js +6 -6
  123. package/dist/commands/media/import.js.map +1 -1
  124. package/dist/commands/migrations/create.js +4 -4
  125. package/dist/commands/migrations/create.js.map +1 -1
  126. package/dist/commands/migrations/list.js +2 -2
  127. package/dist/commands/migrations/list.js.map +1 -1
  128. package/dist/commands/migrations/run.js +14 -14
  129. package/dist/commands/migrations/run.js.map +1 -1
  130. package/dist/commands/openapi/get.js +3 -3
  131. package/dist/commands/openapi/get.js.map +1 -1
  132. package/dist/commands/openapi/list.js +2 -2
  133. package/dist/commands/openapi/list.js.map +1 -1
  134. package/dist/commands/organizations/create.js +5 -5
  135. package/dist/commands/organizations/create.js.map +1 -1
  136. package/dist/commands/organizations/delete.js +6 -6
  137. package/dist/commands/organizations/delete.js.map +1 -1
  138. package/dist/commands/organizations/get.js +3 -3
  139. package/dist/commands/organizations/get.js.map +1 -1
  140. package/dist/commands/organizations/list.js +2 -2
  141. package/dist/commands/organizations/list.js.map +1 -1
  142. package/dist/commands/organizations/update.js +6 -6
  143. package/dist/commands/organizations/update.js.map +1 -1
  144. package/dist/commands/preview.js +2 -2
  145. package/dist/commands/preview.js.map +1 -1
  146. package/dist/commands/projects/create.js +2 -2
  147. package/dist/commands/projects/create.js.map +1 -1
  148. package/dist/commands/projects/list.js +2 -2
  149. package/dist/commands/projects/list.js.map +1 -1
  150. package/dist/commands/schemas/delete.js +2 -2
  151. package/dist/commands/schemas/delete.js.map +1 -1
  152. package/dist/commands/schemas/deploy.js +2 -2
  153. package/dist/commands/schemas/deploy.js.map +1 -1
  154. package/dist/commands/schemas/list.js +1 -1
  155. package/dist/commands/schemas/list.js.map +1 -1
  156. package/dist/commands/schemas/validate.js +2 -1
  157. package/dist/commands/schemas/validate.js.map +1 -1
  158. package/dist/commands/skills/install.js +2 -2
  159. package/dist/commands/skills/install.js.map +1 -1
  160. package/dist/commands/telemetry/disable.js +2 -2
  161. package/dist/commands/telemetry/disable.js.map +1 -1
  162. package/dist/commands/telemetry/enable.js +2 -2
  163. package/dist/commands/telemetry/enable.js.map +1 -1
  164. package/dist/commands/tokens/create.js +2 -2
  165. package/dist/commands/tokens/create.js.map +1 -1
  166. package/dist/commands/tokens/delete.js +2 -2
  167. package/dist/commands/tokens/delete.js.map +1 -1
  168. package/dist/commands/tokens/list.js +2 -2
  169. package/dist/commands/tokens/list.js.map +1 -1
  170. package/dist/commands/users/invite.js +3 -3
  171. package/dist/commands/users/invite.js.map +1 -1
  172. package/dist/generated/apiRoutes.js +401 -0
  173. package/dist/generated/apiRoutes.js.map +1 -0
  174. package/dist/services/api.js +116 -0
  175. package/dist/services/api.js.map +1 -0
  176. package/oclif.manifest.json +433 -252
  177. package/package.json +5 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commands/deploy.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {Args, Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {confirm} from '@sanity/cli-core/ux'\n\nimport {deployApp} from '../actions/deploy/deployApp.js'\nimport {deployDebug} from '../actions/deploy/deployDebug.js'\nimport {deployStudio} from '../actions/deploy/deployStudio.js'\nimport {determineIsApp} from '../util/determineIsApp.js'\nimport {dirIsEmptyOrNonExistent} from '../util/dirIsEmptyOrNonExistent.js'\n\nexport class DeployCommand extends SanityCommand<typeof DeployCommand> {\n static override args = {\n sourceDir: Args.directory({\n description: 'Source directory',\n }),\n }\n\n static override description = 'Builds and deploys Sanity Studio or application to Sanity hosting'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Build and deploy the studio to Sanity hosting',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --no-minify --source-maps',\n description: 'Deploys non-minified build with source maps',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --schema-required',\n description:\n 'Fail fast on schema store fails - for when other services rely on the stored schema',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --external',\n description: 'Register an externally hosted studio (studioHost contains full URL)',\n },\n ]\n\n static override flags = {\n 'auto-updates': Flags.boolean({\n allowNo: true,\n deprecated: true,\n description: 'Automatically update the studio to the latest version',\n }),\n build: Flags.boolean({\n allowNo: true,\n default: true,\n description:\n 'Build the studio before deploying (use --no-build to deploy existing `dist/` output)',\n }),\n 'dry-run': Flags.boolean({\n default: false,\n description: 'Report what would be deployed without uploading or creating anything',\n }),\n external: Flags.boolean({\n default: false,\n description: 'Register an externally hosted studio',\n exclusive: ['source-maps', 'minify', 'build'],\n }),\n json: Flags.boolean({\n char: 'j',\n default: false,\n description: 'Output the result as JSON',\n }),\n minify: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Minify built JavaScript (use --no-minify to skip for faster builds)',\n }),\n 'schema-required': Flags.boolean({\n default: false,\n description: 'Fail if schema deployment fails',\n }),\n 'source-maps': Flags.boolean({\n default: false,\n description: 'Enable source maps for built bundles (increases size of bundle)',\n }),\n title: Flags.string({\n description:\n 'Title for a newly created application or studio. For apps it also skips the interactive title prompt, enabling unattended creation',\n }),\n url: Flags.string({\n description:\n 'Studio URL for deployment. For external studios, the full URL. For hosted studios, the hostname (e.g. \"my-studio\" or \"my-studio.sanity.studio\")',\n }),\n verbose: Flags.boolean({\n default: false,\n description: 'Enable verbose logging',\n }),\n yes: Flags.boolean({\n char: 'y',\n default: false,\n description:\n 'Unattended mode, answers \"yes\" to any \"yes/no\" prompt and otherwise uses defaults',\n }),\n }\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(DeployCommand)\n\n const cliConfig = await this.getCliConfig()\n const projectRoot = await this.getProjectRoot()\n\n const isApp = determineIsApp(cliConfig)\n\n const defaultOutputDir = path.resolve(path.join(projectRoot.directory, 'dist'))\n const sourceDir = path.resolve(process.cwd(), this.args.sourceDir || defaultOutputDir)\n\n // Skip the directory check if the studio is externally hosted\n if (this.args.sourceDir && this.args.sourceDir !== 'dist' && !flags.external) {\n let relativeOutput = path.relative(process.cwd(), sourceDir)\n if (relativeOutput[0] !== '.') {\n relativeOutput = `./${relativeOutput}`\n }\n\n if (!this.isUnattended() && !flags['dry-run']) {\n const isEmpty = await dirIsEmptyOrNonExistent(sourceDir)\n const shouldProceed =\n isEmpty ||\n (await confirm({\n default: false,\n message: `\"${relativeOutput}\" is not empty, do you want to proceed?`,\n }))\n\n if (!shouldProceed) {\n this.output.error('Cancelled.', {exit: 1})\n }\n }\n\n // Keep --json's stdout clean for the payload\n if (!flags.json) this.output.log(`Building to ${relativeOutput}\\n`)\n }\n\n // Force yes downstream: build/app resolution otherwise prompts for prerelease/version choices\n const deployFlags = this.isUnattended() || flags['dry-run'] ? {...flags, yes: true} : flags\n\n if (isApp) {\n deployDebug('Deploying app')\n await deployApp({\n cliConfig,\n flags: deployFlags,\n output: this.output,\n projectRoot,\n sourceDir,\n })\n } else {\n deployDebug('Deploying studio')\n await deployStudio({\n cliConfig,\n flags: deployFlags,\n output: this.output,\n projectRoot,\n sourceDir,\n })\n }\n }\n}\n"],"names":["path","Args","Flags","SanityCommand","confirm","deployApp","deployDebug","deployStudio","determineIsApp","dirIsEmptyOrNonExistent","DeployCommand","args","sourceDir","directory","description","examples","command","flags","boolean","allowNo","deprecated","build","default","external","exclusive","json","char","minify","title","string","url","verbose","yes","run","parse","cliConfig","getCliConfig","projectRoot","getProjectRoot","isApp","defaultOutputDir","resolve","join","process","cwd","relativeOutput","relative","isUnattended","isEmpty","shouldProceed","message","output","error","exit","log","deployFlags"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,OAAO,QAAO,sBAAqB;AAE3C,SAAQC,SAAS,QAAO,iCAAgC;AACxD,SAAQC,WAAW,QAAO,m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CAAC,YAAY,EAAET,eAAe,EAAE,CAAC;QACpE;QAEA,8FAA8F;QAC9F,MAAMU,cAAc,IAAI,CAACR,YAAY,MAAM9B,KAAK,CAAC,UAAU,GAAG;YAAC,GAAGA,KAAK;YAAEe,KAAK;QAAI,IAAIf;QAEtF,IAAIsB,OAAO;YACTjC,YAAY;YACZ,MAAMD,UAAU;gBACd8B;gBACAlB,OAAOsC;gBACPJ,QAAQ,IAAI,CAACA,MAAM;gBACnBd;gBACAzB;YACF;QACF,OAAO;YACLN,YAAY;YACZ,MAAMC,aAAa;gBACjB4B;gBACAlB,OAAOsC;gBACPJ,QAAQ,IAAI,CAACA,MAAM;gBACnBd;gBACAzB;YACF;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/commands/deploy.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, SanityCommand} from '@sanity/cli-core'\nimport {confirm} from '@sanity/cli-core/ux'\n\nimport {deployApp} from '../actions/deploy/deployApp.js'\nimport {deployDebug} from '../actions/deploy/deployDebug.js'\nimport {deployStudio} from '../actions/deploy/deployStudio.js'\nimport {determineIsApp} from '../util/determineIsApp.js'\nimport {dirIsEmptyOrNonExistent} from '../util/dirIsEmptyOrNonExistent.js'\n\nexport class DeployCommand extends SanityCommand<typeof DeployCommand> {\n static override args = {\n sourceDir: Args.directory({\n description: 'Source directory',\n }),\n }\n\n static override description = 'Builds and deploys Sanity Studio or application to Sanity hosting'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Build and deploy the studio to Sanity hosting',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --no-minify --source-maps',\n description: 'Deploys non-minified build with source maps',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --schema-required',\n description:\n 'Fail fast on schema store fails - for when other services rely on the stored schema',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --external',\n description: 'Register an externally hosted studio (studioHost contains full URL)',\n },\n ]\n\n static override flags = {\n 'auto-updates': Flags.boolean({\n allowNo: true,\n deprecated: true,\n description: 'Automatically update the studio to the latest version',\n }),\n build: Flags.boolean({\n allowNo: true,\n default: true,\n description:\n 'Build the studio before deploying (use --no-build to deploy existing `dist/` output)',\n }),\n 'dry-run': Flags.boolean({\n default: false,\n description: 'Report what would be deployed without uploading or creating anything',\n }),\n external: Flags.boolean({\n default: false,\n description: 'Register an externally hosted studio',\n exclusive: ['source-maps', 'minify', 'build'],\n }),\n json: Flags.boolean({\n char: 'j',\n default: false,\n description: 'Output the result as JSON',\n }),\n minify: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Minify built JavaScript (use --no-minify to skip for faster builds)',\n }),\n 'schema-required': Flags.boolean({\n default: false,\n description: 'Fail if schema deployment fails',\n }),\n 'source-maps': Flags.boolean({\n default: false,\n description: 'Enable source maps for built bundles (increases size of bundle)',\n }),\n title: Flags.string({\n description:\n 'Title for a newly created application or studio. For apps it also skips the interactive title prompt, enabling unattended creation',\n }),\n url: Flags.string({\n description:\n 'Studio URL for deployment. For external studios, the full URL. For hosted studios, the hostname (e.g. \"my-studio\" or \"my-studio.sanity.studio\")',\n }),\n verbose: Flags.boolean({\n default: false,\n description: 'Enable verbose logging',\n }),\n yes: Flags.boolean({\n char: 'y',\n default: false,\n description:\n 'Unattended mode, answers \"yes\" to any \"yes/no\" prompt and otherwise uses defaults',\n }),\n }\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(DeployCommand)\n\n const cliConfig = await this.getCliConfig()\n const projectRoot = await this.getProjectRoot()\n\n const isApp = determineIsApp(cliConfig)\n\n const defaultOutputDir = path.resolve(path.join(projectRoot.directory, 'dist'))\n const sourceDir = path.resolve(process.cwd(), this.args.sourceDir || defaultOutputDir)\n\n // Skip the directory check if the studio is externally hosted\n if (this.args.sourceDir && this.args.sourceDir !== 'dist' && !flags.external) {\n let relativeOutput = path.relative(process.cwd(), sourceDir)\n if (relativeOutput[0] !== '.') {\n relativeOutput = `./${relativeOutput}`\n }\n\n if (!this.isUnattended() && !flags['dry-run']) {\n const isEmpty = await dirIsEmptyOrNonExistent(sourceDir)\n const shouldProceed =\n isEmpty ||\n (await confirm({\n default: false,\n message: `\"${relativeOutput}\" is not empty, do you want to proceed?`,\n }))\n\n if (!shouldProceed) {\n this.output.error('Cancelled.', {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n // Keep --json's stdout clean for the payload\n if (!flags.json) this.output.log(`Building to ${relativeOutput}\\n`)\n }\n\n // Force yes downstream: build/app resolution otherwise prompts for prerelease/version choices\n const deployFlags = this.isUnattended() || flags['dry-run'] ? {...flags, yes: true} : flags\n\n if (isApp) {\n deployDebug('Deploying app')\n await deployApp({\n cliConfig,\n flags: deployFlags,\n output: this.output,\n projectRoot,\n sourceDir,\n })\n } else {\n deployDebug('Deploying studio')\n await deployStudio({\n cliConfig,\n flags: deployFlags,\n output: this.output,\n projectRoot,\n sourceDir,\n })\n }\n }\n}\n"],"names":["path","Args","Flags","exitCodes","SanityCommand","confirm","deployApp","deployDebug","deployStudio","determineIsApp","dirIsEmptyOrNonExistent","DeployCommand","args","sourceDir","directory","description","examples","command","flags","boolean","allowNo","deprecated","build","default","external","exclusive","json","char","minify","title","string","url","verbose","yes","run","parse","cliConfig","getCliConfig","projectRoot","getProjectRoot","isApp","defaultOutputDir","resolve","join","process","cwd","relativeOutput","relative","isUnattended","isEmpty","shouldProceed","message","output","error","exit","RUNTIME_ERROR","log","deployFlags"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,SAAS,EAAEC,aAAa,QAAO,mBAAkB;AACzD,SAAQC,OAAO,QAAO,sBAAqB;AAE3C,SAAQC,SAAS,QAAO,iCAAgC;AACxD,SAAQC,WAAW,QAAO,mCAAkC;AAC5D,SAAQC,YAAY,QAAO,oCAAmC;AAC9D,SAAQC,cAAc,QAAO,4BAA2B;AACxD,SAAQC,uBAAuB,QAAO,qCAAoC;AAE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9B,KAAK,CAAC,UAAU,GAAG;YAAC,GAAGA,KAAK;YAAEe,KAAK;QAAI,IAAIf;QAEtF,IAAIsB,OAAO;YACTjC,YAAY;YACZ,MAAMD,UAAU;gBACd8B;gBACAlB,OAAOuC;gBACPL,QAAQ,IAAI,CAACA,MAAM;gBACnBd;gBACAzB;YACF;QACF,OAAO;YACLN,YAAY;YACZ,MAAMC,aAAa;gBACjB4B;gBACAlB,OAAOuC;gBACPL,QAAQ,IAAI,CAACA,MAAM;gBACnBd;gBACAzB;YACF;QACF;IACF;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { styleText } from 'node:util';
2
2
  import { Flags } from '@oclif/core';
3
- import { SanityCommand } from '@sanity/cli-core';
3
+ import { exitCodes, SanityCommand } from '@sanity/cli-core';
4
4
  import { isWorkbenchApp } from '@sanity/workbench-cli';
5
5
  import { devAction } from '../actions/dev/devAction.js';
6
6
  import { devDebug } from '../actions/dev/devDebug.js';
@@ -65,7 +65,7 @@ export class DevCommand extends SanityCommand {
65
65
  'red',
66
66
  'bgBlack'
67
67
  ], `Failed to start dev server: ${error.message}`), {
68
- exit: 1
68
+ exit: exitCodes.RUNTIME_ERROR
69
69
  });
70
70
  }
71
71
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commands/dev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {type CliConfig, SanityCommand} from '@sanity/cli-core'\nimport {isWorkbenchApp} from '@sanity/workbench-cli'\n\nimport {devAction} from '../actions/dev/devAction.js'\nimport {devDebug} from '../actions/dev/devDebug.js'\nimport {determineIsApp} from '../util/determineIsApp.js'\n\n/**\n * Workbench apps never load in the Sanity dashboard, so `--load-in-dashboard`\n * has no effect for them. The flag is defaulted later in `run`, so an\n * `undefined` value here still means the user never passed it.\n */\nexport function shouldWarnDashboardFlagIgnored(\n cliConfig: CliConfig | undefined,\n loadInDashboard: boolean | undefined,\n): boolean {\n return isWorkbenchApp(cliConfig?.app) && loadInDashboard !== undefined\n}\n\nexport class DevCommand extends SanityCommand<typeof DevCommand> {\n static override description = 'Start a local development server with live reloading'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %> --host=0.0.0.0',\n '<%= config.bin %> <%= command.id %> --port=1942',\n '<%= config.bin %> <%= command.id %> --load-in-dashboard',\n ]\n\n static override flags = {\n 'auto-updates': Flags.boolean({\n allowNo: true,\n description: 'Automatically update Sanity Studio dependencies',\n }),\n host: Flags.string({\n description: 'Local network interface to listen on (default: localhost)',\n }),\n 'load-in-dashboard': Flags.boolean({\n allowNo: true,\n description: 'Load the app/studio in the Sanity dashboard',\n }),\n port: Flags.string({\n description: 'TCP port to start server on (default: 3333)',\n }),\n }\n\n public async run(): Promise<{close?: () => Promise<void>}> {\n const {flags} = await this.parse(DevCommand)\n\n const workDir = (await this.getProjectRoot()).directory\n const cliConfig = await this.getCliConfig()\n const isApp = determineIsApp(cliConfig)\n\n if (shouldWarnDashboardFlagIgnored(cliConfig, flags['load-in-dashboard'])) {\n this.output.warn(\n 'Ignoring --load-in-dashboard: workbench apps do not load in the Sanity dashboard',\n )\n }\n\n // load-in-dashboard is defaulted to true for apps.\n if (isApp && flags['load-in-dashboard'] === undefined) {\n flags['load-in-dashboard'] = true\n } else if (flags['load-in-dashboard'] === undefined) {\n // For non-apps, load-in-dashboard is defaulted to false.\n flags['load-in-dashboard'] = false\n }\n\n try {\n const result = await devAction({\n cliConfig,\n flags,\n isApp,\n output: this.output,\n workDir,\n })\n return result\n } catch (error) {\n devDebug(`Failed to start dev server`, error)\n this.output.error(\n styleText(['red', 'bgBlack'], `Failed to start dev server: ${error.message}`),\n {\n exit: 1,\n },\n )\n }\n }\n}\n"],"names":["styleText","Flags","SanityCommand","isWorkbenchApp","devAction","devDebug","determineIsApp","shouldWarnDashboardFlagIgnored","cliConfig","loadInDashboard","app","undefined","DevCommand","description","examples","flags","boolean","allowNo","host","string","port","run","parse","workDir","getProjectRoot","directory","getCliConfig","isApp","output","warn","result","error","message","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,WAAW;YACnD,yDAAyD;YACzDI,KAAK,CAAC,oBAAoB,GAAG;QAC/B;QAEA,IAAI;YACF,MAAMe,SAAS,MAAM1B,UAAU;gBAC7BI;gBACAO;gBACAY;gBACAC,QAAQ,IAAI,CAACA,MAAM;gBACnBL;YACF;YACA,OAAOO;QACT,EAAE,OAAOC,OAAO;YACd1B,SAAS,CAAC,0BAA0B,CAAC,EAAE0B;YACvC,IAAI,CAACH,MAAM,CAACG,KAAK,CACf/B,UAAU;gBAAC;gBAAO;aAAU,EAAE,CAAC,4BAA4B,EAAE+B,MAAMC,OAAO,EAAE,GAC5E;gBACEC,MAAM;YACR;QAEJ;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/commands/dev.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {type CliConfig, exitCodes, SanityCommand} from '@sanity/cli-core'\nimport {isWorkbenchApp} from '@sanity/workbench-cli'\n\nimport {devAction} from '../actions/dev/devAction.js'\nimport {devDebug} from '../actions/dev/devDebug.js'\nimport {determineIsApp} from '../util/determineIsApp.js'\n\n/**\n * Workbench apps never load in the Sanity dashboard, so `--load-in-dashboard`\n * has no effect for them. The flag is defaulted later in `run`, so an\n * `undefined` value here still means the user never passed it.\n */\nexport function shouldWarnDashboardFlagIgnored(\n cliConfig: CliConfig | undefined,\n loadInDashboard: boolean | undefined,\n): boolean {\n return isWorkbenchApp(cliConfig?.app) && loadInDashboard !== undefined\n}\n\nexport class DevCommand extends SanityCommand<typeof DevCommand> {\n static override description = 'Start a local development server with live reloading'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %> --host=0.0.0.0',\n '<%= config.bin %> <%= command.id %> --port=1942',\n '<%= config.bin %> <%= command.id %> --load-in-dashboard',\n ]\n\n static override flags = {\n 'auto-updates': Flags.boolean({\n allowNo: true,\n description: 'Automatically update Sanity Studio dependencies',\n }),\n host: Flags.string({\n description: 'Local network interface to listen on (default: localhost)',\n }),\n 'load-in-dashboard': Flags.boolean({\n allowNo: true,\n description: 'Load the app/studio in the Sanity dashboard',\n }),\n port: Flags.string({\n description: 'TCP port to start server on (default: 3333)',\n }),\n }\n\n public async run(): Promise<{close?: () => Promise<void>}> {\n const {flags} = await this.parse(DevCommand)\n\n const workDir = (await this.getProjectRoot()).directory\n const cliConfig = await this.getCliConfig()\n const isApp = determineIsApp(cliConfig)\n\n if (shouldWarnDashboardFlagIgnored(cliConfig, flags['load-in-dashboard'])) {\n this.output.warn(\n 'Ignoring --load-in-dashboard: workbench apps do not load in the Sanity dashboard',\n )\n }\n\n // load-in-dashboard is defaulted to true for apps.\n if (isApp && flags['load-in-dashboard'] === undefined) {\n flags['load-in-dashboard'] = true\n } else if (flags['load-in-dashboard'] === undefined) {\n // For non-apps, load-in-dashboard is defaulted to false.\n flags['load-in-dashboard'] = false\n }\n\n try {\n const result = await devAction({\n cliConfig,\n flags,\n isApp,\n output: this.output,\n workDir,\n })\n return result\n } catch (error) {\n devDebug(`Failed to start dev server`, error)\n this.output.error(\n styleText(['red', 'bgBlack'], `Failed to start dev server: ${error.message}`),\n {\n exit: exitCodes.RUNTIME_ERROR,\n },\n )\n }\n }\n}\n"],"names":["styleText","Flags","exitCodes","SanityCommand","isWorkbenchApp","devAction","devDebug","determineIsApp","shouldWarnDashboardFlagIgnored","cliConfig","loadInDashboard","app","undefined","DevCommand","description","examples","flags","boolean","allowNo","host","string","port","run","parse","workDir","getProjectRoot","directory","getCliConfig","isApp","output","warn","result","error","message","exit","RUNTIME_ERROR"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAwBC,SAAS,EAAEC,aAAa,QAAO,mBAAkB;AACzE,SAAQC,cAAc,QAAO,wBAAuB;AAEpD,SAAQC,SAAS,QAAO,8BAA6B;AACrD,SAAQC,QAAQ,QAAO,6BAA4B;AACnD,SAAQC,cAAc,QAAO,4BAA2B;AAExD;;;;CAIC,GACD,OAAO,SAASC,+BACdC,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AAK,CACfhC,UAAU;gBAAC;gBAAO;aAAU,EAAE,CAAC,4BAA4B,EAAEgC,MAAMC,OAAO,EAAE,GAC5E;gBACEC,MAAMhC,UAAUiC,aAAa;YAC/B;QAEJ;IACF;AACF"}
@@ -93,7 +93,7 @@ export class DocsReadCommand extends SanityCommand {
93
93
  this.log(content);
94
94
  } catch (error) {
95
95
  this.error(error instanceof Error ? error.message : 'Failed to read article', {
96
- exit: 1
96
+ exit: exitCodes.RUNTIME_ERROR
97
97
  });
98
98
  }
99
99
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/docs/read.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {exitCodes, SanityCommand} from '@sanity/cli-core'\nimport open from 'open'\n\nimport {readDoc} from '../../services/docs.js'\n\ninterface DocsInput {\n readPath: string\n webPath: string\n}\n\nfunction isSanityHostname(hostname: string): boolean {\n return hostname === 'sanity.io' || hostname.endsWith('.sanity.io')\n}\n\nfunction parseDocsInput(input: string): DocsInput {\n try {\n const url = new URL(input)\n\n if (isSanityHostname(url.hostname)) {\n return {\n readPath: url.pathname,\n webPath: `${url.pathname}${url.search}${url.hash}`,\n }\n }\n } catch {\n // Input is not an absolute URL.\n }\n\n if (input.startsWith('/') && !input.startsWith('//')) {\n const url = new URL(input, 'https://www.sanity.io')\n\n return {\n readPath: url.pathname,\n webPath: `${url.pathname}${url.search}${url.hash}`,\n }\n }\n\n return {\n readPath: input,\n webPath: input,\n }\n}\n\nexport class DocsReadCommand extends SanityCommand<typeof DocsReadCommand> {\n static override args = {\n path: Args.string({\n description: 'Path or URL to article, found in search results and docs content as links',\n required: true,\n }),\n }\n\n static override description = 'Read an article in terminal'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> /docs/studio/installation',\n description: 'Read as markdown in terminal',\n },\n {\n command: '<%= config.bin %> <%= command.id %> https://www.sanity.io/docs/studio/installation',\n description: 'Read using full URL',\n },\n {\n command: '<%= config.bin %> <%= command.id %> /docs/studio/installation --web',\n description: 'Open in web browser',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> https://www.sanity.io/docs/studio/installation -w',\n description: 'Open using full URL in web browser',\n },\n ]\n\n static override flags = {\n web: Flags.boolean({\n aliases: ['w'],\n description: 'Open in a web browser',\n }),\n }\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(DocsReadCommand)\n const {path: input} = args\n const {web} = flags\n\n const {readPath, webPath} = parseDocsInput(input)\n\n if (!readPath.startsWith('/')) {\n this.error(\n 'Invalid path or URL. Expected a Sanity docs path or URL.\\nExamples:\\n /docs/studio/installation\\n https://www.sanity.io/docs/studio/installation',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n if (readPath.includes('..') || !readPath.startsWith('/docs/')) {\n this.error(\n 'Invalid path. Must be a valid Sanity docs path starting with /docs/\\nExample: /docs/studio/installation',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n if (web) {\n const url = `https://www.sanity.io${webPath}`\n this.log(`Opening ${url}`)\n await open(url)\n return\n }\n\n this.log(`Reading article: ${readPath}`)\n\n try {\n const content = await readDoc({path: readPath})\n this.log('\\n---\\n')\n this.log(content)\n } catch (error) {\n this.error(error instanceof Error ? error.message : 'Failed to read article', {\n exit: 1,\n })\n }\n }\n}\n"],"names":["Args","Flags","exitCodes","SanityCommand","open","readDoc","isSanityHostname","hostname","endsWith","parseDocsInput","input","url","URL","readPath","pathname","webPath","search","hash","startsWith","DocsReadCommand","args","path","string","description","required","examples","command","flags","web","boolean","aliases","run","parse","error","exit","USAGE_ERROR","includes","log","content","Error","message"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,SAAS,EAAEC,aAAa,QAAO,mBAAkB;AACzD,OAAOC,UAAU,OAAM;AAEvB,SAAQC,OAAO,QAAO,yBAAwB;AAO9C,SAASC,iBAAiBC,QAAgB;IACxC,OAAOA,aAAa,eAAeA,SAASC,QAAQ,CAAC;AACvD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AEE,OAAO,EAAC,GAAGN,eAAeC;QAE3C,IAAI,CAACG,SAASK,UAAU,CAAC,MAAM;YAC7B,IAAI,CAACe,KAAK,CACR,sJACA;gBACEC,MAAMhC,UAAUiC,WAAW;YAC7B;QAEJ;QAEA,IAAItB,SAASuB,QAAQ,CAAC,SAAS,CAACvB,SAASK,UAAU,CAAC,WAAW;YAC7D,IAAI,CAACe,KAAK,CACR,2GACA;gBACEC,MAAMhC,UAAUiC,WAAW;YAC7B;QAEJ;QAEA,IAAIP,KAAK;YACP,MAAMjB,MAAM,CAAC,qBAAqB,EAAEI,SAAS;YAC7C,IAAI,CAACsB,GAAG,CAAC,CAAC,QAAQ,EAAE1B,KAAK;YACzB,MAAMP,KAAKO;YACX;QACF;QAEA,IAAI,CAAC0B,GAAG,CAAC,CAAC,iBAAiB,EAAExB,UAAU;QAEvC,IAAI;YACF,MAAMyB,UAAU,MAAMjC,QAAQ;gBAACgB,MAAMR;YAAQ;YAC7C,IAAI,CAACwB,GAAG,CAAC;YACT,IAAI,CAACA,GAAG,CAACC;QACX,EAAE,OAAOL,OAAO;YACd,IAAI,CAACA,KAAK,CAACA,iBAAiBM,QAAQN,MAAMO,OAAO,GAAG,0BAA0B;gBAC5EN,MAAM;YACR;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/docs/read.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {exitCodes, SanityCommand} from '@sanity/cli-core'\nimport open from 'open'\n\nimport {readDoc} from '../../services/docs.js'\n\ninterface DocsInput {\n readPath: string\n webPath: string\n}\n\nfunction isSanityHostname(hostname: string): boolean {\n return hostname === 'sanity.io' || hostname.endsWith('.sanity.io')\n}\n\nfunction parseDocsInput(input: string): DocsInput {\n try {\n const url = new URL(input)\n\n if (isSanityHostname(url.hostname)) {\n return {\n readPath: url.pathname,\n webPath: `${url.pathname}${url.search}${url.hash}`,\n }\n }\n } catch {\n // Input is not an absolute URL.\n }\n\n if (input.startsWith('/') && !input.startsWith('//')) {\n const url = new URL(input, 'https://www.sanity.io')\n\n return {\n readPath: url.pathname,\n webPath: `${url.pathname}${url.search}${url.hash}`,\n }\n }\n\n return {\n readPath: input,\n webPath: input,\n }\n}\n\nexport class DocsReadCommand extends SanityCommand<typeof DocsReadCommand> {\n static override args = {\n path: Args.string({\n description: 'Path or URL to article, found in search results and docs content as links',\n required: true,\n }),\n }\n\n static override description = 'Read an article in terminal'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> /docs/studio/installation',\n description: 'Read as markdown in terminal',\n },\n {\n command: '<%= config.bin %> <%= command.id %> https://www.sanity.io/docs/studio/installation',\n description: 'Read using full URL',\n },\n {\n command: '<%= config.bin %> <%= command.id %> /docs/studio/installation --web',\n description: 'Open in web browser',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> https://www.sanity.io/docs/studio/installation -w',\n description: 'Open using full URL in web browser',\n },\n ]\n\n static override flags = {\n web: Flags.boolean({\n aliases: ['w'],\n description: 'Open in a web browser',\n }),\n }\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(DocsReadCommand)\n const {path: input} = args\n const {web} = flags\n\n const {readPath, webPath} = parseDocsInput(input)\n\n if (!readPath.startsWith('/')) {\n this.error(\n 'Invalid path or URL. Expected a Sanity docs path or URL.\\nExamples:\\n /docs/studio/installation\\n https://www.sanity.io/docs/studio/installation',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n if (readPath.includes('..') || !readPath.startsWith('/docs/')) {\n this.error(\n 'Invalid path. Must be a valid Sanity docs path starting with /docs/\\nExample: /docs/studio/installation',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n if (web) {\n const url = `https://www.sanity.io${webPath}`\n this.log(`Opening ${url}`)\n await open(url)\n return\n }\n\n this.log(`Reading article: ${readPath}`)\n\n try {\n const content = await readDoc({path: readPath})\n this.log('\\n---\\n')\n this.log(content)\n } catch (error) {\n this.error(error instanceof Error ? error.message : 'Failed to read article', {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n}\n"],"names":["Args","Flags","exitCodes","SanityCommand","open","readDoc","isSanityHostname","hostname","endsWith","parseDocsInput","input","url","URL","readPath","pathname","webPath","search","hash","startsWith","DocsReadCommand","args","path","string","description","required","examples","command","flags","web","boolean","aliases","run","parse","error","exit","USAGE_ERROR","includes","log","content","Error","message","RUNTIME_ERROR"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,SAAS,EAAEC,aAAa,QAAO,mBAAkB;AACzD,OAAOC,UAAU,OAAM;AAEvB,SAAQC,OAAO,QAAO,yBAAwB;AAO9C,SAASC,iBAAiBC,QAAgB;IACxC,OAAOA,aAAa,eAAeA,SAASC,QAAQ,CAAC;AACvD;AAEA,SAASC,eAAeC,KAAa;IACnC,IAAI;QACF,MAAMC,MAAM,IAAIC,IAAIF;QAEpB,IAAIJ,iBAAiBK,IAAIJ,QAAQ,GAAG;YAClC,OAAO;gBACLM,UAAUF,IAAIG,QAAQ;gBACtBC,SAAS,GAAGJ,IAAIG,QAAQ,GAAGH,IAAIK,MAAM,GAAGL,IAAIM,IAAI,EAAE;YACpD;QACF;IACF,EAAE,OAAM;IACN,gCAAgC;IAClC;IAEA,IAAIP,MAAMQ,UAAU,CAAC,QAAQ,CAACR,MAAMQ,UAAU,CAAC,OAAO;QACpD,MAAMP,MAAM,IAAIC,IAAIF,OAAO;QAE3B,OAAO;YACLG,UAAUF,IAAIG,QAAQ;YACtBC,SAAS,GAAGJ,IAAIG,QAAQ,GAAGH,IAAIK,MAAM,GAAGL,IAAIM,IAAI,EAAE;QACpD;IACF;IAEA,OAAO;QACLJ,UAAUH;QACVK,SAASL;IACX;AACF;AAEA,OAAO,MAAMS,wBAAwBhB;IACnC,OAAgBiB,OAAO;QACrBC,MAAMrB,KAAKsB,MAAM,CAAC;YAChBC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,8BAA6B;IAE3D,O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;gBAC5EN,MAAMhC,UAAUuC,aAAa;YAC/B;QACF;IACF;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { styleText } from 'node:util';
2
2
  import { Args, Flags } from '@oclif/core';
3
- import { isInteractive, SanityCommand, subdebug } from '@sanity/cli-core';
3
+ import { exitCodes, isInteractive, SanityCommand, subdebug } from '@sanity/cli-core';
4
4
  import { select } from '@sanity/cli-core/ux';
5
5
  import { readDoc, searchDocs } from '../../services/docs.js';
6
6
  const searchDebug = subdebug('docs:search');
@@ -52,7 +52,7 @@ export class DocsSearchCommand extends SanityCommand {
52
52
  searchDebug('error fetching results', error);
53
53
  const message = error instanceof Error ? error.message : 'The documentation search API is currently unavailable. Please try again later.';
54
54
  this.error(message, {
55
- exit: 1
55
+ exit: exitCodes.RUNTIME_ERROR
56
56
  });
57
57
  }
58
58
  this.log(`\nFound ${results.length} result(s):\n`);
@@ -100,7 +100,7 @@ export class DocsSearchCommand extends SanityCommand {
100
100
  this.log(content);
101
101
  } catch (error) {
102
102
  this.error(`Failed to read article: ${error instanceof Error ? error.message : 'Unknown error'}`, {
103
- exit: 1
103
+ exit: exitCodes.RUNTIME_ERROR
104
104
  });
105
105
  }
106
106
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/docs/search.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {isInteractive, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {select} from '@sanity/cli-core/ux'\n\nimport {readDoc, searchDocs, type SearchResult} from '../../services/docs.js'\n\nconst searchDebug = subdebug('docs:search')\n\nexport class DocsSearchCommand extends SanityCommand<typeof DocsSearchCommand> {\n static override args = {\n query: Args.string({\n description: 'Search query for documentation',\n required: true,\n }),\n }\n\n static override description = 'Search Sanity docs'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> schema',\n description: 'Search for documentation about schemas',\n },\n {\n command: '<%= config.bin %> <%= command.id %> \"groq functions\"',\n description: 'Search with phrase',\n },\n {\n command: '<%= config.bin %> <%= command.id %> \"deployment\" --limit=5',\n description: 'Limit search results',\n },\n ]\n\n static override flags = {\n limit: Flags.integer({\n default: 10,\n description: 'Maximum number of results to return',\n min: 1,\n }),\n }\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(DocsSearchCommand)\n const {query} = args\n const {limit} = flags\n\n this.log(`Searching documentation for: \"${query}\"`)\n\n let results: SearchResult[]\n try {\n results = await searchDocs({\n limit,\n query,\n })\n\n if (results.length === 0) {\n this.log('No results found. Try a different search term.')\n return\n }\n } catch (error) {\n searchDebug('error fetching results', error)\n const message =\n error instanceof Error\n ? error.message\n : 'The documentation search API is currently unavailable. Please try again later.'\n this.error(message, {\n exit: 1,\n })\n }\n\n this.log(`\\nFound ${results.length} result(s):\\n`)\n\n for (const [index, result] of results.entries()) {\n this.log(`${index + 1}. ${result.title}`)\n this.log(` ${styleText('cyan', `URL: https://www.sanity.io${result.path}`)}`)\n if (result.description) {\n this.log(` ${result.description}`)\n }\n this.log('')\n }\n\n // Show usage hint in non-interactive mode\n if (!isInteractive()) {\n this.log('Use `sanity docs read <url>` to read an article in terminal.')\n this.log('Use `sanity docs read <path>` to follow links found within articles.')\n this.log('')\n return\n }\n\n // Interactive selection (only in interactive environments)\n if (results.length > 0) {\n const choices = results.map((result, index) => ({\n description: result.description,\n name: `${index + 1}. ${result.title} (${result.path})`,\n value: index,\n }))\n\n const selectedIndex = await select({\n choices: [...choices, {description: 'Exit without reading', name: 'Exit', value: -1}],\n message: 'Select an article to read in terminal:',\n })\n\n if (typeof selectedIndex === 'number' && selectedIndex >= 0) {\n const selected = results[selectedIndex]\n\n try {\n // Read and display the article\n const content = await readDoc({path: selected.path})\n this.log('\\n---\\n')\n this.log(content)\n } catch (error) {\n this.error(\n `Failed to read article: ${error instanceof Error ? error.message : 'Unknown error'}`,\n {\n exit: 1,\n },\n )\n }\n }\n }\n }\n}\n"],"names":["styleText","Args","Flags","isInteractive","SanityCommand","subdebug","select","readDoc","searchDocs","searchDebug","DocsSearchCommand","args","query","string","description","required","examples","command","flags","limit","integer","default","min","run","parse","log","results","length","error","message","Error","exit","index","result","entries","title","path","choices","map","name","value","selectedIndex","selected","content"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,aAAa,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACvE,SAAQC,MAAM,QAAO,sBAAqB;AAE1C,SAAQC,OAAO,EAAEC,UAAU,QAA0B,yBAAwB;AAE7E,MAAMC,cAAcJ,SAAS;AAE7B,OAAO,MAAMK,0BAA0BN;IACrC,OAAgBO,OAAO;QACrBC,OAAOX,KAAKY,MAAM,CAAC;YACjBC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,qBAAoB;IAElD,OAAgBE,WAAW;QACzB;YACEC,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SAAS;YACTH,aAAa;QACf;KACD,CAAA;IAED,OAAgBI,QAAQ;QACtBC,OAAOjB,MAAMkB,OAAO,CAAC;YACnBC,SAAS;YACTP,aAAa;YACbQ,KAAK;QACP;IACF,EAAC;IAED,MAAaC,MAAqB;QAChC,MAAM,EAACZ,IAAI,EAAEO,KAAK,EAAC,GAAG,MAAM,IAAI,CAACM,KAAK,CAACd;QACvC,MAAM,EAACE,KAAK,EAAC,GAAGD;QAChB,MAAM,EAACQ,KAAK,EAAC,GAAGD;QAEhB,IAAI,CAACO,GAAG,CAAC,CAAC,8BAA8B,EAAEb,MAAM,CAAC,CAAC;QAElD,IAAIc;QACJ,IAAI;YACFA,UAAU,MAAMlB,WAAW;gBACzBW;gBACAP;YACF;YAEA,IAAIc,QAAQC,MAAM,KAAK,GAAG;gBACxB,IAAI,CAACF,GAAG,CAAC;gBACT;YACF;QACF,EAAE,OAAOG,OAAO;YACdnB,YAAY,0BAA0BmB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B,GAAG;gBAC3D,MAAMC,WAAWhB,OAAO,CAACe,cAAc;gBAEvC,IAAI;oBACF,+BAA+B;oBAC/B,MAAME,UAAU,MAAMpC,QAAQ;wBAAC6B,MAAMM,SAASN,IAAI;oBAAA;oBAClD,IAAI,CAACX,GAAG,CAAC;oBACT,IAAI,CAACA,GAAG,CAACkB;gBACX,EAAE,OAAOf,OAAO;oBACd,IAAI,CAACA,KAAK,CACR,CAAC,wBAAwB,EAAEA,iBAAiBE,QAAQF,MAAMC,OAAO,GAAG,iBAAiB,EACrF;wBACEE,MAAM;oBACR;gBAEJ;YACF;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/docs/search.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, isInteractive, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {select} from '@sanity/cli-core/ux'\n\nimport {readDoc, searchDocs, type SearchResult} from '../../services/docs.js'\n\nconst searchDebug = subdebug('docs:search')\n\nexport class DocsSearchCommand extends SanityCommand<typeof DocsSearchCommand> {\n static override args = {\n query: Args.string({\n description: 'Search query for documentation',\n required: true,\n }),\n }\n\n static override description = 'Search Sanity docs'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> schema',\n description: 'Search for documentation about schemas',\n },\n {\n command: '<%= config.bin %> <%= command.id %> \"groq functions\"',\n description: 'Search with phrase',\n },\n {\n command: '<%= config.bin %> <%= command.id %> \"deployment\" --limit=5',\n description: 'Limit search results',\n },\n ]\n\n static override flags = {\n limit: Flags.integer({\n default: 10,\n description: 'Maximum number of results to return',\n min: 1,\n }),\n }\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(DocsSearchCommand)\n const {query} = args\n const {limit} = flags\n\n this.log(`Searching documentation for: \"${query}\"`)\n\n let results: SearchResult[]\n try {\n results = await searchDocs({\n limit,\n query,\n })\n\n if (results.length === 0) {\n this.log('No results found. Try a different search term.')\n return\n }\n } catch (error) {\n searchDebug('error fetching results', error)\n const message =\n error instanceof Error\n ? error.message\n : 'The documentation search API is currently unavailable. Please try again later.'\n this.error(message, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n this.log(`\\nFound ${results.length} result(s):\\n`)\n\n for (const [index, result] of results.entries()) {\n this.log(`${index + 1}. ${result.title}`)\n this.log(` ${styleText('cyan', `URL: https://www.sanity.io${result.path}`)}`)\n if (result.description) {\n this.log(` ${result.description}`)\n }\n this.log('')\n }\n\n // Show usage hint in non-interactive mode\n if (!isInteractive()) {\n this.log('Use `sanity docs read <url>` to read an article in terminal.')\n this.log('Use `sanity docs read <path>` to follow links found within articles.')\n this.log('')\n return\n }\n\n // Interactive selection (only in interactive environments)\n if (results.length > 0) {\n const choices = results.map((result, index) => ({\n description: result.description,\n name: `${index + 1}. ${result.title} (${result.path})`,\n value: index,\n }))\n\n const selectedIndex = await select({\n choices: [...choices, {description: 'Exit without reading', name: 'Exit', value: -1}],\n message: 'Select an article to read in terminal:',\n })\n\n if (typeof selectedIndex === 'number' && selectedIndex >= 0) {\n const selected = results[selectedIndex]\n\n try {\n // Read and display the article\n const content = await readDoc({path: selected.path})\n this.log('\\n---\\n')\n this.log(content)\n } catch (error) {\n this.error(\n `Failed to read article: ${error instanceof Error ? error.message : 'Unknown error'}`,\n {\n exit: exitCodes.RUNTIME_ERROR,\n },\n )\n }\n }\n }\n }\n}\n"],"names":["styleText","Args","Flags","exitCodes","isInteractive","SanityCommand","subdebug","select","readDoc","searchDocs","searchDebug","DocsSearchCommand","args","query","string","description","required","examples","command","flags","limit","integer","default","min","run","parse","log","results","length","error","message","Error","exit","RUNTIME_ERROR","index","result","entries","title","path","choices","map","name","value","selectedIndex","selected","content"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,SAAS,EAAEC,aAAa,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAClF,SAAQC,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,CACR,CAAC,wBAAwB,EAAEA,iBAAiBE,QAAQF,MAAMC,OAAO,GAAG,iBAAiB,EACrF;wBACEE,MAAM7B,UAAU8B,aAAa;oBAC/B;gBAEJ;YACF;QACF;IACF;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { styleText } from 'node:util';
2
2
  import { Args, Flags } from '@oclif/core';
3
- import { SanityCommand } from '@sanity/cli-core';
3
+ import { exitCodes, SanityCommand } from '@sanity/cli-core';
4
4
  import { logSymbols } from '@sanity/cli-core/ux';
5
5
  import { doctorChecks, KNOWN_CHECKS } from '../actions/doctor/checks/index.js';
6
6
  import { runDoctorChecks } from '../actions/doctor/runDoctorChecks.js';
@@ -54,7 +54,7 @@ export class DoctorCommand extends SanityCommand {
54
54
  checks = getChecks(argv);
55
55
  } catch (err) {
56
56
  return this.output.error(err instanceof Error ? err.message : String(err), {
57
- exit: 2
57
+ exit: exitCodes.USAGE_ERROR
58
58
  });
59
59
  }
60
60
  const cwd = process.cwd();
@@ -74,7 +74,7 @@ export class DoctorCommand extends SanityCommand {
74
74
  }
75
75
  // Exit with error code if any checks failed
76
76
  if (results.summary.errors > 0) {
77
- return this.exit(1);
77
+ return this.exit(exitCodes.RUNTIME_ERROR);
78
78
  }
79
79
  }
80
80
  printCheck(check) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commands/doctor.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {logSymbols} from '@sanity/cli-core/ux'\n\nimport {type DoctorCheckName, doctorChecks, KNOWN_CHECKS} from '../actions/doctor/checks/index.js'\nimport {runDoctorChecks} from '../actions/doctor/runDoctorChecks.js'\nimport {\n type CheckMessage,\n type CheckResultStatus,\n type CheckResultWithMeta,\n type DoctorCheck,\n type DoctorResults,\n type MessageType,\n} from '../actions/doctor/types.js'\n\nconst STATUS_SYMBOLS: Record<CheckResultStatus, string> = {\n error: logSymbols.error,\n passed: logSymbols.success,\n warning: logSymbols.warning,\n}\n\nconst MESSAGE_SYMBOLS: Record<MessageType, string> = {\n error: logSymbols.error,\n info: logSymbols.info,\n success: logSymbols.success,\n warning: logSymbols.warning,\n}\n\nexport class DoctorCommand extends SanityCommand<typeof DoctorCommand> {\n // strict=false allows variadic args — validation is handled by getChecks().\n // options is omitted here because oclif's help formatter uses it for display,\n // but actual validation is done explicitly in getChecks() for clear error messages.\n static override args = {\n checks: Args.string({\n description: `Checks to enable (defaults to all). Valid: ${KNOWN_CHECKS.join(', ')}`,\n multiple: true,\n required: false,\n }),\n }\n\n static override description = 'Run diagnostics on your Sanity project'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n {command: '<%= config.bin %> <%= command.id %> --json', description: 'Output results as JSON'},\n {\n command: '<%= config.bin %> <%= command.id %> cli',\n description: 'Only run CLI-related diagnostics',\n },\n ]\n\n static override flags = {\n json: Flags.boolean({\n char: 'j',\n default: false,\n description: 'Output results as JSON',\n }),\n }\n\n // Needed for variable argument count\n static override strict = false\n\n public async run(): Promise<void> {\n const {argv, flags} = await this.parse(DoctorCommand)\n\n let checks: Array<DoctorCheck>\n try {\n checks = getChecks(argv)\n } catch (err) {\n return this.output.error(err instanceof Error ? err.message : String(err), {exit: 2})\n }\n const cwd = process.cwd()\n\n if (!flags.json) {\n this.output.log('Running diagnostics...\\n')\n }\n\n const results = await runDoctorChecks({cwd}, checks)\n\n if (flags.json) {\n this.output.log(JSON.stringify(results, null, 2))\n } else {\n for (const check of results.checks) {\n this.printCheck(check)\n }\n\n this.printSummary(results.summary)\n }\n\n // Exit with error code if any checks failed\n if (results.summary.errors > 0) {\n return this.exit(1)\n }\n }\n\n private printCheck(check: CheckResultWithMeta): void {\n const symbol = STATUS_SYMBOLS[check.status]\n const title =\n check.status === 'passed'\n ? check.title\n : styleText(check.status === 'error' ? 'red' : 'yellow', check.title)\n\n this.output.log(`${symbol} ${title}`)\n\n for (const message of check.messages) {\n this.printMessage(message)\n }\n\n this.output.log('') // Empty line between checks\n }\n\n private printMessage(message: CheckMessage): void {\n const symbol = MESSAGE_SYMBOLS[message.type]\n const text =\n message.type === 'error'\n ? styleText('red', message.text)\n : message.type === 'warning'\n ? styleText('yellow', message.text)\n : message.text\n\n this.output.log(` ${symbol} ${text}`)\n\n if (message.suggestions?.length) {\n for (const suggestion of message.suggestions) {\n this.output.log(` ${styleText('dim', '→')} ${suggestion}`)\n }\n }\n }\n\n private printSummary(summary: DoctorResults['summary']): void {\n const parts: string[] = []\n\n if (summary.passed > 0) {\n parts.push(styleText('green', `${summary.passed} passed`))\n }\n if (summary.warnings > 0) {\n parts.push(\n styleText('yellow', `${summary.warnings} warning${summary.warnings === 1 ? '' : 's'}`),\n )\n }\n if (summary.errors > 0) {\n parts.push(styleText('red', `${summary.errors} error${summary.errors === 1 ? '' : 's'}`))\n }\n\n this.output.log(`Summary: ${parts.join(', ')}`)\n }\n}\n\nfunction getChecks(argv: unknown[]): Array<DoctorCheck> {\n // strict=false means oclif does NOT validate Args.string({ options }) — we must\n // validate explicitly. Filter to string args that aren't flags.\n const stringArgs = argv.filter(\n (item): item is string => typeof item === 'string' && !item.startsWith('-'),\n )\n\n const unknownChecks = stringArgs.filter(\n (item) => !(KNOWN_CHECKS as readonly string[]).includes(item),\n )\n if (unknownChecks.length > 0) {\n throw new Error(\n `Unknown check${unknownChecks.length === 1 ? '' : 's'}: ${unknownChecks.join(', ')}. Valid checks: ${KNOWN_CHECKS.join(', ')}`,\n )\n }\n\n const checkNames = stringArgs as DoctorCheckName[]\n return checkNames.length > 0\n ? checkNames.map((check) => doctorChecks[check])\n : Object.values(doctorChecks)\n}\n"],"names":["styleText","Args","Flags","SanityCommand","logSymbols","doctorChecks","KNOWN_CHECKS","runDoctorChecks","STATUS_SYMBOLS","error","passed","success","warning","MESSAGE_SYMBOLS","info","DoctorCommand","args","checks","string","description","join","multiple","required","examples","command","flags","json","boolean","char","default","strict","run","argv","parse","getChecks","err","output","Error","message","String","exit","cwd","process","log","results","JSON","stringify","check","printCheck","printSummary","summary","errors","symbol","status","title","messages","printMessage","type","text","suggestions","length","suggestion","parts","push","warnings","stringArgs","filter","item","startsWith","unknownChecks","includes","checkNames","map","Object","values"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,UAAU,QAAO,sBAAqB;AAE9C,SAA8BC,YAAY,EAAEC,YAAY,QAAO,oCAAmC;AAClG,SAAQC,eAAe,QAAO,uCAAsC;AAUpE,MAAMC,iBAAoD;IACxDC,OAAOL,WAAWK,KAAK;IACvBC,QAAQN,WAAWO,OAAO;IAC1BC,SAASR,WAAWQ,OAAO;AAC7B;AAEA,MAAMC,kBAA+C;IACnDJ,OAAOL,WAAWK,KAAK;IACvBK,MAAMV,WAAWU,IAAI;IACrBH,SAASP,WAAWO,OAAO;IAC3BC,SAASR,WAAWQ,OAAO;AAC7B;AAEA,OAAO,MAAMG,sBAAsBZ;IACjC,4EAA4E;IAC5E,8EAA8E;IAC9E,oFAAoF;IACpF,OAAgBa,OAAO;QACrBC,QAAQhB,KAAKiB,MAAM,CAAC;YAClBC,aAAa,CAAC,2CAA2C,EAAEb,aAAac,IAAI,CAAC,OAAO;YACpFC,UAAU;YACVC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBH,cAAc,yCAAwC;IAEtE,OAAgBI,WAAW;QACzB;QACA;YAACC,SAAS;YAA8CL,aAAa;QAAwB;QAC7F;YACEK,SAAS;YACTL,aAAa;QACf;KACD,CAAA;IAED,OAAgBM,QAAQ;QACtBC,MAAMxB,MAAMyB,OAAO,CAAC;YAClBC,MAAM;YACNC,SAAS;YACTV,aAAa;QACf;IACF,EAAC;IAED,qCAAqC;IACrC,OAAgBW,SAAS,MAAK;IAE9B,MAAaC,MAAqB;QAChC,MAAM,EAACC,IAAI,EAAEP,KAAK,EAAC,GAAG,MAAM,IAAI,CAACQ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,CAACC,OAAyB,OAAOA,SAAS,YAAY,CAACA,KAAKC,UAAU,CAAC;IAGzE,MAAMC,gBAAgBJ,WAAWC,MAAM,CACrC,CAACC,OAAS,CAAC,AAAC7D,aAAmCgE,QAAQ,CAACH;IAE1D,IAAIE,cAAcT,MAAM,GAAG,GAAG;QAC5B,MAAM,IAAIvB,MACR,CAAC,aAAa,EAAEgC,cAAcT,MAAM,KAAK,IAAI,KAAK,IAAI,EAAE,EAAES,cAAcjD,IAAI,CAAC,MAAM,gBAAgB,EAAEd,aAAac,IAAI,CAAC,OAAO;IAElI;IAEA,MAAMmD,aAAaN;IACnB,OAAOM,WAAWX,MAAM,GAAG,IACvBW,WAAWC,GAAG,CAAC,CAACzB,QAAU1C,YAAY,CAAC0C,MAAM,IAC7C0B,OAAOC,MAAM,CAACrE;AACpB"}
1
+ {"version":3,"sources":["../../src/commands/doctor.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, SanityCommand} from '@sanity/cli-core'\nimport {logSymbols} from '@sanity/cli-core/ux'\n\nimport {type DoctorCheckName, doctorChecks, KNOWN_CHECKS} from '../actions/doctor/checks/index.js'\nimport {runDoctorChecks} from '../actions/doctor/runDoctorChecks.js'\nimport {\n type CheckMessage,\n type CheckResultStatus,\n type CheckResultWithMeta,\n type DoctorCheck,\n type DoctorResults,\n type MessageType,\n} from '../actions/doctor/types.js'\n\nconst STATUS_SYMBOLS: Record<CheckResultStatus, string> = {\n error: logSymbols.error,\n passed: logSymbols.success,\n warning: logSymbols.warning,\n}\n\nconst MESSAGE_SYMBOLS: Record<MessageType, string> = {\n error: logSymbols.error,\n info: logSymbols.info,\n success: logSymbols.success,\n warning: logSymbols.warning,\n}\n\nexport class DoctorCommand extends SanityCommand<typeof DoctorCommand> {\n // strict=false allows variadic args — validation is handled by getChecks().\n // options is omitted here because oclif's help formatter uses it for display,\n // but actual validation is done explicitly in getChecks() for clear error messages.\n static override args = {\n checks: Args.string({\n description: `Checks to enable (defaults to all). Valid: ${KNOWN_CHECKS.join(', ')}`,\n multiple: true,\n required: false,\n }),\n }\n\n static override description = 'Run diagnostics on your Sanity project'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n {command: '<%= config.bin %> <%= command.id %> --json', description: 'Output results as JSON'},\n {\n command: '<%= config.bin %> <%= command.id %> cli',\n description: 'Only run CLI-related diagnostics',\n },\n ]\n\n static override flags = {\n json: Flags.boolean({\n char: 'j',\n default: false,\n description: 'Output results as JSON',\n }),\n }\n\n // Needed for variable argument count\n static override strict = false\n\n public async run(): Promise<void> {\n const {argv, flags} = await this.parse(DoctorCommand)\n\n let checks: Array<DoctorCheck>\n try {\n checks = getChecks(argv)\n } catch (err) {\n return this.output.error(err instanceof Error ? err.message : String(err), {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n const cwd = process.cwd()\n\n if (!flags.json) {\n this.output.log('Running diagnostics...\\n')\n }\n\n const results = await runDoctorChecks({cwd}, checks)\n\n if (flags.json) {\n this.output.log(JSON.stringify(results, null, 2))\n } else {\n for (const check of results.checks) {\n this.printCheck(check)\n }\n\n this.printSummary(results.summary)\n }\n\n // Exit with error code if any checks failed\n if (results.summary.errors > 0) {\n return this.exit(exitCodes.RUNTIME_ERROR)\n }\n }\n\n private printCheck(check: CheckResultWithMeta): void {\n const symbol = STATUS_SYMBOLS[check.status]\n const title =\n check.status === 'passed'\n ? check.title\n : styleText(check.status === 'error' ? 'red' : 'yellow', check.title)\n\n this.output.log(`${symbol} ${title}`)\n\n for (const message of check.messages) {\n this.printMessage(message)\n }\n\n this.output.log('') // Empty line between checks\n }\n\n private printMessage(message: CheckMessage): void {\n const symbol = MESSAGE_SYMBOLS[message.type]\n const text =\n message.type === 'error'\n ? styleText('red', message.text)\n : message.type === 'warning'\n ? styleText('yellow', message.text)\n : message.text\n\n this.output.log(` ${symbol} ${text}`)\n\n if (message.suggestions?.length) {\n for (const suggestion of message.suggestions) {\n this.output.log(` ${styleText('dim', '→')} ${suggestion}`)\n }\n }\n }\n\n private printSummary(summary: DoctorResults['summary']): void {\n const parts: string[] = []\n\n if (summary.passed > 0) {\n parts.push(styleText('green', `${summary.passed} passed`))\n }\n if (summary.warnings > 0) {\n parts.push(\n styleText('yellow', `${summary.warnings} warning${summary.warnings === 1 ? '' : 's'}`),\n )\n }\n if (summary.errors > 0) {\n parts.push(styleText('red', `${summary.errors} error${summary.errors === 1 ? '' : 's'}`))\n }\n\n this.output.log(`Summary: ${parts.join(', ')}`)\n }\n}\n\nfunction getChecks(argv: unknown[]): Array<DoctorCheck> {\n // strict=false means oclif does NOT validate Args.string({ options }) — we must\n // validate explicitly. Filter to string args that aren't flags.\n const stringArgs = argv.filter(\n (item): item is string => typeof item === 'string' && !item.startsWith('-'),\n )\n\n const unknownChecks = stringArgs.filter(\n (item) => !(KNOWN_CHECKS as readonly string[]).includes(item),\n )\n if (unknownChecks.length > 0) {\n throw new Error(\n `Unknown check${unknownChecks.length === 1 ? '' : 's'}: ${unknownChecks.join(', ')}. Valid checks: ${KNOWN_CHECKS.join(', ')}`,\n )\n }\n\n const checkNames = stringArgs as DoctorCheckName[]\n return checkNames.length > 0\n ? checkNames.map((check) => doctorChecks[check])\n : Object.values(doctorChecks)\n}\n"],"names":["styleText","Args","Flags","exitCodes","SanityCommand","logSymbols","doctorChecks","KNOWN_CHECKS","runDoctorChecks","STATUS_SYMBOLS","error","passed","success","warning","MESSAGE_SYMBOLS","info","DoctorCommand","args","checks","string","description","join","multiple","required","examples","command","flags","json","boolean","char","default","strict","run","argv","parse","getChecks","err","output","Error","message","String","exit","USAGE_ERROR","cwd","process","log","results","JSON","stringify","check","printCheck","printSummary","summary","errors","RUNTIME_ERROR","symbol","status","title","messages","printMessage","type","text","suggestions","length","suggestion","parts","push","warnings","stringArgs","filter","item","startsWith","unknownChecks","includes","checkNames","map","Object","values"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,IAAI,EAAEC,KAAK,QAAO,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IAE1D,IAAIE,cAAcT,MAAM,GAAG,GAAG;QAC5B,MAAM,IAAIzB,MACR,CAAC,aAAa,EAAEkC,cAAcT,MAAM,KAAK,IAAI,KAAK,IAAI,EAAE,EAAES,cAAcnD,IAAI,CAAC,MAAM,gBAAgB,EAAEd,aAAac,IAAI,CAAC,OAAO;IAElI;IAEA,MAAMqD,aAAaN;IACnB,OAAOM,WAAWX,MAAM,GAAG,IACvBW,WAAWC,GAAG,CAAC,CAAC1B,QAAU3C,YAAY,CAAC2C,MAAM,IAC7C2B,OAAOC,MAAM,CAACvE;AACpB"}
@@ -124,7 +124,7 @@ export class CreateDocumentCommand extends SanityCommand {
124
124
  const err = error;
125
125
  createDocumentDebug(`Error creating documents from file ${file}`, err);
126
126
  this.error(`Failed to create documents: ${err.message}`, {
127
- exit: 1
127
+ exit: exitCodes.RUNTIME_ERROR
128
128
  });
129
129
  }
130
130
  }
@@ -193,7 +193,7 @@ export class CreateDocumentCommand extends SanityCommand {
193
193
  const err = error;
194
194
  createDocumentDebug('Error in editor workflow', err);
195
195
  this.error(`Failed to create documents: ${err.message}`, {
196
- exit: 1
196
+ exit: exitCodes.RUNTIME_ERROR
197
197
  });
198
198
  }
199
199
  }
@@ -258,7 +258,7 @@ export class CreateDocumentCommand extends SanityCommand {
258
258
  errorMessage += '\nPerhaps you want to use `--replace` or `--missing`?';
259
259
  }
260
260
  this.error(errorMessage, {
261
- exit: 1
261
+ exit: exitCodes.RUNTIME_ERROR
262
262
  });
263
263
  }
264
264
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/create.ts"],"sourcesContent":["import {randomUUID} from 'node:crypto'\nimport fs from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {type MultipleMutationResult, type Mutation} from '@sanity/client'\nimport {watch as chokidarWatch} from 'chokidar'\nimport {execa, execaSync} from 'execa'\nimport json5 from 'json5'\nimport isEqual from 'lodash-es/isEqual.js'\nimport isPlainObject from 'lodash-es/isPlainObject.js'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {getEditor, registerUnlinkOnSigInt} from '../../actions/documents/editor.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {isIdentifiedSanityDocument, isSanityDocumentish} from '../../util/isSanityDocumentish.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nexport type MutationOperationName = 'create' | 'createIfNotExists' | 'createOrReplace'\n\nconst createDocumentDebug = subdebug('documents:create')\n\nexport class CreateDocumentCommand extends SanityCommand<typeof CreateDocumentCommand> {\n static override args = {\n file: Args.string({\n description: 'JSON file to create document(s) from',\n required: false,\n }),\n }\n\n static override description = 'Create one or more documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json',\n description: 'Create the document specified in \"myDocument.json\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Open configured $EDITOR and create the specified document(s)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --replace',\n description:\n 'Fetch document with the ID \"myDocId\" and open configured $EDITOR with the current document content (if any). Replace document with the edited version when the editor closes',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --watch --replace --json5',\n description:\n 'Open configured $EDITOR and replace the document with the given content on each save. Use JSON5 file extension and parser for simplified syntax.',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json --project-id abc123',\n description: 'Create documents in a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to create document(s) in',\n semantics: 'override',\n }),\n ...getDatasetFlag({\n description: 'Dataset to create document(s) in',\n semantics: 'override',\n }),\n id: Flags.string({\n description:\n 'Specify a document ID to use. Will fetch remote document ID and populate editor.',\n }),\n json5: Flags.boolean({\n description: 'Use JSON5 file type to allow a \"simplified\" version of JSON',\n }),\n missing: Flags.boolean({\n description: \"On duplicate document IDs, don't modify the target document(s)\",\n }),\n replace: Flags.boolean({\n description:\n 'On duplicate document IDs, replace existing document with specified document(s)',\n }),\n watch: Flags.boolean({\n description: 'Write the documents whenever the target file or buffer changes',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:create']\n\n private client!: Awaited<ReturnType<typeof getProjectCliClient>>\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(CreateDocumentCommand)\n const {file} = args\n const {dataset, id, json5: useJson5, missing, replace, watch} = flags\n\n if (!file && this.isUnattended()) {\n this.error(\n 'Document input is required in unattended mode. Pass it as the `<file>` argument.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n if (replace && missing) {\n this.error(\n 'Cannot use `--replace` and `--missing` together. Remove one flag and try again.',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n if (id && file) {\n this.error(\n 'Cannot use `--id` with the `<file>` argument. Remove `--id` or omit `<file>` and try again.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n this.client = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n let operation: MutationOperationName = 'create'\n if (replace || missing) {\n operation = replace ? 'createOrReplace' : 'createIfNotExists'\n }\n\n if (file) {\n try {\n const contentPath = path.resolve(process.cwd(), file)\n const content = json5.parse(await fs.readFile(contentPath, 'utf8'))\n const result = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(result, operation))\n return\n } catch (error) {\n const err = error as Error\n createDocumentDebug(`Error creating documents from file ${file}`, err)\n this.error(`Failed to create documents: ${err.message}`, {exit: 1})\n }\n }\n\n try {\n // Create a temporary file and use that as source, opening an editor on it\n const docId = id || randomUUID()\n const ext = useJson5 ? 'json5' : 'json'\n // Add UUID prefix to prevent predictable file names and potential conflicts\n const tmpFile = path.join(os.tmpdir(), 'sanity-cli', `${randomUUID()}-${docId}.${ext}`)\n const stringify = useJson5 ? json5.stringify : JSON.stringify\n const defaultValue = (id && (await this.client.getDocument(id))) || {\n _id: docId,\n _type: 'specify-me',\n }\n\n // Create temp directory with restricted permissions (owner only)\n const tempDir = path.join(os.tmpdir(), 'sanity-cli')\n await fs.mkdir(tempDir, {\n mode: 0o700, // rwx------ (owner read/write/execute only)\n recursive: true,\n })\n\n // Write file with restricted permissions (owner read/write only)\n await fs.writeFile(tmpFile, stringify(defaultValue, null, 2), {\n encoding: 'utf8',\n mode: 0o600, // rw------- (owner read/write only)\n })\n\n const editor = getEditor()\n const readAndPerformCreatesFromFile = this.readAndPerformCreatesFromFile.bind(this, operation)\n\n if (watch) {\n // If we're in watch mode, we want to run the creation on each change (if it validates)\n registerUnlinkOnSigInt(tmpFile)\n this.log(`Watch mode: ${tmpFile}`)\n this.log('Watch mode: Will write documents on each save.')\n this.log('Watch mode: Press Ctrl + C to cancel watch mode.')\n\n // Add race condition protection\n let isProcessing = false\n chokidarWatch(tmpFile).on('change', async () => {\n if (isProcessing) {\n return // Skip if already processing\n }\n isProcessing = true\n\n this.log('')\n try {\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n } finally {\n isProcessing = false\n }\n })\n execa(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n } else {\n // While in normal mode, we just want to wait for the editor to close and run the thing once\n execaSync(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n await fs.unlink(tmpFile).catch(() => {})\n }\n } catch (error) {\n const err = error as Error\n createDocumentDebug('Error in editor workflow', err)\n this.error(`Failed to create documents: ${err.message}`, {exit: 1})\n }\n }\n\n private getErrorMessage(message: string, index: number, isSingle: boolean): string {\n return isSingle ? `Document ${message}` : `Document at index ${index} ${message}`\n }\n\n /**\n * Formats the result message for document operations\n */\n private getResultMessage(\n result: MultipleMutationResult,\n operation: MutationOperationName,\n ): string {\n const joiner = '\\n - '\n if (operation === 'createOrReplace') {\n return `Upserted:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n if (operation === 'create') {\n return `Created:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n // \"Missing\" (createIfNotExists)\n const created: string[] = []\n const skipped: string[] = []\n for (const res of result.results) {\n if (res.operation === 'update') {\n skipped.push(res.id)\n } else {\n created.push(res.id)\n }\n }\n\n if (created.length > 0 && skipped.length > 0) {\n return [\n `Created:\\n - ${created.join(joiner)}`,\n `Skipped (already exists):${joiner}${skipped.join(joiner)}`,\n ].join('\\n\\n')\n } else if (created.length > 0) {\n return `Created:\\n - ${created.join(joiner)}`\n }\n\n return `Skipped (already exists):\\n - ${skipped.join(joiner)}`\n }\n\n /**\n * Reads and processes documents from a file for creation\n */\n private async readAndPerformCreatesFromFile(\n operation: MutationOperationName,\n filePath: string,\n defaultValue: unknown,\n ): Promise<void> {\n let content\n try {\n content = json5.parse(await fs.readFile(filePath, 'utf8'))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to read input file ${filePath}`, error)\n this.log(`Failed to read input: ${error.message}`)\n return\n }\n\n if (isEqual(content, defaultValue)) {\n this.log('Value not modified, doing nothing.')\n this.log('Modify document to trigger creation.')\n return\n }\n\n try {\n const writeResult = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(writeResult, operation))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to write documents`, error)\n let errorMessage = `Failed to write documents: ${error.message}`\n if (error.message.includes('already exists')) {\n errorMessage += '\\nPerhaps you want to use `--replace` or `--missing`?'\n }\n this.error(errorMessage, {exit: 1})\n }\n }\n\n /**\n * Validates a document for Sanity requirements\n */\n private validateDocument(doc: unknown, index: number, arr: unknown[]): void {\n const isSingle = arr.length === 1\n\n if (!isPlainObject(doc)) {\n throw new Error(this.getErrorMessage('must be an object', index, isSingle))\n }\n\n if (!isSanityDocumentish(doc)) {\n throw new Error(\n this.getErrorMessage('must have a `_type` property of type string', index, isSingle),\n )\n }\n\n // Enhanced validations for Sanity document constraints\n const docObj = doc as Record<string, unknown>\n\n // Validate _type is non-empty\n const typeValue = docObj._type?.toString().trim()\n if (!typeValue) {\n throw new Error(this.getErrorMessage('_type cannot be empty', index, isSingle))\n }\n\n // Validate _type format (alphanumeric, underscore, hyphen, dot)\n if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(typeValue)) {\n throw new Error(\n this.getErrorMessage(\n '_type must start with a letter and contain only alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Validate _id format if present\n if (docObj._id && typeof docObj._id === 'string') {\n const idValue = docObj._id.trim()\n if (!idValue) {\n throw new Error(this.getErrorMessage('_id cannot be empty', index, isSingle))\n }\n\n // Sanity document IDs can contain alphanumeric chars, hyphens, underscores, and dots\n if (!/^[a-zA-Z0-9_.-]+$/.test(idValue)) {\n throw new Error(\n this.getErrorMessage(\n '_id can only contain alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Check length constraints (Sanity has reasonable limits)\n if (idValue.length > 200) {\n throw new Error(\n this.getErrorMessage('_id cannot be longer than 200 characters', index, isSingle),\n )\n }\n }\n\n // Warn about reserved fields (these are managed by Sanity)\n const reservedFields = ['_rev', '_updatedAt', '_createdAt']\n for (const field of reservedFields) {\n if (field in docObj) {\n // Note: We don't throw an error here as these might be present in fetched documents\n // that are being re-uploaded, but we could add a debug warning\n createDocumentDebug(\n `Warning: Document ${index} contains reserved field '${field}' which will be ignored by Sanity`,\n )\n }\n }\n }\n\n /**\n * Writes documents to Sanity using the specified operation\n */\n private async writeDocuments(\n documents: {_id?: string; _type: string} | {_id?: string; _type: string}[],\n operation: MutationOperationName,\n ): Promise<MultipleMutationResult> {\n const docs = Array.isArray(documents) ? documents : [documents]\n if (docs.length === 0) {\n throw new Error('No documents provided')\n }\n\n const mutations = docs.map((doc, index): Mutation => {\n this.validateDocument(doc, index, docs)\n if (operation === 'create') {\n return {create: doc}\n }\n\n if (operation === 'createIfNotExists') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createIfNotExists: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n if (operation === 'createOrReplace') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createOrReplace: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n throw new Error(`Unsupported operation ${operation}`)\n })\n\n return this.client.transaction(mutations).commit()\n }\n}\n"],"names":["randomUUID","fs","os","path","Args","Flags","exitCodes","getProjectCliClient","SanityCommand","subdebug","watch","chokidarWatch","execa","execaSync","json5","isEqual","isPlainObject","DOCUMENTS_API_VERSION","getEditor","registerUnlinkOnSigInt","promptForProject","isIdentifiedSanityDocument","isSanityDocumentish","getDatasetFlag","getProjectIdFlag","createDocumentDebug","CreateDocumentCommand","args","file","string","description","required","examples","command","flags","semantics","id","boolean","missing","replace","hiddenAliases","client","run","parse","dataset","useJson5","isUnattended","error","exit","USAGE_ERROR","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","targetDataset","apiVersion","requireUser","operation","contentPath","resolve","process","cwd","content","readFile","result","writeDocuments","log","getResultMessage","err","message","docId","ext","tmpFile","join","tmpdir","stringify","JSON","defaultValue","getDocument","_id","_type","tempDir","mkdir","mode","recursive","writeFile","encoding","editor","readAndPerformCreatesFromFile","bind","isProcessing","on","bin","stdio","unlink","catch","getErrorMessage","index","isSingle","joiner","results","map","res","created","skipped","push","length","filePath","writeResult","errorMessage","includes","validateDocument","doc","arr","Error","docObj","typeValue","toString","trim","test","idValue","reservedFields","field","documents","docs","Array","isArray","mutations","create","createIfNotExists","createOrReplace","transaction","commit"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AAC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KAAKf;YAC/B,IAAI,CAACc,gBAAgB,CAACC,KAAKf,OAAO2B;YAClC,IAAInE,cAAc,UAAU;gBAC1B,OAAO;oBAACuE,QAAQhB;gBAAG;YACrB;YAEA,IAAIvD,cAAc,qBAAqB;gBACrC,IAAItC,2BAA2B6F,MAAM;oBACnC,OAAO;wBAACiB,mBAAmBjB;oBAAG;gBAChC;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAEzD,WAAW;YACnE;YAEA,IAAIA,cAAc,mBAAmB;gBACnC,IAAItC,2BAA2B6F,MAAM;oBACnC,OAAO;wBAACkB,iBAAiBlB;oBAAG;gBAC9B;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAEzD,WAAW;YACnE;YAEA,MAAM,IAAIyD,MAAM,CAAC,sBAAsB,EAAEzD,WAAW;QACtD;QAEA,OAAO,IAAI,CAAClB,MAAM,CAAC4F,WAAW,CAACJ,WAAWK,MAAM;IAClD;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/documents/create.ts"],"sourcesContent":["import {randomUUID} from 'node:crypto'\nimport fs from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {type MultipleMutationResult, type Mutation} from '@sanity/client'\nimport {watch as chokidarWatch} from 'chokidar'\nimport {execa, execaSync} from 'execa'\nimport json5 from 'json5'\nimport isEqual from 'lodash-es/isEqual.js'\nimport isPlainObject from 'lodash-es/isPlainObject.js'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {getEditor, registerUnlinkOnSigInt} from '../../actions/documents/editor.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {isIdentifiedSanityDocument, isSanityDocumentish} from '../../util/isSanityDocumentish.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nexport type MutationOperationName = 'create' | 'createIfNotExists' | 'createOrReplace'\n\nconst createDocumentDebug = subdebug('documents:create')\n\nexport class CreateDocumentCommand extends SanityCommand<typeof CreateDocumentCommand> {\n static override args = {\n file: Args.string({\n description: 'JSON file to create document(s) from',\n required: false,\n }),\n }\n\n static override description = 'Create one or more documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json',\n description: 'Create the document specified in \"myDocument.json\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Open configured $EDITOR and create the specified document(s)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --replace',\n description:\n 'Fetch document with the ID \"myDocId\" and open configured $EDITOR with the current document content (if any). Replace document with the edited version when the editor closes',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --watch --replace --json5',\n description:\n 'Open configured $EDITOR and replace the document with the given content on each save. Use JSON5 file extension and parser for simplified syntax.',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json --project-id abc123',\n description: 'Create documents in a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to create document(s) in',\n semantics: 'override',\n }),\n ...getDatasetFlag({\n description: 'Dataset to create document(s) in',\n semantics: 'override',\n }),\n id: Flags.string({\n description:\n 'Specify a document ID to use. Will fetch remote document ID and populate editor.',\n }),\n json5: Flags.boolean({\n description: 'Use JSON5 file type to allow a \"simplified\" version of JSON',\n }),\n missing: Flags.boolean({\n description: \"On duplicate document IDs, don't modify the target document(s)\",\n }),\n replace: Flags.boolean({\n description:\n 'On duplicate document IDs, replace existing document with specified document(s)',\n }),\n watch: Flags.boolean({\n description: 'Write the documents whenever the target file or buffer changes',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:create']\n\n private client!: Awaited<ReturnType<typeof getProjectCliClient>>\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(CreateDocumentCommand)\n const {file} = args\n const {dataset, id, json5: useJson5, missing, replace, watch} = flags\n\n if (!file && this.isUnattended()) {\n this.error(\n 'Document input is required in unattended mode. Pass it as the `<file>` argument.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n if (replace && missing) {\n this.error(\n 'Cannot use `--replace` and `--missing` together. Remove one flag and try again.',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n if (id && file) {\n this.error(\n 'Cannot use `--id` with the `<file>` argument. Remove `--id` or omit `<file>` and try again.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n this.client = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n let operation: MutationOperationName = 'create'\n if (replace || missing) {\n operation = replace ? 'createOrReplace' : 'createIfNotExists'\n }\n\n if (file) {\n try {\n const contentPath = path.resolve(process.cwd(), file)\n const content = json5.parse(await fs.readFile(contentPath, 'utf8'))\n const result = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(result, operation))\n return\n } catch (error) {\n const err = error as Error\n createDocumentDebug(`Error creating documents from file ${file}`, err)\n this.error(`Failed to create documents: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n try {\n // Create a temporary file and use that as source, opening an editor on it\n const docId = id || randomUUID()\n const ext = useJson5 ? 'json5' : 'json'\n // Add UUID prefix to prevent predictable file names and potential conflicts\n const tmpFile = path.join(os.tmpdir(), 'sanity-cli', `${randomUUID()}-${docId}.${ext}`)\n const stringify = useJson5 ? json5.stringify : JSON.stringify\n const defaultValue = (id && (await this.client.getDocument(id))) || {\n _id: docId,\n _type: 'specify-me',\n }\n\n // Create temp directory with restricted permissions (owner only)\n const tempDir = path.join(os.tmpdir(), 'sanity-cli')\n await fs.mkdir(tempDir, {\n mode: 0o700, // rwx------ (owner read/write/execute only)\n recursive: true,\n })\n\n // Write file with restricted permissions (owner read/write only)\n await fs.writeFile(tmpFile, stringify(defaultValue, null, 2), {\n encoding: 'utf8',\n mode: 0o600, // rw------- (owner read/write only)\n })\n\n const editor = getEditor()\n const readAndPerformCreatesFromFile = this.readAndPerformCreatesFromFile.bind(this, operation)\n\n if (watch) {\n // If we're in watch mode, we want to run the creation on each change (if it validates)\n registerUnlinkOnSigInt(tmpFile)\n this.log(`Watch mode: ${tmpFile}`)\n this.log('Watch mode: Will write documents on each save.')\n this.log('Watch mode: Press Ctrl + C to cancel watch mode.')\n\n // Add race condition protection\n let isProcessing = false\n chokidarWatch(tmpFile).on('change', async () => {\n if (isProcessing) {\n return // Skip if already processing\n }\n isProcessing = true\n\n this.log('')\n try {\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n } finally {\n isProcessing = false\n }\n })\n execa(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n } else {\n // While in normal mode, we just want to wait for the editor to close and run the thing once\n execaSync(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n await fs.unlink(tmpFile).catch(() => {})\n }\n } catch (error) {\n const err = error as Error\n createDocumentDebug('Error in editor workflow', err)\n this.error(`Failed to create documents: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n private getErrorMessage(message: string, index: number, isSingle: boolean): string {\n return isSingle ? `Document ${message}` : `Document at index ${index} ${message}`\n }\n\n /**\n * Formats the result message for document operations\n */\n private getResultMessage(\n result: MultipleMutationResult,\n operation: MutationOperationName,\n ): string {\n const joiner = '\\n - '\n if (operation === 'createOrReplace') {\n return `Upserted:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n if (operation === 'create') {\n return `Created:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n // \"Missing\" (createIfNotExists)\n const created: string[] = []\n const skipped: string[] = []\n for (const res of result.results) {\n if (res.operation === 'update') {\n skipped.push(res.id)\n } else {\n created.push(res.id)\n }\n }\n\n if (created.length > 0 && skipped.length > 0) {\n return [\n `Created:\\n - ${created.join(joiner)}`,\n `Skipped (already exists):${joiner}${skipped.join(joiner)}`,\n ].join('\\n\\n')\n } else if (created.length > 0) {\n return `Created:\\n - ${created.join(joiner)}`\n }\n\n return `Skipped (already exists):\\n - ${skipped.join(joiner)}`\n }\n\n /**\n * Reads and processes documents from a file for creation\n */\n private async readAndPerformCreatesFromFile(\n operation: MutationOperationName,\n filePath: string,\n defaultValue: unknown,\n ): Promise<void> {\n let content\n try {\n content = json5.parse(await fs.readFile(filePath, 'utf8'))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to read input file ${filePath}`, error)\n this.log(`Failed to read input: ${error.message}`)\n return\n }\n\n if (isEqual(content, defaultValue)) {\n this.log('Value not modified, doing nothing.')\n this.log('Modify document to trigger creation.')\n return\n }\n\n try {\n const writeResult = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(writeResult, operation))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to write documents`, error)\n let errorMessage = `Failed to write documents: ${error.message}`\n if (error.message.includes('already exists')) {\n errorMessage += '\\nPerhaps you want to use `--replace` or `--missing`?'\n }\n this.error(errorMessage, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n /**\n * Validates a document for Sanity requirements\n */\n private validateDocument(doc: unknown, index: number, arr: unknown[]): void {\n const isSingle = arr.length === 1\n\n if (!isPlainObject(doc)) {\n throw new Error(this.getErrorMessage('must be an object', index, isSingle))\n }\n\n if (!isSanityDocumentish(doc)) {\n throw new Error(\n this.getErrorMessage('must have a `_type` property of type string', index, isSingle),\n )\n }\n\n // Enhanced validations for Sanity document constraints\n const docObj = doc as Record<string, unknown>\n\n // Validate _type is non-empty\n const typeValue = docObj._type?.toString().trim()\n if (!typeValue) {\n throw new Error(this.getErrorMessage('_type cannot be empty', index, isSingle))\n }\n\n // Validate _type format (alphanumeric, underscore, hyphen, dot)\n if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(typeValue)) {\n throw new Error(\n this.getErrorMessage(\n '_type must start with a letter and contain only alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Validate _id format if present\n if (docObj._id && typeof docObj._id === 'string') {\n const idValue = docObj._id.trim()\n if (!idValue) {\n throw new Error(this.getErrorMessage('_id cannot be empty', index, isSingle))\n }\n\n // Sanity document IDs can contain alphanumeric chars, hyphens, underscores, and dots\n if (!/^[a-zA-Z0-9_.-]+$/.test(idValue)) {\n throw new Error(\n this.getErrorMessage(\n '_id can only contain alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Check length constraints (Sanity has reasonable limits)\n if (idValue.length > 200) {\n throw new Error(\n this.getErrorMessage('_id cannot be longer than 200 characters', index, isSingle),\n )\n }\n }\n\n // Warn about reserved fields (these are managed by Sanity)\n const reservedFields = ['_rev', '_updatedAt', '_createdAt']\n for (const field of reservedFields) {\n if (field in docObj) {\n // Note: We don't throw an error here as these might be present in fetched documents\n // that are being re-uploaded, but we could add a debug warning\n createDocumentDebug(\n `Warning: Document ${index} contains reserved field '${field}' which will be ignored by Sanity`,\n )\n }\n }\n }\n\n /**\n * Writes documents to Sanity using the specified operation\n */\n private async writeDocuments(\n documents: {_id?: string; _type: string} | {_id?: string; _type: string}[],\n operation: MutationOperationName,\n ): Promise<MultipleMutationResult> {\n const docs = Array.isArray(documents) ? documents : [documents]\n if (docs.length === 0) {\n throw new Error('No documents provided')\n }\n\n const mutations = docs.map((doc, index): Mutation => {\n this.validateDocument(doc, index, docs)\n if (operation === 'create') {\n return {create: doc}\n }\n\n if (operation === 'createIfNotExists') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createIfNotExists: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n if (operation === 'createOrReplace') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createOrReplace: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n throw new Error(`Unsupported operation ${operation}`)\n })\n\n return this.client.transaction(mutations).commit()\n }\n}\n"],"names":["randomUUID","fs","os","path","Args","Flags","exitCodes","getProjectCliClient","SanityCommand","subdebug","watch","chokidarWatch","execa","execaSync","json5","isEqual","isPlainObject","DOCUMENTS_API_VERSION","getEditor","registerUnlinkOnSigInt","promptForProject","isIdentifiedSanityDocument","isSanityDocumentish","getDatasetFlag","getProjectIdFlag","createDocumentDebug","CreateDocumentCommand","args","file","string","description","required","examples","command","flags","semantics","id","boolean","missing","replace","hiddenAliases","client","run","parse","dataset","useJson5","isUnattended","error","exit","USAGE_ERROR","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","targetDataset","apiVersion","requireUser","operation","contentPath","resolve","process","cwd","content","readFile","result","writeDocuments","log","getResultMessage","err","message","RUNTIME_ERROR","docId","ext","tmpFile","join","tmpdir","stringify","JSON","defaultValue","getDocument","_id","_type","tempDir","mkdir","mode","recursive","writeFile","encoding","editor","readAndPerformCreatesFromFile","bind","isProcessing","on","bin","stdio","unlink","catch","getErrorMessage","index","isSingle","joiner","results","map","res","created","skipped","push","length","filePath","writeResult","errorMessage","includes","validateDocument","doc","arr","Error","docObj","typeValue","toString","trim","test","idValue","reservedFields","field","documents","docs","Array","isArray","mutations","create","createIfNotExists","createOrReplace","transaction","commit"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AACtC,OAAOC,QAAQ,mBAAkB;AACjC,OAAOC,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAE5B,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAExF,SAAQC,SAASC,aAAa,QAAO,WAAU;AAC/C,SAAQC,KAAK,EAAEC,SAAS,QAAO,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B;oBAAG;gBAChC;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAE1D,WAAW;YACnE;YAEA,IAAIA,cAAc,mBAAmB;gBACnC,IAAItC,2BAA2B8F,MAAM;oBACnC,OAAO;wBAACkB,iBAAiBlB;oBAAG;gBAC9B;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAE1D,WAAW;YACnE;YAEA,MAAM,IAAI0D,MAAM,CAAC,sBAAsB,EAAE1D,WAAW;QACtD;QAEA,OAAO,IAAI,CAAClB,MAAM,CAAC6F,WAAW,CAACJ,WAAWK,MAAM;IAClD;AACF"}
@@ -65,7 +65,7 @@ export class DeleteDocumentCommand extends SanityCommand {
65
65
  ].filter(Boolean);
66
66
  if (ids.length === 0) {
67
67
  this.error('Document ID must be specified', {
68
- exit: 1
68
+ exit: exitCodes.RUNTIME_ERROR
69
69
  });
70
70
  }
71
71
  // Get project configuration (may not exist when running outside a project directory)
@@ -98,14 +98,14 @@ export class DeleteDocumentCommand extends SanityCommand {
98
98
  }
99
99
  if (notFound.length > 0) {
100
100
  this.error(`${notFound.length === 1 ? 'Document' : 'Documents'} not found: ${notFound.join(', ')}`, {
101
- exit: 1
101
+ exit: exitCodes.RUNTIME_ERROR
102
102
  });
103
103
  }
104
104
  } catch (error) {
105
105
  const err = error;
106
106
  deleteDocumentDebug(`Error deleting documents ${ids.join(', ')}`, err);
107
107
  this.error(`Failed to delete ${ids.length} ${ids.length === 1 ? 'document' : 'documents'}: ${err.message}`, {
108
- exit: 1
108
+ exit: exitCodes.RUNTIME_ERROR
109
109
  });
110
110
  }
111
111
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/delete.ts"],"sourcesContent":["import {Args} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst deleteDocumentDebug = subdebug('documents:delete')\n\nexport class DeleteDocumentCommand extends SanityCommand<typeof DeleteDocumentCommand> {\n static override args = {\n id: Args.string({\n description: 'Document ID to delete',\n required: true,\n }),\n ids: Args.string({\n description: 'Additional document IDs to delete',\n required: false,\n }),\n }\n\n static override description = \"Delete one or more documents from the project's configured dataset\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Delete the document with the ID \"myDocId\"',\n },\n {\n command: \"<%= config.bin %> <%= command.id %> 'myDocId'\",\n description: 'ID wrapped in double or single quote works equally well',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dataset=blog someDocId',\n description: 'Delete document with ID \"someDocId\" from dataset \"blog\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> doc1 doc2',\n description: 'Delete the document with ID \"doc1\" and \"doc2\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project-id abc123',\n description: 'Delete a document from a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to delete from', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to delete from', semantics: 'override'}),\n }\n\n static override hiddenAliases: string[] = ['document:delete']\n\n // Disable strict mode to allow for more flexible input\n // This is needed for supporting multiple document IDs\n static override strict = false\n\n public async run(): Promise<void> {\n const {args, argv, flags} = await this.parse(DeleteDocumentCommand)\n const {id} = args\n const {dataset} = flags\n\n // Collect all document IDs from args and argv\n const ids = [id, ...argv.slice(1)].filter(Boolean) as string[]\n\n if (ids.length === 0) {\n this.error('Document ID must be specified', {exit: 1})\n }\n\n // Get project configuration (may not exist when running outside a project directory)\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n const transaction = projectClient.transaction()\n for (const id of ids) {\n transaction.delete(id)\n }\n const {results} = await transaction.commit()\n const deleted = results.filter((res) => res.operation === 'delete').map((res) => res.id)\n const notFound = ids.filter((id) => !deleted.includes(id))\n\n if (deleted.length > 0) {\n this.log(`Deleted ${deleted.length} ${deleted.length === 1 ? 'document' : 'documents'}`)\n }\n\n if (notFound.length > 0) {\n this.error(\n `${notFound.length === 1 ? 'Document' : 'Documents'} not found: ${notFound.join(', ')}`,\n {\n exit: 1,\n },\n )\n }\n } catch (error) {\n const err = error as Error\n deleteDocumentDebug(`Error deleting documents ${ids.join(', ')}`, err)\n this.error(\n `Failed to delete ${ids.length} ${ids.length === 1 ? 'document' : 'documents'}: ${err.message}`,\n {\n exit: 1,\n },\n )\n }\n }\n}\n"],"names":["Args","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","deleteDocumentDebug","DeleteDocumentCommand","args","id","string","description","required","ids","examples","command","flags","semantics","hiddenAliases","strict","run","argv","parse","dataset","slice","filter","Boolean","length","error","exit","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","USAGE_ERROR","targetDataset","projectClient","apiVersion","requireUser","transaction","delete","results","commit","deleted","res","operation","map","notFound","includes","log","join","err","message"],"mappings":"AAAA,SAAQA,IAAI,QAAO,cAAa;AAChC,SAAQC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAExF,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,sBAAsBL,SAAS;AAErC,OAAO,MAAMM,8BAA8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0B,IAAIC,OAAO,EAAE,EAC/F;gBACEzB,MAAM;YACR;QAEJ;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/documents/delete.ts"],"sourcesContent":["import {Args} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst deleteDocumentDebug = subdebug('documents:delete')\n\nexport class DeleteDocumentCommand extends SanityCommand<typeof DeleteDocumentCommand> {\n static override args = {\n id: Args.string({\n description: 'Document ID to delete',\n required: true,\n }),\n ids: Args.string({\n description: 'Additional document IDs to delete',\n required: false,\n }),\n }\n\n static override description = \"Delete one or more documents from the project's configured dataset\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Delete the document with the ID \"myDocId\"',\n },\n {\n command: \"<%= config.bin %> <%= command.id %> 'myDocId'\",\n description: 'ID wrapped in double or single quote works equally well',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dataset=blog someDocId',\n description: 'Delete document with ID \"someDocId\" from dataset \"blog\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> doc1 doc2',\n description: 'Delete the document with ID \"doc1\" and \"doc2\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project-id abc123',\n description: 'Delete a document from a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to delete from', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to delete from', semantics: 'override'}),\n }\n\n static override hiddenAliases: string[] = ['document:delete']\n\n // Disable strict mode to allow for more flexible input\n // This is needed for supporting multiple document IDs\n static override strict = false\n\n public async run(): Promise<void> {\n const {args, argv, flags} = await this.parse(DeleteDocumentCommand)\n const {id} = args\n const {dataset} = flags\n\n // Collect all document IDs from args and argv\n const ids = [id, ...argv.slice(1)].filter(Boolean) as string[]\n\n if (ids.length === 0) {\n this.error('Document ID must be specified', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n // Get project configuration (may not exist when running outside a project directory)\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n const transaction = projectClient.transaction()\n for (const id of ids) {\n transaction.delete(id)\n }\n const {results} = await transaction.commit()\n const deleted = results.filter((res) => res.operation === 'delete').map((res) => res.id)\n const notFound = ids.filter((id) => !deleted.includes(id))\n\n if (deleted.length > 0) {\n this.log(`Deleted ${deleted.length} ${deleted.length === 1 ? 'document' : 'documents'}`)\n }\n\n if (notFound.length > 0) {\n this.error(\n `${notFound.length === 1 ? 'Document' : 'Documents'} not found: ${notFound.join(', ')}`,\n {\n exit: exitCodes.RUNTIME_ERROR,\n },\n )\n }\n } catch (error) {\n const err = error as Error\n deleteDocumentDebug(`Error deleting documents ${ids.join(', ')}`, err)\n this.error(\n `Failed to delete ${ids.length} ${ids.length === 1 ? 'document' : 'documents'}: ${err.message}`,\n {\n exit: exitCodes.RUNTIME_ERROR,\n },\n )\n }\n }\n}\n"],"names":["Args","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","deleteDocumentDebug","DeleteDocumentCommand","args","id","string","description","required","ids","examples","command","flags","semantics","hiddenAliases","strict","run","argv","parse","dataset","slice","filter","Boolean","length","error","exit","RUNTIME_ERROR","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","USAGE_ERROR","targetDataset","projectClient","apiVersion","requireUser","transaction","delete","results","commit","deleted","res","operation","map","notFound","includes","log","join","err","message"],"mappings":"AAAA,SAAQA,IAAI,QAAO,cAAa;AAChC,SAAQC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAExF,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,sBAAsBL,SAAS;AAErC,OAAO,MAAMM,8BAA8BP;IACzC,OAAgBQ,OAAO;QACrBC,IAAIZ,KAAKa,MAAM,CAAC;YACdC,aAAa;YACbC,UAAU;QACZ;QACAC,KAAKhB,KAAKa,MAAM,CAAC;YACfC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,qEAAoE;IAElG,OAAgBG,WAAW;QACzB;YACEC,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;KACD,CAAA;IAED,OAAgBK,QAAQ;QACtB,GAAGX,iBAAiB;YAACM,aAAa;YAA6BM,WAAW;QAAU,EAAE;QACtF,GAAGb,eAAe;YAACO,aAAa;YAA0BM,WAAW;QAAU,EAAE;IACnF,EAAC;IAED,OAAgBC,gBAA0B;QAAC;KAAkB,CAAA;IAE7D,uDAAuD;IACvD,sDAAsD;IACtD,OAAgBC,SAAS,MAAK;IAE9B,MAAaC,MAAqB;QAChC,MAAM,EAACZ,IAAI,EAAEa,IAAI,EAAEL,KAAK,EAAC,GAAG,MAAM,IAAI,CAACM,KAAK,CAACf;QAC7C,MAAM,EAACE,EAAE,EAAC,GAAGD;QACb,MAAM,EAACe,OAAO,EAAC,GAAGP;QAElB,8CAA8C;QAC9C,MAAMH,MAAM;YAAC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K,CACR,GAAGsB,SAASvB,MAAM,KAAK,IAAI,aAAa,YAAY,YAAY,EAAEuB,SAASG,IAAI,CAAC,OAAO,EACvF;oBACExB,MAAM/B,UAAUgC,aAAa;gBAC/B;YAEJ;QACF,EAAE,OAAOF,OAAO;YACd,MAAM0B,MAAM1B;YACZtB,oBAAoB,CAAC,yBAAyB,EAAEO,IAAIwC,IAAI,CAAC,OAAO,EAAEC;YAClE,IAAI,CAAC1B,KAAK,CACR,CAAC,iBAAiB,EAAEf,IAAIc,MAAM,CAAC,CAAC,EAAEd,IAAIc,MAAM,KAAK,IAAI,aAAa,YAAY,EAAE,EAAE2B,IAAIC,OAAO,EAAE,EAC/F;gBACE1B,MAAM/B,UAAUgC,aAAa;YAC/B;QAEJ;IACF;AACF"}
@@ -71,7 +71,7 @@ export class GetDocumentCommand extends SanityCommand {
71
71
  const doc = await projectClient.getDocument(documentId);
72
72
  if (!doc) {
73
73
  this.error(`Document "${documentId}" not found in dataset "${targetDataset}"`, {
74
- exit: 1
74
+ exit: exitCodes.RUNTIME_ERROR
75
75
  });
76
76
  }
77
77
  // Output the document
@@ -84,7 +84,7 @@ export class GetDocumentCommand extends SanityCommand {
84
84
  const err = error;
85
85
  getDocumentDebug(`Error fetching document ${documentId}`, err);
86
86
  this.error(`Failed to fetch document: ${err.message}`, {
87
- exit: 1
87
+ exit: exitCodes.RUNTIME_ERROR
88
88
  });
89
89
  }
90
90
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/get.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {\n colorizeJson,\n exitCodes,\n getProjectCliClient,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst getDocumentDebug = subdebug('documents:get')\n\nexport class GetDocumentCommand extends SanityCommand<typeof GetDocumentCommand> {\n static override args = {\n documentId: Args.string({\n description: 'Document ID to retrieve',\n required: true,\n }),\n }\n\n static override description = 'Get and print a document by ID'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Get the document with ID \"myDocId\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --pretty',\n description: 'Get document with colorized JSON output',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --dataset production',\n description: 'Get document from a specific dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project-id abc123',\n description: 'Get a document from a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to get document from',\n semantics: 'override',\n }),\n ...getDatasetFlag({description: 'Dataset to get document from', semantics: 'override'}),\n pretty: Flags.boolean({\n default: false,\n description: 'Colorize JSON output',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:get']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(GetDocumentCommand)\n const {documentId} = args\n const {dataset, pretty} = flags\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n const doc = await projectClient.getDocument(documentId)\n\n if (!doc) {\n this.error(`Document \"${documentId}\" not found in dataset \"${targetDataset}\"`, {exit: 1})\n }\n\n // Output the document\n if (pretty) {\n this.log(colorizeJson(doc))\n } else {\n this.log(JSON.stringify(doc, null, 2))\n }\n } catch (error) {\n const err = error as Error\n\n getDocumentDebug(`Error fetching document ${documentId}`, err)\n this.error(`Failed to fetch document: ${err.message}`, {exit: 1})\n }\n }\n}\n"],"names":["Args","Flags","colorizeJson","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","getDocumentDebug","GetDocumentCommand","args","documentId","string","description","required","examples","command","flags","semantics","pretty","boolean","default","hiddenAliases","run","parse","dataset","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","error","exit","USAGE_ERROR","targetDataset","projectClient","apiVersion","requireUser","doc","getDocument","log","JSON","stringify","err","message"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SACEC,YAAY,EACZC,SAAS,EACTC,mBAAmB,EACnBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AAEzB,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,mBAAmBL,SAAS;AAElC,OAAO,MAAMM,2BAA2BP;IACtC,OAAgBQ,OAAO;QACrBC,YAAYd,KAAKe,MAAM,CAAC;YACtBC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,iCAAgC;IAE9D,OAAgBE,WAAW;QACzB;YACEC,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SAAS;YACTH,aAAa;QACf;KACD,CAAA;IAED,OAAgBI,QAAQ;QACtB,GAAGV,iBAAiB;YAClBM,aAAa;YACbK,WAAW;QACb,EAAE;QACF,GAAGZ,eAAe;YAACO,aAAa;YAAgCK,WAAW;QAAU,EAAE;QACvFC,QAAQrB,MAAMsB,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,4FACA;gBAACC,MAAMjC,UAAUkC,WAAW;YAAA;QAEhC;QAEA,MAAMC,gBAAgBV,WAAWC,UAAUK,GAAG,EAAEN;QAEhD,IAAI;YACF,MAAMW,gBAAgB,MAAMnC,oBAAoB;gBAC9CoC,YAAYjC;gBACZqB,SAASU;gBACTP;gBACAU,aAAa;YACf;YAEA,MAAMC,MAAM,MAAMH,cAAcI,WAAW,CAAC7B;YAE5C,IAAI,CAAC4B,KAAK;gBACR,IAAI,CAACP,KAAK,CAAC,CAAC,UAAU,EAAErB,WAAW,wBAAwB,EAAEwB,cAAc,CAAC,CAAC,EAAE;oBAACF,MAAM;gBAAC;YACzF;YAEA,sBAAsB;YACtB,IAAId,QAAQ;gBACV,IAAI,CAACsB,GAAG,CAAC1C,aAAawC;YACxB,OAAO;gBACL,IAAI,CAACE,GAAG,CAACC,KAAKC,SAAS,CAACJ,KAAK,MAAM;YACrC;QACF,EAAE,OAAOP,OAAO;YACd,MAAMY,MAAMZ;YAEZxB,iBAAiB,CAAC,wBAAwB,EAAEG,YAAY,EAAEiC;YAC1D,IAAI,CAACZ,KAAK,CAAC,CAAC,0BAA0B,EAAEY,IAAIC,OAAO,EAAE,EAAE;gBAACZ,MAAM;YAAC;QACjE;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/documents/get.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {\n colorizeJson,\n exitCodes,\n getProjectCliClient,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst getDocumentDebug = subdebug('documents:get')\n\nexport class GetDocumentCommand extends SanityCommand<typeof GetDocumentCommand> {\n static override args = {\n documentId: Args.string({\n description: 'Document ID to retrieve',\n required: true,\n }),\n }\n\n static override description = 'Get and print a document by ID'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Get the document with ID \"myDocId\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --pretty',\n description: 'Get document with colorized JSON output',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --dataset production',\n description: 'Get document from a specific dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project-id abc123',\n description: 'Get a document from a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to get document from',\n semantics: 'override',\n }),\n ...getDatasetFlag({description: 'Dataset to get document from', semantics: 'override'}),\n pretty: Flags.boolean({\n default: false,\n description: 'Colorize JSON output',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:get']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(GetDocumentCommand)\n const {documentId} = args\n const {dataset, pretty} = flags\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n const doc = await projectClient.getDocument(documentId)\n\n if (!doc) {\n this.error(`Document \"${documentId}\" not found in dataset \"${targetDataset}\"`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // Output the document\n if (pretty) {\n this.log(colorizeJson(doc))\n } else {\n this.log(JSON.stringify(doc, null, 2))\n }\n } catch (error) {\n const err = error as Error\n\n getDocumentDebug(`Error fetching document ${documentId}`, err)\n this.error(`Failed to fetch document: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Args","Flags","colorizeJson","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","getDocumentDebug","GetDocumentCommand","args","documentId","string","description","required","examples","command","flags","semantics","pretty","boolean","default","hiddenAliases","run","parse","dataset","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","error","exit","USAGE_ERROR","targetDataset","projectClient","apiVersion","requireUser","doc","getDocument","RUNTIME_ERROR","log","JSON","stringify","err","message"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SACEC,YAAY,EACZC,SAAS,EACTC,mBAAmB,EACnBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AAEzB,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,mBAAmBL,SAAS;AAElC,OAAO,MAAMM,2BAA2BP;IACtC,OAAgBQ,OAAO;QACrBC,YAAYd,KAAKe,MAAM,CAAC;YACtBC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,iCAAgC;IAE9D,OAAgBE,WAAW;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,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AAM;YACrC;QACF,EAAE,OAAOP,OAAO;YACd,MAAMa,MAAMb;YAEZxB,iBAAiB,CAAC,wBAAwB,EAAEG,YAAY,EAAEkC;YAC1D,IAAI,CAACb,KAAK,CAAC,CAAC,0BAA0B,EAAEa,IAAIC,OAAO,EAAE,EAAE;gBAACb,MAAMjC,UAAUyC,aAAa;YAAA;QACvF;IACF;AACF"}
@@ -92,7 +92,7 @@ export class QueryDocumentCommand extends SanityCommand {
92
92
  const docs = await projectClient.fetch(query);
93
93
  if (!docs) {
94
94
  this.error('Query returned no results', {
95
- exit: 1
95
+ exit: exitCodes.RUNTIME_ERROR
96
96
  });
97
97
  }
98
98
  // Output the query results
@@ -107,7 +107,7 @@ export class QueryDocumentCommand extends SanityCommand {
107
107
  // Provide more context in error messages
108
108
  const errorMsg = err.message.toLowerCase().includes('syntax') ? `Invalid GROQ query syntax: ${err.message}` : `Failed to run query: ${err.message}`;
109
109
  this.error(`${errorMsg}\nQuery: ${query}`, {
110
- exit: 1
110
+ exit: exitCodes.RUNTIME_ERROR
111
111
  });
112
112
  }
113
113
  }