@sanity/cli 8.35.0 → 8.37.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 (57) hide show
  1. package/dist/actions/build/buildApp.js +1 -4
  2. package/dist/actions/build/buildApp.js.map +1 -1
  3. package/dist/actions/build/buildStudio.js +1 -0
  4. package/dist/actions/build/buildStudio.js.map +1 -1
  5. package/dist/actions/deploy/deployApp.js +32 -12
  6. package/dist/actions/deploy/deployApp.js.map +1 -1
  7. package/dist/actions/deploy/deployChecks.js +2 -1
  8. package/dist/actions/deploy/deployChecks.js.map +1 -1
  9. package/dist/actions/deploy/deployDashboardConfig.js +124 -0
  10. package/dist/actions/deploy/deployDashboardConfig.js.map +1 -0
  11. package/dist/actions/deploy/deployRunner.js.map +1 -1
  12. package/dist/actions/deploy/deployStudio.js +26 -9
  13. package/dist/actions/deploy/deployStudio.js.map +1 -1
  14. package/dist/actions/deploy/resolveDeployTarget.js +2 -2
  15. package/dist/actions/deploy/resolveDeployTarget.js.map +1 -1
  16. package/dist/actions/dev/servers/getDevServerConfig.js +2 -5
  17. package/dist/actions/dev/servers/getDevServerConfig.js.map +1 -1
  18. package/dist/actions/graphql/extractGraphQLAPIs.js +6 -4
  19. package/dist/actions/graphql/extractGraphQLAPIs.js.map +1 -1
  20. package/dist/actions/graphql/extractGraphQLAPIs.worker.js +2 -1
  21. package/dist/actions/graphql/extractGraphQLAPIs.worker.js.map +1 -1
  22. package/dist/actions/preview/previewAction.js +2 -2
  23. package/dist/actions/preview/previewAction.js.map +1 -1
  24. package/dist/actions/targets/resolveCommandTarget.js +130 -0
  25. package/dist/actions/targets/resolveCommandTarget.js.map +1 -0
  26. package/dist/actions/undeploy/runUndeploy.js +33 -5
  27. package/dist/actions/undeploy/runUndeploy.js.map +1 -1
  28. package/dist/actions/undeploy/undeployPlan.js +2 -2
  29. package/dist/actions/undeploy/undeployPlan.js.map +1 -1
  30. package/dist/commands/build.js +8 -1
  31. package/dist/commands/build.js.map +1 -1
  32. package/dist/commands/deploy.js +15 -3
  33. package/dist/commands/deploy.js.map +1 -1
  34. package/dist/commands/documents/query.js +26 -11
  35. package/dist/commands/documents/query.js.map +1 -1
  36. package/dist/commands/media/prune-aspect-data.js +1 -1
  37. package/dist/commands/media/prune-aspect-data.js.map +1 -1
  38. package/dist/commands/media/pull-aspects.js +1 -1
  39. package/dist/commands/media/pull-aspects.js.map +1 -1
  40. package/dist/exports/index.d.ts +2 -2
  41. package/dist/exports/index.js +1 -1
  42. package/dist/exports/index.js.map +1 -1
  43. package/dist/exports/runtime.d.ts +2 -2
  44. package/dist/exports/runtime.js +1 -1
  45. package/dist/exports/runtime.js.map +1 -1
  46. package/dist/generated/apiRoutes.js +37 -0
  47. package/dist/generated/apiRoutes.js.map +1 -1
  48. package/dist/prompts/promptForProject.js +9 -3
  49. package/dist/prompts/promptForProject.js.map +1 -1
  50. package/dist/services/blueprints.js +18 -0
  51. package/dist/services/blueprints.js.map +1 -0
  52. package/dist/util/checkoutBlueprint.js +33 -0
  53. package/dist/util/checkoutBlueprint.js.map +1 -0
  54. package/dist/util/sharedFlags.js +10 -0
  55. package/dist/util/sharedFlags.js.map +1 -1
  56. package/oclif.manifest.json +1143 -1136
  57. package/package.json +16 -16
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/undeploy/runUndeploy.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {CLIError} from '@oclif/core/errors'\nimport {exitCodes, type Output, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage, JsonOutputError} from '@sanity/cli-core/errors'\nimport {\n type UndeployAdapter,\n type UndeployTarget,\n type UndeployTargetResolution,\n} from '@sanity/cli-core/undeploy'\nimport {confirm, spinner} from '@sanity/cli-core/ux'\n\nimport {type UndeployCommand} from '../../commands/undeploy.js'\nimport {\n type CheckReporter,\n createCollectingReporter,\n createFailFastReporter,\n} from '../../util/checks.js'\nimport {toStderrOutput} from '../../util/toStderrOutput.js'\nimport {\n describeUndeployTarget,\n renderUndeployPlan,\n undeployLabel,\n type UndeployPlan,\n undeployPlanToJson,\n} from './undeployPlan.js'\n\nconst undeployDebug = subdebug('undeploy')\n\ntype UndeployFlags = UndeployCommand['flags']\n\nexport interface UndeployOptions {\n flags: UndeployFlags\n isUnattended: boolean\n output: Output\n}\n\n/** What a real undeploy produced — the payload `--json` reports. */\ntype UndeployResult =\n | {application: null; payload: null; reason: string; undeployed: false}\n | {\n application: object | null\n deletes: UndeployTarget['deletes']\n payload: UndeployTarget['payload']\n reason: null\n undeployed: true\n url: string | null\n }\n\n/**\n * Runs an undeploy in the mode the flags select: a real undeploy fails fast,\n * confirms, and deletes; `--dry-run` drives the same target resolution\n * read-only and renders a plan instead. `--json` emits the same information as\n * machine-readable JSON.\n */\nexport async function runUndeploy(\n options: UndeployOptions,\n adapter: UndeployAdapter,\n): Promise<void> {\n const {flags, output} = options\n const json = !!flags.json\n const emitJson = (payload: unknown) => output.logJson(payload)\n let failurePayload: unknown\n\n // The JSON payload owns stdout, so the run's progress logs go to stderr; only\n // the final JSON.stringify writes to stdout.\n const runOptions = json ? {...options, output: toStderrOutput(output)} : options\n\n try {\n if (flags['dry-run']) {\n const reporter = createCollectingReporter()\n const resolution = await resolveTarget(adapter, reporter)\n const plan: UndeployPlan = {\n checks: reporter.results,\n reason: resolution?.type === 'none' ? resolution.message : null,\n target: resolution?.type === 'found' ? resolution.target : null,\n type: adapter.type,\n }\n if (json) {\n const payload = undeployPlanToJson(plan)\n if (plan.checks.some((check) => check.status === 'fail')) failurePayload = payload\n else emitJson(payload)\n } else renderUndeployPlan(plan, output)\n // A blocked plan exits like a real (fail-fast) undeploy would.\n const failed = plan.checks.find((check) => check.status === 'fail')\n if (failed) output.error('Undeploy blocked by failing checks.', {exit: failed.exitCode ?? 1})\n return\n }\n\n const result = await undeployApp(runOptions, adapter)\n if (json && result) emitJson(result)\n } catch (error) {\n const failure = normalizeFailure(error, adapter.type)\n // Preserve the blocked plan or the existing undeployment failure envelope.\n if (json && !flags['dry-run']) {\n failurePayload = {\n application: null,\n error: {message: failure.message},\n payload: null,\n reason: failure.message,\n undeployed: false,\n }\n }\n if (json && failurePayload !== undefined) {\n throw new JsonOutputError(failure.message, failurePayload, failure.exit)\n }\n output.error(failure.message, {exit: failure.exit})\n }\n}\n\n/** The real run: resolve the target, confirm, delete, report. */\nasync function undeployApp(\n options: UndeployOptions,\n adapter: UndeployAdapter,\n): Promise<UndeployResult | undefined> {\n const {flags, output} = options\n\n const resolution = await resolveTarget(adapter, createFailFastReporter(output))\n // A resolve failure never lands here: the fail-fast reporter already exited.\n if (!resolution) return undefined\n if (resolution.type === 'none') {\n output.log(`${resolution.message}.`)\n if (resolution.solution) output.log(`${resolution.solution}.`)\n output.log('Nothing to undeploy.')\n return {application: null, payload: null, reason: resolution.message, undeployed: false}\n }\n\n const {target} = resolution\n if (!flags.yes && options.isUnattended) {\n throw new CLIError('Undeploy requires confirmation. Pass --yes to continue.', {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n if (!flags.yes) {\n const shouldUndeploy = await confirm({\n default: false,\n message: confirmUndeployMessage(target),\n })\n if (!shouldUndeploy) {\n throw new CLIError('Undeploy cancelled', {exit: exitCodes.USER_ABORT})\n }\n }\n\n const label = undeployLabel(target, adapter.type)\n const spin = spinner(`Undeploying ${label}`).start()\n try {\n await adapter.undeploy(target)\n } catch (error) {\n spin.fail()\n undeployDebug(`Error undeploying ${label}`, error)\n // Labeled here, where the target is known — `normalizeFailure` only sees the adapter type.\n throw new CLIError(`Error undeploying ${label}: ${getErrorMessage(error)}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n spin.succeed()\n\n printUndeployed(target, output)\n return {\n application: target.application ?? null,\n deletes: target.deletes,\n payload: target.payload,\n reason: null,\n undeployed: true,\n url: target.url,\n }\n}\n\n/**\n * Resolves the undeploy target and reports the verdict as a check, shared by\n * both modes so a real run and a dry run can't diverge.\n */\nasync function resolveTarget(\n adapter: UndeployAdapter,\n reporter: CheckReporter,\n): Promise<UndeployTargetResolution | null> {\n const spin = spinner('Checking application info').start()\n\n let resolution: UndeployTargetResolution\n try {\n resolution = await adapter.resolveTarget()\n } catch (error) {\n spin.fail()\n undeployDebug('Failed to resolve undeploy target', error)\n reporter.report({\n message: `Failed to resolve undeploy target: ${getErrorMessage(error)}`,\n status: 'fail',\n })\n return null\n }\n\n spin[resolution.type === 'found' ? 'succeed' : 'fail']()\n reporter.report(describeUndeployTarget(resolution))\n return resolution\n}\n\nfunction confirmUndeployMessage(target: UndeployTarget): string {\n if (target.deletes === 'config') {\n return `This will delete the deployed config for ${styleText(\n 'yellow',\n target.title ?? 'this app',\n )}.\nAre you ${styleText('red', 'sure')} you want to undeploy?`\n }\n\n if (target.type === 'coreApp') {\n return `This will undeploy the following application:\n\n Title: ${styleText('yellow', target.title || '(untitled application)')}\n ID: ${styleText('yellow', target.id)}\n\nThe application will no longer be available for any of your users if you proceed.\n\nAre you ${styleText('red', 'sure')} you want to undeploy?`\n }\n\n return `This will undeploy ${styleText('yellow', target.url ?? target.id)} and make it unavailable for your users.\nAre you ${styleText('red', 'sure')} you want to undeploy?`\n}\n\nfunction printUndeployed(target: UndeployTarget, output: Output): void {\n if (target.deletes === 'config') {\n output.log(`\\n${styleText('bold', 'Config deleted.')}`)\n return\n }\n\n if (target.type === 'coreApp') {\n output.log(\n `\\n${styleText('bold', '⏱️ Application undeploy scheduled.')} It might be a few minutes until ${\n target.title ? styleText('italic', `'${target.title}'`) : 'your application'\n } is unavailable.`,\n )\n output.log(\n `\\n${styleText('bold', 'Remember to remove `deployment.appId` from your application configuration')} to avoid errors when redeploying.`,\n )\n return\n }\n\n output.log(\n `\\nStudio undeploy scheduled. It might be a few minutes until ${target.url ?? 'your studio'} is unavailable.`,\n )\n}\n\n/** The one failure diagnosis both the stderr message and the `--json` envelope read. */\nfunction normalizeFailure(\n error: unknown,\n type: UndeployAdapter['type'],\n): {exit: number; message: string} {\n // Ctrl+C on the confirmation prompt isn't a real failure\n if (error instanceof Error && error.name === 'ExitPromptError') {\n return {exit: exitCodes.USER_ABORT, message: 'Undeploy cancelled'}\n }\n // A failed check already carries its own message and exit code\n if (error instanceof CLIError) {\n return {exit: error.oclif?.exit ?? 1, message: error.message}\n }\n const label = type === 'coreApp' ? 'application' : 'studio'\n undeployDebug(`Error undeploying ${label}`, error)\n return {\n exit: exitCodes.RUNTIME_ERROR,\n message: `Error undeploying ${label}: ${getErrorMessage(error)}`,\n }\n}\n"],"names":["styleText","CLIError","exitCodes","subdebug","getErrorMessage","JsonOutputError","confirm","spinner","createCollectingReporter","createFailFastReporter","toStderrOutput","describeUndeployTarget","renderUndeployPlan","undeployLabel","undeployPlanToJson","undeployDebug","runUndeploy","options","adapter","flags","output","json","emitJson","payload","logJson","failurePayload","runOptions","reporter","resolution","resolveTarget","plan","checks","results","reason","type","message","target","some","check","status","failed","find","error","exit","exitCode","result","undeployApp","failure","normalizeFailure","application","undeployed","undefined","log","solution","yes","isUnattended","USAGE_ERROR","shouldUndeploy","default","confirmUndeployMessage","USER_ABORT","label","spin","start","undeploy","fail","RUNTIME_ERROR","succeed","printUndeployed","deletes","url","report","title","id","Error","name","oclif"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,QAAQ,QAAO,qBAAoB;AAC3C,SAAQC,SAAS,EAAeC,QAAQ,QAAO,mBAAkB;AACjE,SAAQC,eAAe,EAAEC,eAAe,QAAO,0BAAyB;AAMxE,SAAQC,OAAO,EAAEC,OAAO,QAAO,sBAAqB;AAGpD,SAEEC,wBAAwB,EACxBC,sBAAsB,QACjB,uBAAsB;AAC7B,SAAQC,cAAc,QAAO,+BAA8B;AAC3D,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,aAAa,EAEbC,kBAAkB,QACb,oBAAmB;AAE1B,MAAMC,gBAAgBZ,SAAS;AAsB/B;;;;;CAKC,GACD,OAAO,eAAea,YACpBC,OAAwB,EACxBC,OAAwB;IAExB,MAAM,EAACC,K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AAChC,MAAMzC,UAAU0D,UAAU;YAAEzB,SAAS;QAAoB;IACnE;IACA,+DAA+D;IAC/D,IAAIO,iBAAiBzC,UAAU;QAC7B,OAAO;YAAC0C,MAAMD,MAAMkC,KAAK,EAAEjC,QAAQ;YAAGR,SAASO,MAAMP,OAAO;QAAA;IAC9D;IACA,MAAM0B,QAAQ3B,SAAS,YAAY,gBAAgB;IACnDnB,cAAc,CAAC,kBAAkB,EAAE8C,OAAO,EAAEnB;IAC5C,OAAO;QACLC,MAAMzC,UAAUgE,aAAa;QAC7B/B,SAAS,CAAC,kBAAkB,EAAE0B,MAAM,EAAE,EAAEzD,gBAAgBsC,QAAQ;IAClE;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/undeploy/runUndeploy.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {CLIError} from '@oclif/core/errors'\nimport {exitCodes, type Output, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage, JsonOutputError} from '@sanity/cli-core/errors'\nimport {\n type UndeployAdapter,\n type UndeployTarget,\n type UndeployTargetResolution,\n} from '@sanity/cli-core/undeploy'\nimport {confirm, spinner} from '@sanity/cli-core/ux'\nimport {fetchDeploySummaryDetails, getWorkbenchUrl} from '@sanity/workbench-cli/deploy'\nimport {formatUndeploySummary} from '@sanity/workbench-cli/undeploy'\n\nimport {type UndeployCommand} from '../../commands/undeploy.js'\nimport {\n type CheckReporter,\n createCollectingReporter,\n createFailFastReporter,\n} from '../../util/checks.js'\nimport {toStderrOutput} from '../../util/toStderrOutput.js'\nimport {\n describeUndeployTarget,\n renderUndeployPlan,\n undeployLabel,\n type UndeployPlan,\n undeployPlanToJson,\n} from './undeployPlan.js'\n\nconst undeployDebug = subdebug('undeploy')\n\ntype UndeployFlags = UndeployCommand['flags']\n\nexport interface UndeployOptions {\n flags: UndeployFlags\n isUnattended: boolean\n output: Output\n}\n\n/** What a real undeploy produced — the payload `--json` reports. */\ntype UndeployResult =\n | {application: null; payload: null; reason: string; undeployed: false}\n | {\n application: object | null\n deletes: UndeployTarget['deletes']\n organizationId?: string\n organizationName?: string | null\n payload: UndeployTarget['payload']\n reason: null\n undeployed: true\n undeployedBy?: string | null\n url: string | null\n }\n\n/**\n * Runs an undeploy in the mode the flags select: a real undeploy fails fast,\n * confirms, and deletes; `--dry-run` drives the same target resolution\n * read-only and renders a plan instead. `--json` emits the same information as\n * machine-readable JSON.\n */\nexport async function runUndeploy(\n options: UndeployOptions,\n adapter: UndeployAdapter,\n): Promise<void> {\n const {flags, output} = options\n const json = !!flags.json\n const emitJson = (payload: unknown) => output.logJson(payload)\n let failurePayload: unknown\n\n // The JSON payload owns stdout, so the run's progress logs go to stderr; only\n // the final JSON.stringify writes to stdout.\n const runOptions = json ? {...options, output: toStderrOutput(output)} : options\n\n try {\n if (flags['dry-run']) {\n const reporter = createCollectingReporter()\n const resolution = await resolveTarget(adapter, reporter)\n const plan: UndeployPlan = {\n checks: reporter.results,\n reason: resolution?.type === 'none' ? resolution.message : null,\n target: resolution?.type === 'found' ? resolution.target : null,\n type: adapter.type,\n }\n if (json) {\n const payload = undeployPlanToJson(plan)\n if (plan.checks.some((check) => check.status === 'fail')) failurePayload = payload\n else emitJson(payload)\n } else renderUndeployPlan(plan, output)\n // A blocked plan exits like a real (fail-fast) undeploy would.\n const failed = plan.checks.find((check) => check.status === 'fail')\n if (failed) output.error('Undeploy blocked by failing checks.', {exit: failed.exitCode ?? 1})\n return\n }\n\n const result = await undeployApp(runOptions, adapter)\n if (json && result) emitJson(result)\n } catch (error) {\n const failure = normalizeFailure(error, adapter.type)\n // Preserve the blocked plan or the existing undeployment failure envelope.\n if (json && !flags['dry-run']) {\n failurePayload = {\n application: null,\n error: {message: failure.message},\n payload: null,\n reason: failure.message,\n undeployed: false,\n }\n }\n if (json && failurePayload !== undefined) {\n throw new JsonOutputError(failure.message, failurePayload, failure.exit)\n }\n output.error(failure.message, {exit: failure.exit})\n }\n}\n\n/** The real run: resolve the target, confirm, delete, report. */\nasync function undeployApp(\n options: UndeployOptions,\n adapter: UndeployAdapter,\n): Promise<UndeployResult | undefined> {\n const {flags, output} = options\n const startedAt = Date.now()\n\n const resolution = await resolveTarget(adapter, createFailFastReporter(output))\n // A resolve failure never lands here: the fail-fast reporter already exited.\n if (!resolution) return undefined\n if (resolution.type === 'none') {\n output.log(`${resolution.message}.`)\n if (resolution.solution) output.log(`${resolution.solution}.`)\n output.log('Nothing to undeploy.')\n return {application: null, payload: null, reason: resolution.message, undeployed: false}\n }\n\n const {target} = resolution\n const summaryDetails = target.organizationId\n ? fetchDeploySummaryDetails(target.organizationId)\n : undefined\n\n if (!flags.yes && options.isUnattended) {\n throw new CLIError('Undeploy requires confirmation. Pass --yes to continue.', {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n if (!flags.yes) {\n const shouldUndeploy = await confirm({\n default: false,\n message: confirmUndeployMessage(target),\n })\n if (!shouldUndeploy) {\n throw new CLIError('Undeploy cancelled', {exit: exitCodes.USER_ABORT})\n }\n }\n\n const label = undeployLabel(target, adapter.type)\n const spin = spinner(`Undeploying ${label}`).start()\n try {\n await adapter.undeploy(target)\n } catch (error) {\n spin.fail()\n undeployDebug(`Error undeploying ${label}`, error)\n // Labeled here, where the target is known — `normalizeFailure` only sees the adapter type.\n throw new CLIError(`Error undeploying ${label}: ${getErrorMessage(error)}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n spin.succeed()\n\n const details = await summaryDetails\n printUndeployed(target, output, {...details, durationMs: Date.now() - startedAt})\n\n return {\n application: target.application ?? null,\n deletes: target.deletes,\n payload: target.payload,\n reason: null,\n undeployed: true,\n url: target.url,\n ...(target.organizationId && {\n organizationId: target.organizationId,\n organizationName: details?.organizationName ?? null,\n undeployedBy: details?.userName ?? null,\n }),\n }\n}\n\n/**\n * Resolves the undeploy target and reports the verdict as a check, shared by\n * both modes so a real run and a dry run can't diverge.\n */\nasync function resolveTarget(\n adapter: UndeployAdapter,\n reporter: CheckReporter,\n): Promise<UndeployTargetResolution | null> {\n const spin = spinner('Checking application info').start()\n\n let resolution: UndeployTargetResolution\n try {\n resolution = await adapter.resolveTarget()\n } catch (error) {\n spin.fail()\n undeployDebug('Failed to resolve undeploy target', error)\n reporter.report({\n message: `Failed to resolve undeploy target: ${getErrorMessage(error)}`,\n status: 'fail',\n })\n return null\n }\n\n spin[resolution.type === 'found' ? 'succeed' : 'fail']()\n reporter.report(describeUndeployTarget(resolution))\n return resolution\n}\n\nfunction confirmUndeployMessage(target: UndeployTarget): string {\n if (target.deletes === 'config') {\n return `This will delete the ${styleText('yellow', target.title ?? 'deployed config')}.\nAre you ${styleText('red', 'sure')} you want to undeploy?`\n }\n\n if (target.type === 'coreApp') {\n return `This will undeploy the following application:\n\n Title: ${styleText('yellow', target.title || '(untitled application)')}\n ID: ${styleText('yellow', target.id)}\n\nThe application will no longer be available for any of your users if you proceed.\n\nAre you ${styleText('red', 'sure')} you want to undeploy?`\n }\n\n return `This will undeploy ${styleText('yellow', target.url ?? target.id)} and make it unavailable for your users.\nAre you ${styleText('red', 'sure')} you want to undeploy?`\n}\n\nfunction printUndeployed(\n target: UndeployTarget,\n output: Output,\n summary: {\n durationMs: number\n hostSlug?: string | null\n organizationName?: string | null\n userName?: string | null\n },\n): void {\n if (target.deletes === 'config') {\n output.log(\n formatUndeploySummary({\n ...summary,\n organizationId: target.organizationId,\n title: target.title ?? 'Deployed config',\n url: target.url ?? getWorkbenchUrl(target.organizationId),\n }),\n )\n return\n }\n\n if (target.organizationId) {\n output.log(\n formatUndeploySummary({\n ...summary,\n organizationId: target.organizationId,\n title: target.title ?? target.id,\n type: target.type,\n url: getWorkbenchUrl(target.organizationId, summary.hostSlug),\n }),\n )\n return\n }\n\n if (target.type === 'coreApp') {\n output.log(\n `\\n${styleText('bold', '⏱️ Application undeploy scheduled.')} It might be a few minutes until ${\n target.title ? styleText('italic', `'${target.title}'`) : 'your application'\n } is unavailable.`,\n )\n output.log(\n `\\n${styleText('bold', 'Remember to remove `deployment.appId` from your application configuration')} to avoid errors when redeploying.`,\n )\n return\n }\n\n output.log(\n `\\nStudio undeploy scheduled. It might be a few minutes until ${target.url ?? 'your studio'} is unavailable.`,\n )\n}\n\n/** The one failure diagnosis both the stderr message and the `--json` envelope read. */\nfunction normalizeFailure(\n error: unknown,\n type: UndeployAdapter['type'],\n): {exit: number; message: string} {\n // Ctrl+C on the confirmation prompt isn't a real failure\n if (error instanceof Error && error.name === 'ExitPromptError') {\n return {exit: exitCodes.USER_ABORT, message: 'Undeploy cancelled'}\n }\n // A failed check already carries its own message and exit code\n if (error instanceof CLIError) {\n return {exit: error.oclif?.exit ?? 1, message: error.message}\n }\n const label = type === 'coreApp' ? 'application' : 'studio'\n undeployDebug(`Error undeploying ${label}`, error)\n return {\n exit: exitCodes.RUNTIME_ERROR,\n message: `Error undeploying ${label}: ${getErrorMessage(error)}`,\n }\n}\n"],"names":["styleText","CLIError","exitCodes","subdebug","getErrorMessage","JsonOutputError","confirm","spinner","fetchDeploySummaryDetails","getWorkbenchUrl","formatUndeploySummary","createCollectingReporter","createFailFastReporter","toStderrOutput","describeUndeployTarget","renderUndeployPlan","undeployLabel","undeployPlanToJson","undeployDebug","runUndeploy","options","adapter","flags","output","json","emitJson","payload","logJson","failurePayload","runOptions","reporter","resolution","resolveTarget","plan","checks","results","reason","type","message","target","some","check","status","failed","find","error","exit","exitCode","result","undeployApp","failure","normalizeFailure","application","undeployed","undefined","startedAt","Date","now","log","solution","summaryDetails","organizationId","yes","isUnattended","USAGE_ERROR","shouldUndeploy","default","confirmUndeployMessage","USER_ABORT","label","spin","start","undeploy","fail","RUNTIME_ERROR","succeed","details","printUndeployed","durationMs","deletes","url","organizationName","undeployedBy","userName","report","title","id","summary","hostSlug","Error","name","oclif"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,QAAQ,QAAO,qBAAoB;AAC3C,SAAQC,SAAS,EAAeC,QAAQ,QAAO,mBAAkB;AACjE,SAAQC,eAAe,EAAEC,eAAe,QAAO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C,UAAUkE,UAAU;YAAE9B,SAAS;QAAoB;IACnE;IACA,+DAA+D;IAC/D,IAAIO,iBAAiB5C,UAAU;QAC7B,OAAO;YAAC6C,MAAMD,MAAM8C,KAAK,EAAE7C,QAAQ;YAAGR,SAASO,MAAMP,OAAO;QAAA;IAC9D;IACA,MAAM+B,QAAQhC,SAAS,YAAY,gBAAgB;IACnDnB,cAAc,CAAC,kBAAkB,EAAEmD,OAAO,EAAExB;IAC5C,OAAO;QACLC,MAAM5C,UAAUwE,aAAa;QAC7BpC,SAAS,CAAC,kBAAkB,EAAE+B,MAAM,EAAE,EAAEjE,gBAAgByC,QAAQ;IAClE;AACF"}
@@ -5,7 +5,7 @@ export function canUndeploy(plan) {
5
5
  }
6
6
  /** What an undeploy deletes, phrased for the human output. */ export function undeployLabel(target, type) {
7
7
  if (target?.deletes === 'config') {
8
- return `installation config${target.title ? ` for "${target.title}"` : ''}`;
8
+ return target.title ?? 'deployed config';
9
9
  }
10
10
  return type === 'coreApp' ? 'application' : 'studio';
11
11
  }
@@ -46,7 +46,7 @@ export function canUndeploy(plan) {
46
46
  const { target } = resolution;
47
47
  if (target.deletes === 'config') {
48
48
  return {
49
- message: target.title ? `Undeploys the installation config for "${target.title}"` : 'Undeploys the installation config',
49
+ message: `Undeploys the ${target.title ?? 'deployed config'}`,
50
50
  status: 'pass'
51
51
  };
52
52
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/undeploy/undeployPlan.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type Output} from '@sanity/cli-core'\nimport {type UndeployTarget, type UndeployTargetResolution} from '@sanity/cli-core/undeploy'\n\nimport {type Check, checkStatusIcon, renderIssues} from '../../util/checks.js'\n\n/** What a `--dry-run` undeploy would do: the real undeploy sequence with the deletion gated off. */\nexport interface UndeployPlan {\n checks: Check[]\n /** Why there is nothing to undeploy; `null` when a target resolved. */\n reason: string | null\n /** What would be deleted; `null` when there is nothing to undeploy. */\n target: UndeployTarget | null\n type: 'coreApp' | 'studio'\n}\n\nexport function canUndeploy(plan: UndeployPlan): boolean {\n return plan.target !== null && plan.checks.every((check) => check.status !== 'fail')\n}\n\n/** What an undeploy deletes, phrased for the human output. */\nexport function undeployLabel(target: UndeployTarget | null, type: 'coreApp' | 'studio'): string {\n if (target?.deletes === 'config') {\n return `installation config${target.title ? ` for \"${target.title}\"` : ''}`\n }\n return type === 'coreApp' ? 'application' : 'studio'\n}\n\n/**\n * A machine-readable projection of the plan: blocking problems mapped to their\n * fix, warnings as messages. Derived from the same checks and target the human\n * report renders, so the two can't drift.\n */\nexport function undeployPlanToJson(plan: UndeployPlan): UndeployPlanJson {\n const errors: Record<string, string | null> = {}\n const warnings: string[] = []\n for (const check of plan.checks) {\n if (check.status === 'fail') errors[check.message] = check.solution ?? null\n else if (check.status === 'warn') warnings.push(check.message)\n }\n\n return {\n // Only a successful undeploy reports the backend's record.\n application: null,\n canUndeploy: canUndeploy(plan),\n deletes: plan.target?.deletes ?? null,\n errors,\n payload: plan.target?.payload ?? null,\n reason: plan.reason ?? plan.checks.find((check) => check.status === 'fail')?.message ?? null,\n url: plan.target?.url ?? null,\n warnings,\n }\n}\n\ninterface UndeployPlanJson {\n application: null\n canUndeploy: boolean\n deletes: UndeployTarget['deletes'] | null\n errors: Record<string, string | null>\n payload: UndeployTarget['payload'] | null\n reason: string | null\n url: string | null\n warnings: string[]\n}\n\n/**\n * The single diagnosis for each undeploy-target verdict, shared by the dry-run\n * report and the real run so message and fix can't drift between the two.\n */\nexport function describeUndeployTarget(resolution: UndeployTargetResolution): Check {\n if (resolution.type === 'none') {\n return {message: resolution.message, solution: resolution.solution, status: 'skip'}\n }\n\n const {target} = resolution\n if (target.deletes === 'config') {\n return {\n message: target.title\n ? `Undeploys the installation config for \"${target.title}\"`\n : 'Undeploys the installation config',\n status: 'pass',\n }\n }\n if (target.type === 'studio') {\n return {message: `Undeploys studio ${target.url ?? target.id}`, status: 'pass'}\n }\n const name = target.title ? `\"${target.title}\" (${target.id})` : target.id\n return {message: `Undeploys application ${name}`, status: 'pass'}\n}\n\nexport function renderUndeployPlan(plan: UndeployPlan, output: Output): void {\n const problems = plan.checks.filter((check) => check.status === 'fail')\n const warnings = plan.checks.filter((check) => check.status === 'warn')\n\n output.log('\\nDry run — no changes made.\\n')\n\n // Only pass/skip here; problems and warnings render below with their fixes.\n // A passing target check already says what gets undeployed, so an\n // undeployable plan needs no extra verdict line.\n for (const check of plan.checks) {\n if (check.status === 'pass' || check.status === 'skip') {\n const fix = check.solution ? `: ${check.solution}` : ''\n output.log(` ${checkStatusIcon(check.status)} ${check.message}${fix}`)\n }\n }\n\n if (plan.target) renderTarget(plan.target, output)\n\n if (!canUndeploy(plan)) {\n if (problems.length > 0) {\n const label = undeployLabel(plan.target, plan.type)\n output.log(\n styleText(\n 'red',\n `\\n${checkStatusIcon('fail')} ${label[0].toUpperCase()}${label.slice(1)} can not be undeployed.`,\n ),\n )\n } else {\n output.log('\\nNothing to undeploy.')\n }\n }\n\n renderIssues(output, 'Problems to fix:', problems)\n renderIssues(output, 'Warnings:', warnings)\n}\n\nfunction renderTarget(target: UndeployTarget, output: Output): void {\n const rows: [string, string | null][] = [\n ['Title', target.title],\n ['ID', target.id],\n ['URL', target.url],\n ]\n\n output.log('')\n for (const [key, value] of rows) {\n if (value) output.log(` ${key.padEnd(8)} ${styleText('yellow', value)}`)\n }\n\n // Adapter-authored lines about what gets deleted (interfaces, config snapshots, …)\n for (const entry of target.summary ?? []) {\n for (const line of entry.split('\\n')) output.log(` ${line}`)\n }\n}\n"],"names":["styleText","checkStatusIcon","renderIssues","canUndeploy","plan","target","checks","every","check","status","undeployLabel","type","deletes","title","undeployPlanToJson","errors","warnings","message","solution","push","application","payload","reason","find","url","describeUndeployTarget","resolution","id","name","renderUndeployPlan","output","problems","filter","log","fix","renderTarget","length","label","toUpperCase","slice","rows","key","value","padEnd","entry","summary","line","split"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAKnC,SAAoBC,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AAMS,OAAO,GAAGiB,KAAK;QACxE;IACF;IAEA,IAAI9B,KAAKC,MAAM,EAAE8B,aAAa/B,KAAKC,MAAM,EAAEyB;IAE3C,IAAI,CAAC3B,YAAYC,OAAO;QACtB,IAAI2B,SAASK,MAAM,GAAG,GAAG;YACvB,MAAMC,QAAQ3B,cAAcN,KAAKC,MAAM,EAAED,KAAKO,IAAI;YAClDmB,OAAOG,GAAG,CACRjC,UACE,OACA,CAAC,EAAE,EAAEC,gBAAgB,QAAQ,CAAC,EAAEoC,KAAK,CAAC,EAAE,CAACC,WAAW,KAAKD,MAAME,KAAK,CAAC,GAAG,uBAAuB,CAAC;QAGtG,OAAO;YACLT,OAAOG,GAAG,CAAC;QACb;IACF;IAEA/B,aAAa4B,QAAQ,oBAAoBC;IACzC7B,aAAa4B,QAAQ,aAAad;AACpC;AAEA,SAASmB,aAAa9B,MAAsB,EAAEyB,MAAc;IAC1D,MAAMU,OAAkC;QACtC;YAAC;YAASnC,OAAOQ,KAAK;SAAC;QACvB;YAAC;YAAMR,OAAOsB,EAAE;SAAC;QACjB;YAAC;YAAOtB,OAAOmB,GAAG;SAAC;KACpB;IAEDM,OAAOG,GAAG,CAAC;IACX,KAAK,MAAM,CAACQ,KAAKC,MAAM,IAAIF,KAAM;QAC/B,IAAIE,OAAOZ,OAAOG,GAAG,CAAC,CAAC,IAAI,EAAEQ,IAAIE,MAAM,CAAC,GAAG,CAAC,EAAE3C,UAAU,UAAU0C,QAAQ;IAC5E;IAEA,mFAAmF;IACnF,KAAK,MAAME,SAASvC,OAAOwC,OAAO,IAAI,EAAE,CAAE;QACxC,KAAK,MAAMC,QAAQF,MAAMG,KAAK,CAAC,MAAOjB,OAAOG,GAAG,CAAC,CAAC,IAAI,EAAEa,MAAM;IAChE;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/undeploy/undeployPlan.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type Output} from '@sanity/cli-core'\nimport {type UndeployTarget, type UndeployTargetResolution} from '@sanity/cli-core/undeploy'\n\nimport {type Check, checkStatusIcon, renderIssues} from '../../util/checks.js'\n\n/** What a `--dry-run` undeploy would do: the real undeploy sequence with the deletion gated off. */\nexport interface UndeployPlan {\n checks: Check[]\n /** Why there is nothing to undeploy; `null` when a target resolved. */\n reason: string | null\n /** What would be deleted; `null` when there is nothing to undeploy. */\n target: UndeployTarget | null\n type: 'coreApp' | 'studio'\n}\n\nexport function canUndeploy(plan: UndeployPlan): boolean {\n return plan.target !== null && plan.checks.every((check) => check.status !== 'fail')\n}\n\n/** What an undeploy deletes, phrased for the human output. */\nexport function undeployLabel(target: UndeployTarget | null, type: 'coreApp' | 'studio'): string {\n if (target?.deletes === 'config') {\n return target.title ?? 'deployed config'\n }\n return type === 'coreApp' ? 'application' : 'studio'\n}\n\n/**\n * A machine-readable projection of the plan: blocking problems mapped to their\n * fix, warnings as messages. Derived from the same checks and target the human\n * report renders, so the two can't drift.\n */\nexport function undeployPlanToJson(plan: UndeployPlan): UndeployPlanJson {\n const errors: Record<string, string | null> = {}\n const warnings: string[] = []\n for (const check of plan.checks) {\n if (check.status === 'fail') errors[check.message] = check.solution ?? null\n else if (check.status === 'warn') warnings.push(check.message)\n }\n\n return {\n // Only a successful undeploy reports the backend's record.\n application: null,\n canUndeploy: canUndeploy(plan),\n deletes: plan.target?.deletes ?? null,\n errors,\n payload: plan.target?.payload ?? null,\n reason: plan.reason ?? plan.checks.find((check) => check.status === 'fail')?.message ?? null,\n url: plan.target?.url ?? null,\n warnings,\n }\n}\n\ninterface UndeployPlanJson {\n application: null\n canUndeploy: boolean\n deletes: UndeployTarget['deletes'] | null\n errors: Record<string, string | null>\n payload: UndeployTarget['payload'] | null\n reason: string | null\n url: string | null\n warnings: string[]\n}\n\n/**\n * The single diagnosis for each undeploy-target verdict, shared by the dry-run\n * report and the real run so message and fix can't drift between the two.\n */\nexport function describeUndeployTarget(resolution: UndeployTargetResolution): Check {\n if (resolution.type === 'none') {\n return {message: resolution.message, solution: resolution.solution, status: 'skip'}\n }\n\n const {target} = resolution\n if (target.deletes === 'config') {\n return {\n message: `Undeploys the ${target.title ?? 'deployed config'}`,\n status: 'pass',\n }\n }\n if (target.type === 'studio') {\n return {message: `Undeploys studio ${target.url ?? target.id}`, status: 'pass'}\n }\n const name = target.title ? `\"${target.title}\" (${target.id})` : target.id\n return {message: `Undeploys application ${name}`, status: 'pass'}\n}\n\nexport function renderUndeployPlan(plan: UndeployPlan, output: Output): void {\n const problems = plan.checks.filter((check) => check.status === 'fail')\n const warnings = plan.checks.filter((check) => check.status === 'warn')\n\n output.log('\\nDry run — no changes made.\\n')\n\n // Only pass/skip here; problems and warnings render below with their fixes.\n // A passing target check already says what gets undeployed, so an\n // undeployable plan needs no extra verdict line.\n for (const check of plan.checks) {\n if (check.status === 'pass' || check.status === 'skip') {\n const fix = check.solution ? `: ${check.solution}` : ''\n output.log(` ${checkStatusIcon(check.status)} ${check.message}${fix}`)\n }\n }\n\n if (plan.target) renderTarget(plan.target, output)\n\n if (!canUndeploy(plan)) {\n if (problems.length > 0) {\n const label = undeployLabel(plan.target, plan.type)\n output.log(\n styleText(\n 'red',\n `\\n${checkStatusIcon('fail')} ${label[0].toUpperCase()}${label.slice(1)} can not be undeployed.`,\n ),\n )\n } else {\n output.log('\\nNothing to undeploy.')\n }\n }\n\n renderIssues(output, 'Problems to fix:', problems)\n renderIssues(output, 'Warnings:', warnings)\n}\n\nfunction renderTarget(target: UndeployTarget, output: Output): void {\n const rows: [string, string | null][] = [\n ['Title', target.title],\n ['ID', target.id],\n ['URL', target.url],\n ]\n\n output.log('')\n for (const [key, value] of rows) {\n if (value) output.log(` ${key.padEnd(8)} ${styleText('yellow', value)}`)\n }\n\n // Adapter-authored lines about what gets deleted (interfaces, config snapshots, …)\n for (const entry of target.summary ?? []) {\n for (const line of entry.split('\\n')) output.log(` ${line}`)\n }\n}\n"],"names":["styleText","checkStatusIcon","renderIssues","canUndeploy","plan","target","checks","every","check","status","undeployLabel","type","deletes","title","undeployPlanToJson","errors","warnings","message","solution","push","application","payload","reason","find","url","describeUndeployTarget","resolution","id","name","renderUndeployPlan","output","problems","filter","log","fix","renderTarget","length","label","toUpperCase","slice","rows","key","value","padEnd","entry","summary","line","split"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAKnC,SAAoBC,eAAe,EAAEC,YAAY,QAAO,uBAAsB;AAY9E,OAAO,SAASC,YAAYC,IAAkB;IAC5C,OAAOA,KAAKC,MAAM,KAAK,QAAQD,KAAKE,MAAM,CAACC,KAAK,CAAC,CAACC,QAAUA,MAAMC,MAAM,KAAK;AAC/E;AAEA,4DAA4D,GAC5D,OAAO,SAASC,cAAcL,MAA6B,EAAEM,IAA0B;IACrF,IAAIN,QAAQO,YAAY,UAAU;QAChC,OAAOP,OAAOQ,KAAK,IAAI;IACzB;IACA,OAAOF,SAAS,YAAY,gBAAgB;AAC9C;AAEA;;;;CAIC,GACD,OAAO,SAASG,mBAAmBV,IAAkB;IACnD,MAAMW,SAAwC,CAAC;IAC/C,MAAMC,WAAqB,EAAE;IAC7B,KAAK,MAAMR,SAASJ,KAAKE,MAAM,CAAE;QAC/B,IAAIE,MAAMC,MAAM,KAAK,QAAQM,MAAM,CAACP,MAAMS,OAAO,CAAC,GAAGT,MAAMU,QAAQ,IAAI;aAClE,IAAIV,MAAMC,MAAM,KAAK,QAAQO,SAASG,IAAI,CAACX,MAAMS,OAAO;IAC/D;IAEA,OAAO;QACL,2DAA2D;QAC3DG,aAAa;QACbjB,aAAaA,YAAYC;QACzBQ,SAASR,KAAKC,MAAM,EAAEO,WAAW;QACjCG;QACAM,SAASjB,KAAKC,MAAM,EAAEgB,WAAW;QACjCC,QAAQlB,KAAKkB,MAAM,IAAIlB,KAAKE,MAAM,CAACiB,IAAI,CAAC,CAACf,QAAUA,MAAMC,MAAM,KAAK,SAASQ,WAAW;QACxFO,KAAKpB,KAAKC,MAAM,EAAEmB,OAAO;QACzBR;IACF;AACF;AAaA;;;CAGC,GACD,OAA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clif/core';
2
2
  import { SanityCommand } from '@sanity/cli-core';
3
+ import { startBuildSummary } from '@sanity/workbench-cli/build';
3
4
  import { buildApp } from '../actions/build/buildApp.js';
4
5
  import { buildStudio } from '../actions/build/buildStudio.js';
5
6
  import { shouldAutoUpdate } from '../actions/build/shouldAutoUpdate.js';
@@ -51,8 +52,12 @@ export class BuildCommand extends SanityCommand {
51
52
  flags,
52
53
  output
53
54
  });
55
+ const summarize = startBuildSummary({
56
+ cliConfig,
57
+ isApp
58
+ });
54
59
  const buildFunc = isApp ? buildApp : buildStudio;
55
- await buildFunc({
60
+ const { mfManifest } = await buildFunc({
56
61
  autoUpdatesEnabled,
57
62
  cliConfig,
58
63
  flags,
@@ -60,6 +65,8 @@ export class BuildCommand extends SanityCommand {
60
65
  output,
61
66
  workDir
62
67
  });
68
+ // A Dashboard build without a manifest stopped at the version mismatch prompt.
69
+ if (summarize && mfManifest) output.log(await summarize());
63
70
  }
64
71
  }
65
72
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commands/build.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\n\nimport {buildApp} from '../actions/build/buildApp.js'\nimport {buildStudio} from '../actions/build/buildStudio.js'\nimport {shouldAutoUpdate} from '../actions/build/shouldAutoUpdate.js'\nimport {determineIsApp} from '../util/determineIsApp.js'\n\nexport class BuildCommand extends SanityCommand<typeof BuildCommand> {\n static override args = {\n outputDir: Args.directory({description: 'Output directory'}),\n }\n\n static override description = 'Build Sanity Studio into a static bundle'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n '<%= config.bin %> <%= command.id %> --no-minify --source-maps',\n ]\n\n static override flags = {\n 'auto-updates': Flags.boolean({\n allowNo: true,\n description: 'Enable/disable auto updates of studio versions',\n }),\n minify: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Enable/disable minifying of built bundles',\n }),\n 'source-maps': Flags.boolean({\n allowNo: true,\n default: false,\n description: 'Enable source maps for built bundles (increases size of bundle)',\n }),\n stats: Flags.boolean({\n default: false,\n description: 'Show stats about the built bundles',\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 cliConfig = await this.getCliConfig()\n\n const {flags} = await this.parse(BuildCommand)\n\n const isApp = determineIsApp(cliConfig)\n\n const workDir = (await this.getProjectRoot()).directory\n\n const output = this.output\n\n const autoUpdatesEnabled = shouldAutoUpdate({cliConfig, flags, output})\n\n const buildFunc = isApp ? buildApp : buildStudio\n await buildFunc({\n autoUpdatesEnabled,\n cliConfig,\n flags,\n outDir: this.args.outputDir,\n output,\n workDir,\n })\n }\n}\n"],"names":["Args","Flags","SanityCommand","buildApp","buildStudio","shouldAutoUpdate","determineIsApp","BuildCommand","args","outputDir","directory","description","examples","flags","boolean","allowNo","minify","default","stats","yes","char","run","cliConfig","getCliConfig","parse","isApp","workDir","getProjectRoot","output","autoUpdatesEnabled","buildFunc","outDir"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,aAAa,QAAO,mBAAkB;AAE9C,SAAQC,QAAQ,QAAO,+BAA8B;AACrD,SAAQC,WAAW,QAAO,kCAAiC;AAC3D,SAAQC,gBAAgB,QAAO,uCAAsC;AACrE,SAAQC,cAAc,QAAO,4BAA2B;AAExD,OAAO,MAAMC,qBAAqBL;IAChC,OAAgBM,OAAO;QACrBC,WAAWT,KAAKU,SAAS,CAAC;YAACC,aAAa;QAAkB;IAC5D,EAAC;IAED,OAAgBA,cAAc,2CAA0C;IAExE,OAAgBC,WAAW;QACzB;QACA;KACD,CAAA;IAED,OAAgBC,QAAQ;QACtB,gBAAgBZ,MAAMa,OAAO,CAAC;YAC5BC,SAAS;YACTJ,aAAa;QACf;QACAK,QAAQf,MAAMa,OAAO,CAAC;YACpBC,SAAS;YACTE,SAAS;YACTN,aAAa;QACf;QACA,eAAeV,MAAMa,OAAO,CAAC;YAC3BC,SAAS;YACTE,SAAS;YACTN,aAAa;QACf;QACAO,OAAOjB,MAAMa,OAAO,CAAC;YACnBG,SAAS;YACTN,aAAa;QACf;QACAQ,KAAKlB,MAAMa,OAAO,CAAC;YACjBM,MAAM;YACNH,SAAS;YACTN,aACE;QACJ;IACF,EAAC;IAED,MAAaU,MAAqB;QAChC,MAAMC,YAAY,MAAM,IAAI,CAACC,YAAY;QAEzC,MAAM,EAACV,KAAK,EAAC,GAAG,MAAM,IAAI,CAACW,KAAK,CAACjB;QAEjC,MAAMkB,QAAQnB,eAAegB;QAE7B,MAAMI,UAAU,AAAC,CAAA,MAAM,IAAI,CAACC,cAAc,EAAC,EAAGjB,SAAS;QAEvD,MAAMkB,SAAS,IAAI,CAACA,MAAM;QAE1B,MAAMC,qBAAqBxB,iBAAiB;YAACiB;YAAWT;YAAOe;QAAM;QAErE,MAAME,YAAYL,QAAQtB,WAAWC;QACrC,MAAM0B,UAAU;YACdD;YACAP;YACAT;YACAkB,QAAQ,IAAI,CAACvB,IAAI,CAACC,SAAS;YAC3BmB;YACAF;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/commands/build.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {startBuildSummary} from '@sanity/workbench-cli/build'\n\nimport {buildApp} from '../actions/build/buildApp.js'\nimport {buildStudio} from '../actions/build/buildStudio.js'\nimport {shouldAutoUpdate} from '../actions/build/shouldAutoUpdate.js'\nimport {determineIsApp} from '../util/determineIsApp.js'\n\nexport class BuildCommand extends SanityCommand<typeof BuildCommand> {\n static override args = {\n outputDir: Args.directory({description: 'Output directory'}),\n }\n\n static override description = 'Build Sanity Studio into a static bundle'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n '<%= config.bin %> <%= command.id %> --no-minify --source-maps',\n ]\n\n static override flags = {\n 'auto-updates': Flags.boolean({\n allowNo: true,\n description: 'Enable/disable auto updates of studio versions',\n }),\n minify: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Enable/disable minifying of built bundles',\n }),\n 'source-maps': Flags.boolean({\n allowNo: true,\n default: false,\n description: 'Enable source maps for built bundles (increases size of bundle)',\n }),\n stats: Flags.boolean({\n default: false,\n description: 'Show stats about the built bundles',\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 cliConfig = await this.getCliConfig()\n\n const {flags} = await this.parse(BuildCommand)\n\n const isApp = determineIsApp(cliConfig)\n\n const workDir = (await this.getProjectRoot()).directory\n\n const output = this.output\n\n const autoUpdatesEnabled = shouldAutoUpdate({cliConfig, flags, output})\n\n const summarize = startBuildSummary({cliConfig, isApp})\n const buildFunc = isApp ? buildApp : buildStudio\n const {mfManifest} = await buildFunc({\n autoUpdatesEnabled,\n cliConfig,\n flags,\n outDir: this.args.outputDir,\n output,\n workDir,\n })\n\n // A Dashboard build without a manifest stopped at the version mismatch prompt.\n if (summarize && mfManifest) output.log(await summarize())\n }\n}\n"],"names":["Args","Flags","SanityCommand","startBuildSummary","buildApp","buildStudio","shouldAutoUpdate","determineIsApp","BuildCommand","args","outputDir","directory","description","examples","flags","boolean","allowNo","minify","default","stats","yes","char","run","cliConfig","getCliConfig","parse","isApp","workDir","getProjectRoot","output","autoUpdatesEnabled","summarize","buildFunc","mfManifest","outDir","log"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,iBAAiB,QAAO,8BAA6B;AAE7D,SAAQC,QAAQ,QAAO,+BAA8B;AACrD,SAAQC,WAAW,QAAO,kCAAiC;AAC3D,SAAQC,gBAAgB,QAAO,uCAAsC;AACrE,SAAQC,cAAc,QAAO,4BAA2B;AAExD,OAAO,MAAMC,qBAAqBN;IAChC,OAAgB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';
4
4
  import { confirm } from '@sanity/cli-core/ux';
5
5
  import { getWorkbench, resolveWorkbenchConfig } from '@sanity/workbench-cli/deploy';
6
6
  import { deployApp } from '../actions/deploy/deployApp.js';
7
+ import { deployDashboardConfig } from '../actions/deploy/deployDashboardConfig.js';
7
8
  import { deployDebug } from '../actions/deploy/deployDebug.js';
8
9
  import { deployStudio } from '../actions/deploy/deployStudio.js';
9
10
  import { getAppId } from '../util/appId.js';
@@ -133,11 +134,12 @@ export class DeployCommand extends SanityCommand {
133
134
  const cliConfig = await this.getCliConfig();
134
135
  const projectRoot = await this.getProjectRoot();
135
136
  const isApp = determineIsApp(cliConfig);
137
+ const config = resolveWorkbenchConfig(cliConfig);
136
138
  // `--media-library-id` only steers the aspect-document sync of a Media
137
139
  // Library config deploy (see deployApp); studio and app deploys never read
138
140
  // it. Warned rather than silently dropped (same courtesy init gives
139
141
  // --dashboard on the media template).
140
- if (flags['media-library-id'] && !resolveWorkbenchConfig(cliConfig)) {
142
+ if (flags['media-library-id'] && config?.appType !== 'media-library') {
141
143
  this.output.warn('--media-library-id is ignored — it only applies when deploying a Media Library config');
142
144
  }
143
145
  if (flags.create) {
@@ -147,7 +149,7 @@ export class DeployCommand extends SanityCommand {
147
149
  if (getAppId(cliConfig)) {
148
150
  return this.output.error('--create cannot be used with a configured app ID. Omit --create to deploy to that app, or remove deployment.appId and app.id to create a new one.');
149
151
  }
150
- if (getWorkbench(cliConfig) || resolveWorkbenchConfig(cliConfig)) {
152
+ if (getWorkbench(cliConfig) || config) {
151
153
  return this.output.error('--create is not supported for this app configuration. Omit --create and run sanity deploy.');
152
154
  }
153
155
  }
@@ -179,7 +181,17 @@ export class DeployCommand extends SanityCommand {
179
181
  ...flags,
180
182
  yes: true
181
183
  } : flags;
182
- if (isApp) {
184
+ if (config?.appType === 'dashboard') {
185
+ deployDebug('Deploying dashboard configuration');
186
+ await deployDashboardConfig({
187
+ cliConfig,
188
+ config,
189
+ flags: deployFlags,
190
+ output: this.output,
191
+ projectRoot,
192
+ sourceDir
193
+ });
194
+ } else if (isApp) {
183
195
  deployDebug('Deploying app');
184
196
  await deployApp({
185
197
  cliConfig,
@@ -1 +1 @@
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'\nimport {getWorkbench, resolveWorkbenchConfig} from '@sanity/workbench-cli/deploy'\n\nimport {deployApp} from '../actions/deploy/deployApp.js'\nimport {deployDebug} from '../actions/deploy/deployDebug.js'\nimport {deployStudio} from '../actions/deploy/deployStudio.js'\nimport {getAppId} from '../util/appId.js'\nimport {determineIsApp} from '../util/determineIsApp.js'\nimport {dirIsEmptyOrNonExistent} from '../util/dirIsEmptyOrNonExistent.js'\nimport {defineCommandTelemetry} from '../util/telemetry/commandTelemetry.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 enableJsonFlag = true\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 command: '<%= config.bin %> <%= command.id %> --external --url https://apps.example.com',\n description: 'Register an externally hosted studio, served from the provided origin',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --create --title \"My App\" --yes --json',\n description:\n 'Create and deploy an App SDK app without prompts. Save application.id as deployment.appId, then omit --create on later deploys',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --create --title \"My App\" --dry-run --json',\n description: 'Preview a new App SDK deployment without creating or uploading anything',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --url my-studio --yes',\n description: 'Deploy a studio without prompts using its hostname',\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 create: Flags.boolean({\n description: 'Create a new App SDK app, even if the organization has other apps',\n exclusive: ['external', 'url'],\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'],\n }),\n json: Flags.boolean({\n char: 'j',\n default: false,\n description: 'Output the result as JSON',\n }),\n 'media-library-id': Flags.string({\n description:\n 'For a Media Library config deploy: the media library to sync the aspect definitions to. Defaults to the single active library of the configured organization; required when the organization has several',\n // Part of the beta config-app flow, like the hidden media commands it\n // pairs with. A help-listed flag is hard to take back — unhide at GA.\n hidden: true,\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, use --create to select creation when the organization already has apps',\n }),\n url: Flags.string({\n description:\n 'Studio URL for deployment. For external deploys, 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 static telemetry = defineCommandTelemetry(this.flags, {redact: ['title', 'url']})\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 // `--media-library-id` only steers the aspect-document sync of a Media\n // Library config deploy (see deployApp); studio and app deploys never read\n // it. Warned rather than silently dropped (same courtesy init gives\n // --dashboard on the media template).\n if (flags['media-library-id'] && !resolveWorkbenchConfig(cliConfig)) {\n this.output.warn(\n '--media-library-id is ignored — it only applies when deploying a Media Library config',\n )\n }\n\n if (flags.create) {\n if (!isApp) {\n return this.output.error(\n '--create is only supported for App SDK apps. For a studio, use --url <hostname>.',\n )\n }\n if (getAppId(cliConfig)) {\n return this.output.error(\n '--create cannot be used with a configured app ID. Omit --create to deploy to that app, or remove deployment.appId and app.id to create a new one.',\n )\n }\n if (getWorkbench(cliConfig) || resolveWorkbenchConfig(cliConfig)) {\n return this.output.error(\n '--create is not supported for this app configuration. Omit --create and run sanity deploy.',\n )\n }\n }\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","getWorkbench","resolveWorkbenchConfig","deployApp","deployDebug","deployStudio","getAppId","determineIsApp","dirIsEmptyOrNonExistent","defineCommandTelemetry","DeployCommand","args","sourceDir","directory","description","enableJsonFlag","examples","command","flags","boolean","allowNo","deprecated","build","default","create","exclusive","external","json","char","string","hidden","minify","title","url","verbose","yes","telemetry","redact","run","parse","cliConfig","getCliConfig","projectRoot","getProjectRoot","isApp","output","warn","error","defaultOutputDir","resolve","join","process","cwd","relativeOutput","relative","isUnattended","isEmpty","shouldProceed","message","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;AAC3C,SAAQC,YAAY,EAAEC,sBAAsB,QAAO,+BAA8B;AAEjF,SAAQC,SAAS,QAAO,iCAAgC;AACxD,SAAQC,WAAW,QAAO,mCAAkC;AAC5D,SAAQC,YAAY,QAAO,oCAAmC;AAC9D,SAAQC,QAAQ,QAAO,mBAAkB;AACzC,SAAQC,cAAc,QAAO,4BAA2B;AACxD,SAAQC,uBAAuB,QAAO,qCAAoC;AAC1E,SAAQC,sBAAsB,QAAO,wCAAuC;AAE5E,OAAO,MAAMC,sBAAsBX;IACjC,OAAgBY,OAAO;QACrBC,WAAWhB,KAAKiB,SAAS,CAAC;YACxBC,aAAa;QACf;IACF,EAAC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AAS,IAAI,IAAI,CAACD,IAAI,CAACC,SAAS,KAAK,UAAU,CAACM,MAAMQ,QAAQ,EAAE;YAC5E,IAAI2B,iBAAiB1D,KAAK2D,QAAQ,CAACH,QAAQC,GAAG,IAAIxC;YAClD,IAAIyC,cAAc,CAAC,EAAE,KAAK,KAAK;gBAC7BA,iBAAiB,CAAC,EAAE,EAAEA,gBAAgB;YACxC;YAEA,IAAI,CAAC,IAAI,CAACE,YAAY,MAAM,CAACrC,KAAK,CAAC,UAAU,EAAE;gBAC7C,MAAMsC,UAAU,MAAMhD,wBAAwBI;gBAC9C,MAAM6C,gBACJD,WACC,MAAMxD,QAAQ;oBACbuB,SAAS;oBACTmC,SAAS,CAAC,CAAC,EAAEL,eAAe,uCAAuC,CAAC;gBACtE;gBAEF,IAAI,CAACI,eAAe;oBAClB,IAAI,CAACZ,MAAM,CAACE,KAAK,CAAC,cAAc;wBAACY,MAAM7D,UAAU8D,aAAa;oBAAA;gBAChE;YACF;YAEA,6CAA6C;YAC7C,IAAI,CAAC1C,MAAMS,IAAI,EAAE,IAAI,CAACkB,MAAM,CAACgB,GAAG,CAAC,CAAC,YAAY,EAAER,eAAe,EAAE,CAAC;QACpE;QAEA,8FAA8F;QAC9F,MAAMS,cAAc,IAAI,CAACP,YAAY,MAAMrC,KAAK,CAAC,UAAU,GAAG;YAAC,GAAGA,KAAK;YAAEiB,KAAK;QAAI,IAAIjB;QAEtF,IAAI0B,OAAO;YACTxC,YAAY;YACZ,MAAMD,UAAU;gBACdqC;gBACAtB,OAAO4C;gBACPjB,QAAQ,IAAI,CAACA,MAAM;gBACnBH;gBACA9B;YACF;QACF,OAAO;YACLR,YAAY;YACZ,MAAMC,aAAa;gBACjBmC;gBACAtB,OAAO4C;gBACPjB,QAAQ,IAAI,CAACA,MAAM;gBACnBH;gBACA9B;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'\nimport {getWorkbench, resolveWorkbenchConfig} from '@sanity/workbench-cli/deploy'\n\nimport {deployApp} from '../actions/deploy/deployApp.js'\nimport {deployDashboardConfig} from '../actions/deploy/deployDashboardConfig.js'\nimport {deployDebug} from '../actions/deploy/deployDebug.js'\nimport {deployStudio} from '../actions/deploy/deployStudio.js'\nimport {getAppId} from '../util/appId.js'\nimport {determineIsApp} from '../util/determineIsApp.js'\nimport {dirIsEmptyOrNonExistent} from '../util/dirIsEmptyOrNonExistent.js'\nimport {defineCommandTelemetry} from '../util/telemetry/commandTelemetry.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 enableJsonFlag = true\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 command: '<%= config.bin %> <%= command.id %> --external --url https://apps.example.com',\n description: 'Register an externally hosted studio, served from the provided origin',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --create --title \"My App\" --yes --json',\n description:\n 'Create and deploy an App SDK app without prompts. Save application.id as deployment.appId, then omit --create on later deploys',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --create --title \"My App\" --dry-run --json',\n description: 'Preview a new App SDK deployment without creating or uploading anything',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --url my-studio --yes',\n description: 'Deploy a studio without prompts using its hostname',\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 create: Flags.boolean({\n description: 'Create a new App SDK app, even if the organization has other apps',\n exclusive: ['external', 'url'],\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'],\n }),\n json: Flags.boolean({\n char: 'j',\n default: false,\n description: 'Output the result as JSON',\n }),\n 'media-library-id': Flags.string({\n description:\n 'For a Media Library config deploy: the media library to sync the aspect definitions to. Defaults to the single active library of the configured organization; required when the organization has several',\n // Part of the beta config-app flow, like the hidden media commands it\n // pairs with. A help-listed flag is hard to take back — unhide at GA.\n hidden: true,\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, use --create to select creation when the organization already has apps',\n }),\n url: Flags.string({\n description:\n 'Studio URL for deployment. For external deploys, 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 static telemetry = defineCommandTelemetry(this.flags, {redact: ['title', 'url']})\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 const config = resolveWorkbenchConfig(cliConfig)\n\n // `--media-library-id` only steers the aspect-document sync of a Media\n // Library config deploy (see deployApp); studio and app deploys never read\n // it. Warned rather than silently dropped (same courtesy init gives\n // --dashboard on the media template).\n if (flags['media-library-id'] && config?.appType !== 'media-library') {\n this.output.warn(\n '--media-library-id is ignored — it only applies when deploying a Media Library config',\n )\n }\n\n if (flags.create) {\n if (!isApp) {\n return this.output.error(\n '--create is only supported for App SDK apps. For a studio, use --url <hostname>.',\n )\n }\n if (getAppId(cliConfig)) {\n return this.output.error(\n '--create cannot be used with a configured app ID. Omit --create to deploy to that app, or remove deployment.appId and app.id to create a new one.',\n )\n }\n if (getWorkbench(cliConfig) || config) {\n return this.output.error(\n '--create is not supported for this app configuration. Omit --create and run sanity deploy.',\n )\n }\n }\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 (config?.appType === 'dashboard') {\n deployDebug('Deploying dashboard configuration')\n await deployDashboardConfig({\n cliConfig,\n config,\n flags: deployFlags,\n output: this.output,\n projectRoot,\n sourceDir,\n })\n } else 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","getWorkbench","resolveWorkbenchConfig","deployApp","deployDashboardConfig","deployDebug","deployStudio","getAppId","determineIsApp","dirIsEmptyOrNonExistent","defineCommandTelemetry","DeployCommand","args","sourceDir","directory","description","enableJsonFlag","examples","command","flags","boolean","allowNo","deprecated","build","default","create","exclusive","external","json","char","string","hidden","minify","title","url","verbose","yes","telemetry","redact","run","parse","cliConfig","getCliConfig","projectRoot","getProjectRoot","isApp","config","appType","output","warn","error","defaultOutputDir","resolve","join","process","cwd","relativeOutput","relative","isUnattended","isEmpty","shouldProceed","message","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;AAC3C,SAAQC,YAAY,EAAEC,sBAAsB,QAAO,+BAA8B;AAEjF,SAAQC,SAAS,QAAO,iCAAgC;AACxD,SAAQC,qBAAqB,QAAO,6CAA4C;AAChF,SAAQC,WAAW,QAAO,mCAAkC;AAC5D,SAAQC,YAAY,QAAO,oCAAmC;AAC9D,SAAQC,QAAQ,QAAO,mBAAkB;AACzC,SAAQC,cAAc,QAAO,4BAA2B;AACxD,SAAQC,uBAAuB,QAAO,qCAAoC;AAC1E,SAAQC,sBAAsB,QAAO,wCAAuC;AAE5E,OAAO,MAAMC,sBAAsBZ;IACjC,OAAgBa,OAAO;QACrBC,WAAWjB,KAAKkB,SAAS,CAA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;QACF,OAAO;YACLR,YAAY;YACZ,MAAMC,aAAa;gBACjBmC;gBACAtB,OAAO8C;gBACPjB,QAAQ,IAAI,CAACA,MAAM;gBACnBL;gBACA9B;YACF;QACF;IACF;AACF"}
@@ -2,8 +2,9 @@ import { Args, Flags } from '@oclif/core';
2
2
  import { colorizeJson, exitCodes, getProjectCliClient, SanityCommand, subdebug } from '@sanity/cli-core';
3
3
  import { getCliExecutionContext } from '@sanity/cli-core/executionContext';
4
4
  import { DOCUMENTS_API_VERSION } from '../../actions/documents/constants.js';
5
+ import { resolveCommandTarget } from '../../actions/targets/resolveCommandTarget.js';
5
6
  import { promptForProject } from '../../prompts/promptForProject.js';
6
- import { getDatasetFlag, getProjectIdFlag } from '../../util/sharedFlags.js';
7
+ import { getDatasetFlag, getProjectIdFlag, getWithBlueprintsFlag } from '../../util/sharedFlags.js';
7
8
  const queryDocumentDebug = subdebug('documents:query');
8
9
  export class QueryDocumentCommand extends SanityCommand {
9
10
  static args = {
@@ -40,6 +41,7 @@ export class QueryDocumentCommand extends SanityCommand {
40
41
  description: 'Dataset to query',
41
42
  semantics: 'override'
42
43
  }),
44
+ ...getWithBlueprintsFlag(),
43
45
  anonymous: Flags.boolean({
44
46
  default: false,
45
47
  description: 'Send the query without any authorization token'
@@ -59,17 +61,14 @@ export class QueryDocumentCommand extends SanityCommand {
59
61
  const { args, flags } = await this.parse(QueryDocumentCommand);
60
62
  const { query } = args;
61
63
  const { anonymous, 'api-version': apiVersion, dataset, pretty } = flags;
62
- const cliConfig = await this.tryGetCliConfig();
63
- const projectId = await this.getProjectId({
64
- fallback: ()=>promptForProject({})
65
- });
64
+ const { dataset: targetDataset, projectId } = flags['with-blueprints'] ? await resolveCommandTarget({
65
+ dataset,
66
+ loadCliConfig: ()=>this.tryGetCliConfig(),
67
+ needsDataset: true,
68
+ project: flags.project,
69
+ unattended: this.isUnattended()
70
+ }) : await this.resolveClassicTarget(dataset);
66
71
  const requireUser = !anonymous;
67
- if (!cliConfig.api?.dataset && !dataset) {
68
- this.error('Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.', {
69
- exit: exitCodes.USAGE_ERROR
70
- });
71
- }
72
- const targetDataset = dataset || cliConfig.api?.dataset;
73
72
  const configuredApiVersion = apiVersion ?? (getCliExecutionContext() ? undefined : process.env.SANITY_CLI_QUERY_API_VERSION);
74
73
  const targetApiVersion = configuredApiVersion || DOCUMENTS_API_VERSION;
75
74
  if (!configuredApiVersion) {
@@ -104,6 +103,22 @@ export class QueryDocumentCommand extends SanityCommand {
104
103
  });
105
104
  }
106
105
  }
106
+ async resolveClassicTarget(datasetFlag) {
107
+ const cliConfig = await this.tryGetCliConfig();
108
+ const projectId = await this.getProjectId({
109
+ fallback: ()=>promptForProject({})
110
+ });
111
+ const dataset = datasetFlag || cliConfig.api?.dataset;
112
+ if (!dataset) {
113
+ this.error('Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.', {
114
+ exit: exitCodes.USAGE_ERROR
115
+ });
116
+ }
117
+ return {
118
+ dataset,
119
+ projectId
120
+ };
121
+ }
107
122
  }
108
123
 
109
124
  //# sourceMappingURL=query.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/documents/query.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {\n colorizeJson,\n exitCodes,\n getProjectCliClient,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\nimport {getCliExecutionContext} from '@sanity/cli-core/executionContext'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst queryDocumentDebug = subdebug('documents:query')\n\nexport class QueryDocumentCommand extends SanityCommand<typeof QueryDocumentCommand> {\n static override args = {\n query: Args.string({\n description: 'GROQ query to run against the dataset',\n required: true,\n }),\n }\n\n static override description = 'Query for documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"][0..4]\\'',\n description: 'Fetch 5 documents of type \"movie\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"]|order(releaseDate asc)[0]{title}\\' --dataset staging',\n description: 'Fetch title of the oldest movie in the dataset named \"staging\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_id == \"header\"] { \"headerText\": pt::text(body) }\\' --api-version v2021-06-07',\n description: 'Use API version v2021-06-07 and do a query',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"post\"]\\' --project abc123 --dataset production',\n description: 'Query documents in a specific project and dataset',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to query', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to query', semantics: 'override'}),\n anonymous: Flags.boolean({\n default: false,\n description: 'Send the query without any authorization token',\n }),\n 'api-version': Flags.string({\n description: `API version to use (defaults to ${DOCUMENTS_API_VERSION})`,\n }),\n pretty: Flags.boolean({\n default: false,\n description: 'Colorize JSON output',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:query']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(QueryDocumentCommand)\n const {query} = args\n const {anonymous, 'api-version': apiVersion, dataset, pretty} = flags\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({\n fallback: () => promptForProject({}),\n })\n\n const requireUser = !anonymous\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n const configuredApiVersion =\n apiVersion ??\n (getCliExecutionContext() ? undefined : process.env.SANITY_CLI_QUERY_API_VERSION)\n const targetApiVersion = configuredApiVersion || DOCUMENTS_API_VERSION\n\n if (!configuredApiVersion) {\n this.warn(`--api-version not specified, using \\`${DOCUMENTS_API_VERSION}\\``)\n }\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: targetApiVersion,\n dataset: targetDataset,\n projectId,\n requireUser,\n })\n\n const docs = await projectClient.fetch(query)\n\n if (!docs) {\n this.error('Query returned no results', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n // Output the query results\n if (pretty) {\n this.log(colorizeJson(docs))\n } else {\n this.log(JSON.stringify(docs, null, 2))\n }\n } catch (error) {\n const err = error as Error\n\n queryDocumentDebug(`Error running query: ${query}`, err)\n\n // Provide more context in error messages\n const errorMsg = err.message.toLowerCase().includes('syntax')\n ? `Invalid GROQ query syntax: ${err.message}`\n : `Failed to run query: ${err.message}`\n\n this.error(`${errorMsg}\\nQuery: ${query}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Args","Flags","colorizeJson","exitCodes","getProjectCliClient","SanityCommand","subdebug","getCliExecutionContext","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","queryDocumentDebug","QueryDocumentCommand","args","query","string","description","required","examples","command","flags","semantics","anonymous","boolean","default","pretty","hiddenAliases","run","parse","apiVersion","dataset","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","requireUser","api","error","exit","USAGE_ERROR","targetDataset","configuredApiVersion","undefined","process","env","SANITY_CLI_QUERY_API_VERSION","targetApiVersion","warn","projectClient","docs","fetch","RUNTIME_ERROR","log","JSON","stringify","err","errorMsg","message","toLowerCase","includes"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SACEC,YAAY,EACZC,SAAS,EACTC,mBAAmB,EACnBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,sBAAsB,QAAO,oCAAmC;AAExE,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,qBAAqBN,SAAS;AAEpC,OAAO,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AW;YAAA;QAEhC;QAEA,MAAMC,gBAAgBX,WAAWC,UAAUM,GAAG,EAAEP;QAChD,MAAMY,uBACJb,cACCvB,CAAAA,2BAA2BqC,YAAYC,QAAQC,GAAG,CAACC,4BAA4B,AAAD;QACjF,MAAMC,mBAAmBL,wBAAwBnC;QAEjD,IAAI,CAACmC,sBAAsB;YACzB,IAAI,CAACM,IAAI,CAAC,CAAC,qCAAqC,EAAEzC,sBAAsB,EAAE,CAAC;QAC7E;QAEA,IAAI;YACF,MAAM0C,gBAAgB,MAAM9C,oBAAoB;gBAC9C0B,YAAYkB;gBACZjB,SAASW;gBACTR;gBACAG;YACF;YAEA,MAAMc,OAAO,MAAMD,cAAcE,KAAK,CAACrC;YAEvC,IAAI,CAACoC,MAAM;gBACT,IAAI,CAACZ,KAAK,CAAC,6BAA6B;oBAACC,MAAMrC,UAAUkD,aAAa;gBAAA;YACxE;YAEA,2BAA2B;YAC3B,IAAI3B,QAAQ;gBACV,IAAI,CAAC4B,GAAG,CAACpD,aAAaiD;YACxB,OAAO;gBACL,IAAI,CAACG,GAAG,CAACC,KAAKC,SAAS,CAACL,MAAM,MAAM;YACtC;QACF,EAAE,OAAOZ,OAAO;YACd,MAAMkB,MAAMlB;YAEZ3B,mBAAmB,CAAC,qBAAqB,EAAEG,OAAO,EAAE0C;YAEpD,yCAAyC;YACzC,MAAMC,WAAWD,IAAIE,OAAO,CAACC,WAAW,GAAGC,QAAQ,CAAC,YAChD,CAAC,2BAA2B,EAAEJ,IAAIE,OAAO,EAAE,GAC3C,CAAC,qBAAqB,EAAEF,IAAIE,OAAO,EAAE;YAEzC,IAAI,CAACpB,KAAK,CAAC,GAAGmB,SAAS,SAAS,EAAE3C,OAAO,EAAE;gBAACyB,MAAMrC,UAAUkD,aAAa;YAAA;QAC3E;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/documents/query.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {\n colorizeJson,\n exitCodes,\n getProjectCliClient,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\nimport {getCliExecutionContext} from '@sanity/cli-core/executionContext'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {resolveCommandTarget} from '../../actions/targets/resolveCommandTarget.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag, getWithBlueprintsFlag} from '../../util/sharedFlags.js'\n\nconst queryDocumentDebug = subdebug('documents:query')\n\nexport class QueryDocumentCommand extends SanityCommand<typeof QueryDocumentCommand> {\n static override args = {\n query: Args.string({\n description: 'GROQ query to run against the dataset',\n required: true,\n }),\n }\n\n static override description = 'Query for documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"][0..4]\\'',\n description: 'Fetch 5 documents of type \"movie\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"]|order(releaseDate asc)[0]{title}\\' --dataset staging',\n description: 'Fetch title of the oldest movie in the dataset named \"staging\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_id == \"header\"] { \"headerText\": pt::text(body) }\\' --api-version v2021-06-07',\n description: 'Use API version v2021-06-07 and do a query',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"post\"]\\' --project abc123 --dataset production',\n description: 'Query documents in a specific project and dataset',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to query', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to query', semantics: 'override'}),\n ...getWithBlueprintsFlag(),\n anonymous: Flags.boolean({\n default: false,\n description: 'Send the query without any authorization token',\n }),\n 'api-version': Flags.string({\n description: `API version to use (defaults to ${DOCUMENTS_API_VERSION})`,\n }),\n pretty: Flags.boolean({\n default: false,\n description: 'Colorize JSON output',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:query']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(QueryDocumentCommand)\n const {query} = args\n const {anonymous, 'api-version': apiVersion, dataset, pretty} = flags\n\n const {dataset: targetDataset, projectId} = flags['with-blueprints']\n ? await resolveCommandTarget({\n dataset,\n loadCliConfig: () => this.tryGetCliConfig(),\n needsDataset: true,\n project: flags.project,\n unattended: this.isUnattended(),\n })\n : await this.resolveClassicTarget(dataset)\n\n const requireUser = !anonymous\n\n const configuredApiVersion =\n apiVersion ??\n (getCliExecutionContext() ? undefined : process.env.SANITY_CLI_QUERY_API_VERSION)\n const targetApiVersion = configuredApiVersion || DOCUMENTS_API_VERSION\n\n if (!configuredApiVersion) {\n this.warn(`--api-version not specified, using \\`${DOCUMENTS_API_VERSION}\\``)\n }\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: targetApiVersion,\n dataset: targetDataset,\n projectId,\n requireUser,\n })\n\n const docs = await projectClient.fetch(query)\n\n if (!docs) {\n this.error('Query returned no results', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n // Output the query results\n if (pretty) {\n this.log(colorizeJson(docs))\n } else {\n this.log(JSON.stringify(docs, null, 2))\n }\n } catch (error) {\n const err = error as Error\n\n queryDocumentDebug(`Error running query: ${query}`, err)\n\n // Provide more context in error messages\n const errorMsg = err.message.toLowerCase().includes('syntax')\n ? `Invalid GROQ query syntax: ${err.message}`\n : `Failed to run query: ${err.message}`\n\n this.error(`${errorMsg}\\nQuery: ${query}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n private async resolveClassicTarget(datasetFlag?: string) {\n const cliConfig = await this.tryGetCliConfig()\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\n const dataset = datasetFlag || cliConfig.api?.dataset\n\n if (!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 return {dataset, projectId}\n }\n}\n"],"names":["Args","Flags","colorizeJson","exitCodes","getProjectCliClient","SanityCommand","subdebug","getCliExecutionContext","DOCUMENTS_API_VERSION","resolveCommandTarget","promptForProject","getDatasetFlag","getProjectIdFlag","getWithBlueprintsFlag","queryDocumentDebug","QueryDocumentCommand","args","query","string","description","required","examples","command","flags","semantics","anonymous","boolean","default","pretty","hiddenAliases","run","parse","apiVersion","dataset","targetDataset","projectId","loadCliConfig","tryGetCliConfig","needsDataset","project","unattended","isUnattended","resolveClassicTarget","requireUser","configuredApiVersion","undefined","process","env","SANITY_CLI_QUERY_API_VERSION","targetApiVersion","warn","projectClient","docs","fetch","error","exit","RUNTIME_ERROR","log","JSON","stringify","err","errorMsg","message","toLowerCase","includes","datasetFlag","cliConfig","getProjectId","fallback","api","USAGE_ERROR"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SACEC,YAAY,EACZC,SAAS,EACTC,mBAAmB,EACnBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,sBAAsB,QAAO,oCAAmC;AAExE,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,oBAAoB,QAAO,gDAA+C;AAClF,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,EAAEC,qBAAqB,QAAO,4BAA2B;AAEjG,MAAMC,qBAAqBR,SAAS;AAEpC,OAAO,MAAMS,6BAA6BV;IACxC,OAAgBW,OAAO;QACrBC,OAAOjB,KAAKkB,MAAM,CAAC;YACjBC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,sBAAqB;IAEnD,OAAgBE,WAAW;QACzB;YACEC,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SACE;YACFH,aAAa;QACf;QACA;YACEG,SACE;YACFH,aAAa;QACf;QACA;YACEG,SACE;YACFH,aAAa;QACf;KACD,CAAA;IAED,OAAgBI,QAAQ;QACtB,GAAGX,iBAAiB;YAACO,aAAa;YAAuBK,WAAW;QAAU,EAAE;QAChF,GAAGb,eAAe;YAACQ,aAAa;YAAoBK,WAAW;QA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,MAAM;gBACT,IAAI,CAACE,KAAK,CAAC,6BAA6B;oBAACC,MAAMpD,UAAUqD,aAAa;gBAAA;YACxE;YAEA,2BAA2B;YAC3B,IAAI5B,QAAQ;gBACV,IAAI,CAAC6B,GAAG,CAACvD,aAAakD;YACxB,OAAO;gBACL,IAAI,CAACK,GAAG,CAACC,KAAKC,SAAS,CAACP,MAAM,MAAM;YACtC;QACF,EAAE,OAAOE,OAAO;YACd,MAAMM,MAAMN;YAEZxC,mBAAmB,CAAC,qBAAqB,EAAEG,OAAO,EAAE2C;YAEpD,yCAAyC;YACzC,MAAMC,WAAWD,IAAIE,OAAO,CAACC,WAAW,GAAGC,QAAQ,CAAC,YAChD,CAAC,2BAA2B,EAAEJ,IAAIE,OAAO,EAAE,GAC3C,CAAC,qBAAqB,EAAEF,IAAIE,OAAO,EAAE;YAEzC,IAAI,CAACR,KAAK,CAAC,GAAGO,SAAS,SAAS,EAAE5C,OAAO,EAAE;gBAACsC,MAAMpD,UAAUqD,aAAa;YAAA;QAC3E;IACF;IAEA,MAAcd,qBAAqBuB,WAAoB,EAAE;QACvD,MAAMC,YAAY,MAAM,IAAI,CAAC7B,eAAe;QAC5C,MAAMF,YAAY,MAAM,IAAI,CAACgC,YAAY,CAAC;YAACC,UAAU,IAAM1D,iBAAiB,CAAC;QAAE;QAC/E,MAAMuB,UAAUgC,eAAeC,UAAUG,GAAG,EAAEpC;QAE9C,IAAI,CAACA,SAAS;YACZ,IAAI,CAACqB,KAAK,CACR,4FACA;gBAACC,MAAMpD,UAAUmE,WAAW;YAAA;QAEhC;QAEA,OAAO;YAACrC;YAASE;QAAS;IAC5B;AACF"}
@@ -73,7 +73,7 @@ const NOT_A_CONFIG_APP = 'This command must be run inside a Media Library config
73
73
  throw err;
74
74
  }
75
75
  const config = resolveWorkbenchConfig(cliConfig);
76
- if (!config) {
76
+ if (config?.appType !== 'media-library') {
77
77
  this.error(NOT_A_CONFIG_APP, {
78
78
  exit: exitCodes.RUNTIME_ERROR
79
79
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/media/prune-aspect-data.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {\n type CliConfig,\n exitCodes,\n ProjectRootNotFoundError,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\nimport {resolveWorkbenchConfig} from '@sanity/workbench-cli/deploy'\n\nimport {VALID_ASPECT_NAME} from '../../actions/media/aspectName.js'\nimport {resolveMediaLibraryId} from '../../actions/media/resolveMediaLibraryId.js'\nimport {\n getAspectDataCarrierIds,\n getStoredAspectIds,\n unsetAspectData,\n} from '../../services/mediaLibraries.js'\nimport {pluralize} from '../../util/pluralize.js'\n\nconst pruneAspectDataDebug = subdebug('media:prune-aspect-data')\n\nconst NOT_A_CONFIG_APP =\n 'This command must be run inside a Media Library config app — a project whose ' +\n '`sanity.cli.ts` declares `unstable_defineMediaLibrary(...)`. Scaffold one with ' +\n '`sanity init --template media-library-config`.'\n\n/** Unset-patch batch size per mutate request. */\nconst BATCH_SIZE = 100\n\n/** How many carrier ids the report lists before truncating. */\nconst SAMPLE_SIZE = 10\n\n/**\n * The deliberate, explicitly-invoked counterpart to the deploy-time aspect\n * sync: deploying a config only mirrors aspect *definitions* — `aspects.<name>`\n * values on assets are never touched and resurface if a matching field comes\n * back. This command removes that data. Irreversible fan-out mutation, so it\n * never asks for confirmation: without `--yes` it only reports what would change.\n */\nexport class MediaPruneAspectDataCommand extends SanityCommand<typeof MediaPruneAspectDataCommand> {\n static override args = {\n aspectName: Args.string({\n description: 'Name of the aspect whose data to remove from all assets',\n required: true,\n }),\n }\n\n static override description =\n \"Irreversibly remove an aspect's data (aspects.<name> values) from every asset of a media library\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> legacyAspect',\n description: 'Report which assets carry aspects.legacyAspect (changes nothing)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> legacyAspect --yes',\n description: 'Remove aspects.legacyAspect from every asset that carries it',\n },\n ]\n\n static override flags = {\n 'media-library-id': Flags.string({\n description:\n 'The id of the media library to prune (defaults to the single active library of the configured organization)',\n }),\n yes: Flags.boolean({\n char: 'y',\n description:\n 'Execute the prune. Without this flag the command only reports what would change',\n }),\n }\n\n // Part of the beta config-app flow: the command requires a config app to\n // resolve its organization, so listing it in the general help would only\n // route legacy-flow users into the beta paradigm. The prune itself is\n // paradigm-neutral (it only unsets asset data) — when there is demand from\n // the legacy flow, ungate it from the config app and unhide it.\n static override hidden = true\n\n public async run(): Promise<void> {\n const {aspectName} = this.args\n const {'media-library-id': mediaLibraryIdFlag, yes = false} = this.flags\n\n // The name rule shared with the sync contract; also makes the\n // interpolation into the carrier GROQ filter injection-safe.\n if (!VALID_ASPECT_NAME.test(aspectName)) {\n this.error(`\"${aspectName}\" is not a valid aspect name (${VALID_ASPECT_NAME})`, {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n let cliConfig: CliConfig\n try {\n cliConfig = await this.getCliConfig()\n } catch (err) {\n if (err instanceof ProjectRootNotFoundError) {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n throw err\n }\n\n const config = resolveWorkbenchConfig(cliConfig)\n if (!config) {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n try {\n // Not `isUnattended()`: that treats `--yes` as unattended, but here\n // `--yes` consents to the prune, not to skipping prompts — the report\n // path literally instructs \"Re-run with --yes\", and that run must still\n // offer the library picker in a multi-library organization. Only a\n // genuinely non-interactive run (CI, piped stdin) must not prompt.\n const mediaLibraryId = await resolveMediaLibraryId({\n mediaLibraryIdFlag,\n organizationId: config.organizationId,\n unattended: !this.resolveIsInteractive(),\n })\n\n const spin = spinner('Finding assets that carry the aspect').start()\n let storedIds: string[]\n let carriers: string[]\n try {\n storedIds = await getStoredAspectIds(mediaLibraryId, 'prune-aspect-data')\n carriers = await getAspectDataCarrierIds(mediaLibraryId, aspectName)\n } finally {\n // Also on failure — a spinner left running garbles the error output.\n spin.stop()\n }\n\n // Guardrails, not gates: pruning while either is true can be deliberate\n // (e.g. clearing data before re-shaping a field), so warn and continue.\n if (config.fields.some((field) => field.name === aspectName)) {\n this.warn(\n `\"${aspectName}\" is still declared in sanity.cli.ts — its data is likely in active use and will grow back.`,\n )\n }\n if (storedIds.includes(aspectName)) {\n this.warn(\n `Aspect definition \"${aspectName}\" still exists in the library — this only removes data, not the definition.`,\n )\n }\n\n if (carriers.length === 0) {\n this.log(\n `No assets in media library ${styleText('bold', mediaLibraryId)} carry ${styleText(\n 'bold',\n `aspects.${aspectName}`,\n )} — nothing to prune.`,\n )\n return\n }\n\n const sample = carriers.slice(0, SAMPLE_SIZE)\n // \"documents\", not \"assets\": under the raw perspective drafts and\n // release versions are separate ids, so an asset count would overstate.\n this.log(\n `${styleText('bold', String(carriers.length))} ${pluralize(\n 'document',\n carriers.length,\n )} in media library ${styleText('bold', mediaLibraryId)} ${\n carriers.length === 1 ? 'carries' : 'carry'\n } ${styleText('bold', `aspects.${aspectName}`)}:`,\n )\n for (const id of sample) {\n this.log(` - ${id}`)\n }\n if (carriers.length > sample.length) {\n this.log(styleText('dim', ` … and ${carriers.length - sample.length} more`))\n }\n\n if (!yes) {\n this.log('')\n this.log(\n `This would ${styleText(\n 'bold',\n 'irreversibly',\n )} unset aspects.${aspectName} on all of them. Re-run with ${styleText(\n 'bold',\n '--yes',\n )} to execute.`,\n )\n return\n }\n\n let pruned = 0\n for (let offset = 0; offset < carriers.length; offset += BATCH_SIZE) {\n const batch = carriers.slice(offset, offset + BATCH_SIZE)\n try {\n await unsetAspectData({aspectName, assetIds: batch, mediaLibraryId})\n } catch (batchError) {\n // The progress made so far must survive into the error: re-running\n // is safe (pruned assets no longer match the carrier query), so the\n // message says how far it got and that a retry finishes the rest.\n throw new Error(\n `Removed aspects.${aspectName} from ${pruned} of ${carriers.length} ${pluralize(\n 'document',\n carriers.length,\n )} before a batch failed: ${getErrorMessage(batchError)}\\n` +\n `Re-running the command with --yes is safe — already-pruned documents no longer ` +\n `match and only the remaining ${carriers.length - pruned} will be mutated.`,\n {cause: batchError},\n )\n }\n pruned += batch.length\n this.log(styleText('dim', ` pruned ${pruned}/${carriers.length}`))\n }\n\n this.log('')\n this.log(\n `${logSymbols.success} aspects.${aspectName} removed from ${pruned} ${pluralize(\n 'document',\n pruned,\n )}.`,\n )\n } catch (error) {\n const err = error as Error\n // Ctrl+C in the library prompt and errors that already carry their exit\n // story (`this.error`, CLIError from the resolver) pass through to\n // `SanityCommand.catch` instead of being re-wrapped here.\n if (err.name === 'ExitPromptError' || 'oclif' in err) {\n throw err\n }\n pruneAspectDataDebug('Failed to prune aspect data', {\n aspectName,\n error: err,\n })\n this.error(\n styleText('bold', 'Failed to prune aspect data') + `\\n\\n${styleText('red', err.message)}`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n }\n}\n"],"names":["styleText","Args","Flags","exitCodes","ProjectRootNotFoundError","SanityCommand","subdebug","getErrorMessage","logSymbols","spinner","resolveWorkbenchConfig","VALID_ASPECT_NAME","resolveMediaLibraryId","getAspectDataCarrierIds","getStoredAspectIds","unsetAspectData","pluralize","pruneAspectDataDebug","NOT_A_CONFIG_APP","BATCH_SIZE","SAMPLE_SIZE","MediaPruneAspectDataCommand","args","aspectName","string","description","required","examples","command","flags","yes","boolean","char","hidden","run","mediaLibraryIdFlag","test","error","exit","USAGE_ERROR","cliConfig","getCliConfig","err","RUNTIME_ERROR","config","mediaLibraryId","organizationId","unattended","resolveIsInteractive","spin","start","storedIds","carriers","stop","fields","some","field","name","warn","includes","length","log","sample","slice","String","id","pruned","offset","batch","assetIds","batchError","Error","cause","success","message"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAEEC,SAAS,EACTC,wBAAwB,EACxB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oBACF,MAAMJ,gBAAgB;wBAACQ;wBAAY8C,UAAUD;wBAAOvB;oBAAc;gBACpE,EAAE,OAAOyB,YAAY;oBACnB,mEAAmE;oBACnE,oEAAoE;oBACpE,kEAAkE;oBAClE,MAAM,IAAIC,MACR,CAAC,gBAAgB,EAAEhD,WAAW,MAAM,EAAE2C,OAAO,IAAI,EAAEd,SAASQ,MAAM,CAAC,CAAC,EAAE5C,UACpE,YACAoC,SAASQ,MAAM,EACf,wBAAwB,EAAErD,gBAAgB+D,YAAY,EAAE,CAAC,GACzD,CAAC,+EAA+E,CAAC,GACjF,CAAC,6BAA6B,EAAElB,SAASQ,MAAM,GAAGM,OAAO,iBAAiB,CAAC,EAC7E;wBAACM,OAAOF;oBAAU;gBAEtB;gBACAJ,UAAUE,MAAMR,MAAM;gBACtB,IAAI,CAACC,GAAG,CAAC7D,UAAU,OAAO,CAAC,SAAS,EAAEkE,OAAO,CAAC,EAAEd,SAASQ,MAAM,EAAE;YACnE;YAEA,IAAI,CAACC,GAAG,CAAC;YACT,IAAI,CAACA,GAAG,CACN,GAAGrD,WAAWiE,OAAO,CAAC,SAAS,EAAElD,WAAW,cAAc,EAAE2C,OAAO,CAAC,EAAElD,UACpE,YACAkD,QACA,CAAC,CAAC;QAER,EAAE,OAAO7B,OAAO;YACd,MAAMK,MAAML;YACZ,wEAAwE;YACxE,mEAAmE;YACnE,0DAA0D;YAC1D,IAAIK,IAAIe,IAAI,KAAK,qBAAqB,WAAWf,KAAK;gBACpD,MAAMA;YACR;YACAzB,qBAAqB,+BAA+B;gBAClDM;gBACAc,OAAOK;YACT;YACA,IAAI,CAACL,KAAK,CACRrC,UAAU,QAAQ,iCAAiC,CAAC,IAAI,EAAEA,UAAU,OAAO0C,IAAIgC,OAAO,GAAG,EACzF;gBAACpC,MAAMnC,UAAUwC,aAAa;YAAA;QAElC;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/media/prune-aspect-data.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {\n type CliConfig,\n exitCodes,\n ProjectRootNotFoundError,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\nimport {resolveWorkbenchConfig} from '@sanity/workbench-cli/deploy'\n\nimport {VALID_ASPECT_NAME} from '../../actions/media/aspectName.js'\nimport {resolveMediaLibraryId} from '../../actions/media/resolveMediaLibraryId.js'\nimport {\n getAspectDataCarrierIds,\n getStoredAspectIds,\n unsetAspectData,\n} from '../../services/mediaLibraries.js'\nimport {pluralize} from '../../util/pluralize.js'\n\nconst pruneAspectDataDebug = subdebug('media:prune-aspect-data')\n\nconst NOT_A_CONFIG_APP =\n 'This command must be run inside a Media Library config app — a project whose ' +\n '`sanity.cli.ts` declares `unstable_defineMediaLibrary(...)`. Scaffold one with ' +\n '`sanity init --template media-library-config`.'\n\n/** Unset-patch batch size per mutate request. */\nconst BATCH_SIZE = 100\n\n/** How many carrier ids the report lists before truncating. */\nconst SAMPLE_SIZE = 10\n\n/**\n * The deliberate, explicitly-invoked counterpart to the deploy-time aspect\n * sync: deploying a config only mirrors aspect *definitions* — `aspects.<name>`\n * values on assets are never touched and resurface if a matching field comes\n * back. This command removes that data. Irreversible fan-out mutation, so it\n * never asks for confirmation: without `--yes` it only reports what would change.\n */\nexport class MediaPruneAspectDataCommand extends SanityCommand<typeof MediaPruneAspectDataCommand> {\n static override args = {\n aspectName: Args.string({\n description: 'Name of the aspect whose data to remove from all assets',\n required: true,\n }),\n }\n\n static override description =\n \"Irreversibly remove an aspect's data (aspects.<name> values) from every asset of a media library\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> legacyAspect',\n description: 'Report which assets carry aspects.legacyAspect (changes nothing)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> legacyAspect --yes',\n description: 'Remove aspects.legacyAspect from every asset that carries it',\n },\n ]\n\n static override flags = {\n 'media-library-id': Flags.string({\n description:\n 'The id of the media library to prune (defaults to the single active library of the configured organization)',\n }),\n yes: Flags.boolean({\n char: 'y',\n description:\n 'Execute the prune. Without this flag the command only reports what would change',\n }),\n }\n\n // Part of the beta config-app flow: the command requires a config app to\n // resolve its organization, so listing it in the general help would only\n // route legacy-flow users into the beta paradigm. The prune itself is\n // paradigm-neutral (it only unsets asset data) — when there is demand from\n // the legacy flow, ungate it from the config app and unhide it.\n static override hidden = true\n\n public async run(): Promise<void> {\n const {aspectName} = this.args\n const {'media-library-id': mediaLibraryIdFlag, yes = false} = this.flags\n\n // The name rule shared with the sync contract; also makes the\n // interpolation into the carrier GROQ filter injection-safe.\n if (!VALID_ASPECT_NAME.test(aspectName)) {\n this.error(`\"${aspectName}\" is not a valid aspect name (${VALID_ASPECT_NAME})`, {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n let cliConfig: CliConfig\n try {\n cliConfig = await this.getCliConfig()\n } catch (err) {\n if (err instanceof ProjectRootNotFoundError) {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n throw err\n }\n\n const config = resolveWorkbenchConfig(cliConfig)\n if (config?.appType !== 'media-library') {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n try {\n // Not `isUnattended()`: that treats `--yes` as unattended, but here\n // `--yes` consents to the prune, not to skipping prompts — the report\n // path literally instructs \"Re-run with --yes\", and that run must still\n // offer the library picker in a multi-library organization. Only a\n // genuinely non-interactive run (CI, piped stdin) must not prompt.\n const mediaLibraryId = await resolveMediaLibraryId({\n mediaLibraryIdFlag,\n organizationId: config.organizationId,\n unattended: !this.resolveIsInteractive(),\n })\n\n const spin = spinner('Finding assets that carry the aspect').start()\n let storedIds: string[]\n let carriers: string[]\n try {\n storedIds = await getStoredAspectIds(mediaLibraryId, 'prune-aspect-data')\n carriers = await getAspectDataCarrierIds(mediaLibraryId, aspectName)\n } finally {\n // Also on failure — a spinner left running garbles the error output.\n spin.stop()\n }\n\n // Guardrails, not gates: pruning while either is true can be deliberate\n // (e.g. clearing data before re-shaping a field), so warn and continue.\n if (config.fields.some((field) => field.name === aspectName)) {\n this.warn(\n `\"${aspectName}\" is still declared in sanity.cli.ts — its data is likely in active use and will grow back.`,\n )\n }\n if (storedIds.includes(aspectName)) {\n this.warn(\n `Aspect definition \"${aspectName}\" still exists in the library — this only removes data, not the definition.`,\n )\n }\n\n if (carriers.length === 0) {\n this.log(\n `No assets in media library ${styleText('bold', mediaLibraryId)} carry ${styleText(\n 'bold',\n `aspects.${aspectName}`,\n )} — nothing to prune.`,\n )\n return\n }\n\n const sample = carriers.slice(0, SAMPLE_SIZE)\n // \"documents\", not \"assets\": under the raw perspective drafts and\n // release versions are separate ids, so an asset count would overstate.\n this.log(\n `${styleText('bold', String(carriers.length))} ${pluralize(\n 'document',\n carriers.length,\n )} in media library ${styleText('bold', mediaLibraryId)} ${\n carriers.length === 1 ? 'carries' : 'carry'\n } ${styleText('bold', `aspects.${aspectName}`)}:`,\n )\n for (const id of sample) {\n this.log(` - ${id}`)\n }\n if (carriers.length > sample.length) {\n this.log(styleText('dim', ` … and ${carriers.length - sample.length} more`))\n }\n\n if (!yes) {\n this.log('')\n this.log(\n `This would ${styleText(\n 'bold',\n 'irreversibly',\n )} unset aspects.${aspectName} on all of them. Re-run with ${styleText(\n 'bold',\n '--yes',\n )} to execute.`,\n )\n return\n }\n\n let pruned = 0\n for (let offset = 0; offset < carriers.length; offset += BATCH_SIZE) {\n const batch = carriers.slice(offset, offset + BATCH_SIZE)\n try {\n await unsetAspectData({aspectName, assetIds: batch, mediaLibraryId})\n } catch (batchError) {\n // The progress made so far must survive into the error: re-running\n // is safe (pruned assets no longer match the carrier query), so the\n // message says how far it got and that a retry finishes the rest.\n throw new Error(\n `Removed aspects.${aspectName} from ${pruned} of ${carriers.length} ${pluralize(\n 'document',\n carriers.length,\n )} before a batch failed: ${getErrorMessage(batchError)}\\n` +\n `Re-running the command with --yes is safe — already-pruned documents no longer ` +\n `match and only the remaining ${carriers.length - pruned} will be mutated.`,\n {cause: batchError},\n )\n }\n pruned += batch.length\n this.log(styleText('dim', ` pruned ${pruned}/${carriers.length}`))\n }\n\n this.log('')\n this.log(\n `${logSymbols.success} aspects.${aspectName} removed from ${pruned} ${pluralize(\n 'document',\n pruned,\n )}.`,\n )\n } catch (error) {\n const err = error as Error\n // Ctrl+C in the library prompt and errors that already carry their exit\n // story (`this.error`, CLIError from the resolver) pass through to\n // `SanityCommand.catch` instead of being re-wrapped here.\n if (err.name === 'ExitPromptError' || 'oclif' in err) {\n throw err\n }\n pruneAspectDataDebug('Failed to prune aspect data', {\n aspectName,\n error: err,\n })\n this.error(\n styleText('bold', 'Failed to prune aspect data') + `\\n\\n${styleText('red', err.message)}`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n }\n}\n"],"names":["styleText","Args","Flags","exitCodes","ProjectRootNotFoundError","SanityCommand","subdebug","getErrorMessage","logSymbols","spinner","resolveWorkbenchConfig","VALID_ASPECT_NAME","resolveMediaLibraryId","getAspectDataCarrierIds","getStoredAspectIds","unsetAspectData","pluralize","pruneAspectDataDebug","NOT_A_CONFIG_APP","BATCH_SIZE","SAMPLE_SIZE","MediaPruneAspectDataCommand","args","aspectName","string","description","required","examples","command","flags","yes","boolean","char","hidden","run","mediaLibraryIdFlag","test","error","exit","USAGE_ERROR","cliConfig","getCliConfig","err","RUNTIME_ERROR","config","appType","mediaLibraryId","organizationId","unattended","resolveIsInteractive","spin","start","storedIds","carriers","stop","fields","some","field","name","warn","includes","length","log","sample","slice","String","id","pruned","offset","batch","assetIds","batchError","Error","cause","success","message"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAEEC,SAAS,EACTC,wBAAwB,EACxBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQ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E,EAAE,OAAOyB,YAAY;oBACnB,mEAAmE;oBACnE,oEAAoE;oBACpE,kEAAkE;oBAClE,MAAM,IAAIC,MACR,CAAC,gBAAgB,EAAEjD,WAAW,MAAM,EAAE4C,OAAO,IAAI,EAAEd,SAASQ,MAAM,CAAC,CAAC,EAAE7C,UACpE,YACAqC,SAASQ,MAAM,EACf,wBAAwB,EAAEtD,gBAAgBgE,YAAY,EAAE,CAAC,GACzD,CAAC,+EAA+E,CAAC,GACjF,CAAC,6BAA6B,EAAElB,SAASQ,MAAM,GAAGM,OAAO,iBAAiB,CAAC,EAC7E;wBAACM,OAAOF;oBAAU;gBAEtB;gBACAJ,UAAUE,MAAMR,MAAM;gBACtB,IAAI,CAACC,GAAG,CAAC9D,UAAU,OAAO,CAAC,SAAS,EAAEmE,OAAO,CAAC,EAAEd,SAASQ,MAAM,EAAE;YACnE;YAEA,IAAI,CAACC,GAAG,CAAC;YACT,IAAI,CAACA,GAAG,CACN,GAAGtD,WAAWkE,OAAO,CAAC,SAAS,EAAEnD,WAAW,cAAc,EAAE4C,OAAO,CAAC,EAAEnD,UACpE,YACAmD,QACA,CAAC,CAAC;QAER,EAAE,OAAO9B,OAAO;YACd,MAAMK,MAAML;YACZ,wEAAwE;YACxE,mEAAmE;YACnE,0DAA0D;YAC1D,IAAIK,IAAIgB,IAAI,KAAK,qBAAqB,WAAWhB,KAAK;gBACpD,MAAMA;YACR;YACAzB,qBAAqB,+BAA+B;gBAClDM;gBACAc,OAAOK;YACT;YACA,IAAI,CAACL,KAAK,CACRrC,UAAU,QAAQ,iCAAiC,CAAC,IAAI,EAAEA,UAAU,OAAO0C,IAAIiC,OAAO,GAAG,EACzF;gBAACrC,MAAMnC,UAAUwC,aAAa;YAAA;QAElC;IACF;AACF"}
@@ -67,7 +67,7 @@ export class MediaPullAspectsCommand extends SanityCommand {
67
67
  throw err;
68
68
  }
69
69
  const config = resolveWorkbenchConfig(cliConfig);
70
- if (!config) {
70
+ if (config?.appType !== 'media-library') {
71
71
  this.error(NOT_A_CONFIG_APP, {
72
72
  exit: exitCodes.RUNTIME_ERROR
73
73
  });