@sanity/cli-core 2.7.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/SanityCommand.d.ts +7 -4
- package/dist/SanityCommand.js +14 -0
- package/dist/SanityCommand.js.map +1 -1
- package/dist/_exports/config.d.ts +0 -4
- package/dist/_exports/index.d.ts +7 -4
- package/dist/_exports/types.d.ts +0 -4
- package/dist/_exports/ux.d.ts +53 -12
- package/dist/_exports/ux.js +1 -0
- package/dist/_exports/ux.js.map +1 -1
- package/dist/config/cli/cliUserConfig.js +10 -4
- package/dist/config/cli/cliUserConfig.js.map +1 -1
- package/dist/config/cli/types/cliConfig.js.map +1 -1
- package/dist/telemetry/getCliTelemetry.js +5 -0
- package/dist/telemetry/getCliTelemetry.js.map +1 -1
- package/dist/ux/flowOutput.js +128 -0
- package/dist/ux/flowOutput.js.map +1 -0
- package/dist/ux/spinner.js +28 -1
- package/dist/ux/spinner.js.map +1 -1
- package/package.json +4 -3
package/dist/SanityCommand.d.ts
CHANGED
|
@@ -34,8 +34,6 @@ declare interface CliConfig {
|
|
|
34
34
|
app?: {
|
|
35
35
|
/** The entrypoint for your custom app. By default, `src/App.tsx` */
|
|
36
36
|
entry?: string;
|
|
37
|
-
/** Dock group the app renders in. Defaults to `dock.applications`. */
|
|
38
|
-
group?: "dock.applications" | "dock.system" | "dock.user";
|
|
39
37
|
/**
|
|
40
38
|
* Path to an icon file relative to project root.
|
|
41
39
|
* The file must be an SVG.
|
|
@@ -45,8 +43,6 @@ declare interface CliConfig {
|
|
|
45
43
|
id?: string;
|
|
46
44
|
/** The ID for the Sanity organization that manages this application */
|
|
47
45
|
organizationId?: string;
|
|
48
|
-
/** Sort position within the dock group, ascending. Defaults to `100`. */
|
|
49
|
-
priority?: number;
|
|
50
46
|
/** The title of the custom app, as it is seen in Dashboard UI */
|
|
51
47
|
title?: string;
|
|
52
48
|
/** Dashboard visibility of the application. Defaults to `default`. */
|
|
@@ -396,6 +392,13 @@ export declare abstract class SanityCommand<T extends typeof Command>
|
|
|
396
392
|
* @returns Whether the terminal is interactive.
|
|
397
393
|
*/
|
|
398
394
|
resolveIsInteractive(): boolean;
|
|
395
|
+
/**
|
|
396
|
+
* Execute an already-constructed command without oclif's static runner:
|
|
397
|
+
* `Command.run()` performs a full `Config.load()` — filesystem reads, env
|
|
398
|
+
* consultation, and a process-global config cache write — on every call,
|
|
399
|
+
* which programmatic invocations must not repeat per request.
|
|
400
|
+
*/
|
|
401
|
+
runInExecutionContext<TResult>(): Promise<TResult>;
|
|
399
402
|
/**
|
|
400
403
|
* Get the CLI config, returning an empty config if no project root is found.
|
|
401
404
|
*
|
package/dist/SanityCommand.js
CHANGED
|
@@ -151,6 +151,9 @@ export class SanityCommand extends Command {
|
|
|
151
151
|
*
|
|
152
152
|
* @returns The project root result.
|
|
153
153
|
*/ getProjectRoot() {
|
|
154
|
+
if (getCliExecutionContext()) {
|
|
155
|
+
throw new ProjectRootNotFoundError('Project root resolution from the filesystem is disabled for programmatic invocations');
|
|
156
|
+
}
|
|
154
157
|
return findProjectRoot(process.cwd());
|
|
155
158
|
}
|
|
156
159
|
async init() {
|
|
@@ -222,6 +225,17 @@ export class SanityCommand extends Command {
|
|
|
222
225
|
return isInteractive();
|
|
223
226
|
}
|
|
224
227
|
/**
|
|
228
|
+
* Execute an already-constructed command without oclif's static runner:
|
|
229
|
+
* `Command.run()` performs a full `Config.load()` — filesystem reads, env
|
|
230
|
+
* consultation, and a process-global config cache write — on every call,
|
|
231
|
+
* which programmatic invocations must not repeat per request.
|
|
232
|
+
*/ runInExecutionContext() {
|
|
233
|
+
if (!getCliExecutionContext()) {
|
|
234
|
+
throw new Error('runInExecutionContext requires a CLI execution context');
|
|
235
|
+
}
|
|
236
|
+
return this._run();
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
225
239
|
* Get the CLI config, returning an empty config if no project root is found.
|
|
226
240
|
*
|
|
227
241
|
* Use this instead of `getCliConfig()` in commands that can operate without a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/SanityCommand.ts"],"sourcesContent":["import {format, styleText} from 'node:util'\n\nimport {Command, Interfaces} from '@oclif/core'\nimport {type CommandError} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {\n getGlobalCliClient,\n getProjectCliClient,\n type GlobalCliClientOptions,\n type ProjectCliClientOptions,\n} from './apiClient.js'\nimport {getCliConfig} from './config/cli/getCliConfig.js'\nimport {type CliConfig} from './config/cli/types/cliConfig.js'\nimport {findProjectRoot} from './config/findProjectRoot.js'\nimport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nimport {NonInteractiveError} from './errors/NonInteractiveError.js'\nimport {ProjectRootNotFoundError} from './errors/ProjectRootNotFoundError.js'\nimport {getCliExecutionContext} from './executionContext.js'\nimport {exitCodes} from './exitCodes.js'\nimport {getCliTelemetry, reportCliTraceError} from './telemetry/getCliTelemetry.js'\nimport {type CLITelemetryStore} from './telemetry/types.js'\nimport {type Output} from './types.js'\nimport {isInteractive} from './util/isInteractive.js'\n\ntype Flags<T extends typeof Command> = Interfaces.InferredFlags<\n (typeof SanityCommand)['baseFlags'] & T['flags']\n>\n\ntype Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>\n\nconst debug = subdebug('sanityCommand')\n\n/**\n * Interface for `SanityCommand`, a wrapper around OCLIF's Command class.\n * Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.\n * @see https://oclif.io/docs/base_class/\n */\nexport interface SanityCommandInterface {\n getCliConfig: () => Promise<CliConfig>\n getProjectId: (options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }) => Promise<string>\n getProjectRoot: () => Promise<ProjectRootResult>\n isUnattended: () => boolean\n output: Output\n resolveIsInteractive: () => boolean\n}\n\nexport abstract class SanityCommand<T extends typeof Command>\n extends Command\n implements SanityCommandInterface\n{\n protected args!: Args<T>\n protected flags!: Flags<T>\n\n /**\n * Get the global API client.\n *\n * @param args - The global API client options.\n * @returns The global API client.\n *\n * @deprecated use `getGlobalCliClient` function directly instead.\n */\n protected getGlobalApiClient = (args: GlobalCliClientOptions) => getGlobalCliClient(args)\n\n /**\n * Get the project API client.\n *\n * @param args - The project API client options.\n * @returns The project API client.\n *\n * @deprecated use `getProjectCliClient` function directly instead.\n */\n protected getProjectApiClient = (args: ProjectCliClientOptions) => getProjectCliClient(args)\n\n /**\n * Helper for outputting to the console.\n *\n * @example\n * ```ts\n * this.output.log('Hello')\n * this.output.warn('Warning')\n * this.output.error('Error')\n * ```\n */\n public output: Output = {\n error: this.error.bind(this),\n log: this.log.bind(this),\n warn: this.warn.bind(this),\n }\n\n /**\n * The telemetry store.\n *\n * @returns The telemetry store.\n */\n protected telemetry!: CLITelemetryStore\n\n /**\n * Report real command errors to the CLI command trace.\n * User aborts (SIGINT, ExitPromptError) are not reported — the trace is left\n * incomplete, which accurately represents that the command was interrupted.\n */\n protected override async catch(err: CommandError): Promise<void> {\n // ExitPromptError is thrown by `@inquirer/prompts` when the user cancels a prompt\n // The `message === 'SIGINT'` check matches oclif's own convention (see handle.js in @oclif/core)\n if (err.name === 'ExitPromptError' || err.message === 'SIGINT') {\n this.logToStderr(styleText('yellow', '\\u{203A}') + ' Aborted by user')\n return this.exit(exitCodes.SIGINT)\n }\n\n // In other cases, we _do_ want to report the error\n reportCliTraceError(err)\n\n // oclif's base `catch` sets `process.exitCode` as a side effect\n // we do not want to write to the host's own exit status.\n if (getCliExecutionContext()) {\n if (this.jsonEnabled()) {\n this.logJson(this.toErrorJson(err))\n return\n }\n throw err\n }\n\n return super.catch(err)\n }\n\n /**\n * Get the CLI config.\n *\n * @returns The CLI config.\n */\n public async getCliConfig(): Promise<CliConfig> {\n const root = await this.getProjectRoot()\n\n debug(`Using project root`, root)\n return getCliConfig(root.directory)\n }\n\n /**\n * Get the project ID from passed flags or (if not provided) the CLI config.\n *\n * Optionally accepts a `fallback` function that is called when no project ID\n * can be determined from flags or config. This allows commands to provide\n * interactive project selection while keeping the prompt logic in the CLI package.\n *\n * If the fallback throws a `NonInteractiveError` (e.g. because the terminal is\n * not interactive), it falls through to the standard error with suggestions.\n *\n * Optionally accepts a `deprecatedFlagName` for commands that have a deprecated\n * flag (e.g. `--project`) that should be checked after `--project-id` but before\n * the CLI config.\n *\n * @returns The project ID.\n */\n public async getProjectId(options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }): Promise<string> {\n const hasProjectFlag = this.ctor.flags != null && 'project-id' in this.ctor.flags\n\n // Check --project-id flag first\n if (hasProjectFlag) {\n const flagProjectId =\n 'project-id' in this.flags && typeof this.flags['project-id'] === 'string'\n ? this.flags['project-id']\n : undefined\n\n if (flagProjectId) return flagProjectId\n }\n\n // Check deprecated flag (e.g. --project) before CLI config\n if (options?.deprecatedFlagName) {\n const deprecatedValue =\n options.deprecatedFlagName in this.flags &&\n typeof this.flags[options.deprecatedFlagName] === 'string'\n ? (this.flags[options.deprecatedFlagName] as string)\n : undefined\n\n if (deprecatedValue) return deprecatedValue\n }\n\n // Fall back to CLI config\n try {\n const config = await this.getCliConfig()\n const configProjectId = config.api?.projectId\n if (configProjectId) return configProjectId\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n // No project root — fall through to fallback/error\n }\n\n // Offer interactive selection if a fallback was provided\n if (options?.fallback) {\n try {\n return await options.fallback()\n } catch (err) {\n if (!(err instanceof NonInteractiveError)) throw err\n // Non-interactive: throw with actionable suggestions\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n cause: err,\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n 'Running in an interactive terminal to get a project selection prompt',\n ],\n })\n }\n }\n\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n ],\n })\n }\n\n /**\n * Get the project's root directory by resolving the config\n *\n * @returns The project root result.\n */\n public getProjectRoot(): Promise<ProjectRootResult> {\n return findProjectRoot(process.cwd())\n }\n\n public async init(): Promise<void> {\n const {args, flags} = await this.parse({\n args: this.ctor.args,\n baseFlags: (super.ctor as typeof SanityCommand).baseFlags,\n enableJsonFlag: this.ctor.enableJsonFlag,\n flags: this.ctor.flags,\n strict: this.ctor.strict,\n })\n\n this.args = args as Args<T>\n this.flags = flags as Flags<T>\n this.telemetry = getCliTelemetry()\n\n await super.init()\n }\n\n /**\n * Check if the command is running in unattended mode.\n *\n * This means the command should not ask for user input, instead using defaults where\n * possible, and if that does not make sense (eg there's missing information), then we\n * should error out (remember to exit with a non-zero code).\n *\n * Most commands should take an explicit `--yes` flag to enable unattended mode, but\n * some commands may also be run in unattended mode if `process.stdin` is not a TTY\n * (eg when running in a CI environment), or when `--json` asks for machine-readable\n * output (a caller parsing JSON can't answer a prompt).\n */\n public isUnattended(): boolean {\n return this.flags.yes || this.flags.json || !this.resolveIsInteractive()\n }\n\n /**\n * Write to stdout — or, when running under an execution context (e.g. from\n * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`\n * semantics: suppressed when `--json` is enabled, printf-style formatting.\n */\n public override log(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.log(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stdout(format(message, ...args))\n }\n\n /**\n * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the\n * execution context's `stdout` sink, so programmatic callers don't have to\n * strip ANSI codes.\n */\n public override logJson(json: unknown): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.logJson(json)\n return\n }\n context.stdout(JSON.stringify(json, null, 2))\n }\n\n /**\n * Like `log`, but for stderr / the context's `stderr` sink.\n */\n public override logToStderr(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stderr) {\n super.logToStderr(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stderr(format(message, ...args))\n }\n\n /**\n * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.\n *\n * @returns Whether the terminal is interactive.\n */\n public resolveIsInteractive(): boolean {\n return isInteractive()\n }\n\n /**\n * Get the CLI config, returning an empty config if no project root is found.\n *\n * Use this instead of `getCliConfig()` in commands that can operate without a\n * project directory (e.g. when `--project-id` and `--dataset` flags are provided).\n *\n * @returns The CLI config, or an empty config object if no project root is found.\n */\n protected async tryGetCliConfig(): Promise<CliConfig> {\n try {\n return await this.getCliConfig()\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n return {}\n }\n }\n\n /**\n * Emit a warning — routed to the execution context's `stderr` sink when one\n * is active, otherwise through oclif's standard warning printer.\n */\n public override warn(input: Error | string): Error | string {\n const context = getCliExecutionContext()\n if (!context?.stderr) return super.warn(input)\n\n if (!this.jsonEnabled()) {\n context.stderr(`Warning: ${input instanceof Error ? input.message : input}`)\n }\n return input\n }\n}\n"],"names":["format","styleText","Command","subdebug","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","NonInteractiveError","ProjectRootNotFoundError","getCliExecutionContext","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","debug","SanityCommand","args","flags","getGlobalApiClient","getProjectApiClient","output","error","bind","log","warn","telemetry","catch","err","name","message","logToStderr","exit","SIGINT","jsonEnabled","logJson","toErrorJson","root","getProjectRoot","directory","getProjectId","options","hasProjectFlag","ctor","flagProjectId","undefined","deprecatedFlagName","deprecatedValue","config","configProjectId","api","projectId","fallback","cause","suggestions","process","cwd","init","parse","baseFlags","enableJsonFlag","strict","isUnattended","yes","json","resolveIsInteractive","context","stdout","JSON","stringify","stderr","tryGetCliConfig","input","Error"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO,QAAmB,cAAa;AAG/C,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SACEC,kBAAkB,EAClBC,mBAAmB,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YACpB,KAAK,CAAC3C,IAAIM,YAAYb;YACtB;QACF;QACA,IAAI,CAAC,IAAI,CAACiB,WAAW,IAAIgC,QAAQC,MAAM,CAACnE,OAAO8B,YAAYb;IAC7D;IAEA;;;;GAIC,GACD,AAAgBkB,QAAQ6B,IAAa,EAAQ;QAC3C,MAAME,UAAUxD;QAChB,IAAI,CAACwD,SAASC,QAAQ;YACpB,KAAK,CAAChC,QAAQ6B;YACd;QACF;QACAE,QAAQC,MAAM,CAACC,KAAKC,SAAS,CAACL,MAAM,MAAM;IAC5C;IAEA;;GAEC,GACD,AAAgBjC,YAAYD,UAAU,EAAE,EAAE,GAAGb,IAAe,EAAQ;QAClE,MAAMiD,UAAUxD;QAChB,IAAI,CAACwD,SAASI,QAAQ;YACpB,KAAK,CAACvC,YAAYD,YAAYb;YAC9B;QACF;QACA,IAAI,CAAC,IAAI,CAACiB,WAAW,IAAIgC,QAAQI,MAAM,CAACtE,OAAO8B,YAAYb;IAC7D;IAEA;;;;GAIC,GACD,AAAOgD,uBAAgC;QACrC,OAAOnD;IACT;IAEA;;;;;;;GAOC,GACD,MAAgByD,kBAAsC;QACpD,IAAI;YACF,OAAO,MAAM,IAAI,CAACjE,YAAY;QAChC,EAAE,OAAOsB,KAAK;YACZ,IAAI,CAAEA,CAAAA,eAAenB,wBAAuB,GAAI,MAAMmB;YACtD,OAAO,CAAC;QACV;IACF;IAEA;;;GAGC,GACD,AAAgBH,KAAK+C,KAAqB,EAAkB;QAC1D,MAAMN,UAAUxD;QAChB,IAAI,CAACwD,SAASI,QAAQ,OAAO,KAAK,CAAC7C,KAAK+C;QAExC,IAAI,CAAC,IAAI,CAACtC,WAAW,IAAI;YACvBgC,QAAQI,MAAM,CAAC,CAAC,SAAS,EAAEE,iBAAiBC,QAAQD,MAAM1C,OAAO,GAAG0C,OAAO;QAC7E;QACA,OAAOA;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../src/SanityCommand.ts"],"sourcesContent":["import {format, styleText} from 'node:util'\n\nimport {Command, Interfaces} from '@oclif/core'\nimport {type CommandError} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {\n getGlobalCliClient,\n getProjectCliClient,\n type GlobalCliClientOptions,\n type ProjectCliClientOptions,\n} from './apiClient.js'\nimport {getCliConfig} from './config/cli/getCliConfig.js'\nimport {type CliConfig} from './config/cli/types/cliConfig.js'\nimport {findProjectRoot} from './config/findProjectRoot.js'\nimport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nimport {NonInteractiveError} from './errors/NonInteractiveError.js'\nimport {ProjectRootNotFoundError} from './errors/ProjectRootNotFoundError.js'\nimport {getCliExecutionContext} from './executionContext.js'\nimport {exitCodes} from './exitCodes.js'\nimport {getCliTelemetry, reportCliTraceError} from './telemetry/getCliTelemetry.js'\nimport {type CLITelemetryStore} from './telemetry/types.js'\nimport {type Output} from './types.js'\nimport {isInteractive} from './util/isInteractive.js'\n\ntype Flags<T extends typeof Command> = Interfaces.InferredFlags<\n (typeof SanityCommand)['baseFlags'] & T['flags']\n>\n\ntype Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>\n\nconst debug = subdebug('sanityCommand')\n\n/**\n * Interface for `SanityCommand`, a wrapper around OCLIF's Command class.\n * Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.\n * @see https://oclif.io/docs/base_class/\n */\nexport interface SanityCommandInterface {\n getCliConfig: () => Promise<CliConfig>\n getProjectId: (options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }) => Promise<string>\n getProjectRoot: () => Promise<ProjectRootResult>\n isUnattended: () => boolean\n output: Output\n resolveIsInteractive: () => boolean\n}\n\nexport abstract class SanityCommand<T extends typeof Command>\n extends Command\n implements SanityCommandInterface\n{\n protected args!: Args<T>\n protected flags!: Flags<T>\n\n /**\n * Get the global API client.\n *\n * @param args - The global API client options.\n * @returns The global API client.\n *\n * @deprecated use `getGlobalCliClient` function directly instead.\n */\n protected getGlobalApiClient = (args: GlobalCliClientOptions) => getGlobalCliClient(args)\n\n /**\n * Get the project API client.\n *\n * @param args - The project API client options.\n * @returns The project API client.\n *\n * @deprecated use `getProjectCliClient` function directly instead.\n */\n protected getProjectApiClient = (args: ProjectCliClientOptions) => getProjectCliClient(args)\n\n /**\n * Helper for outputting to the console.\n *\n * @example\n * ```ts\n * this.output.log('Hello')\n * this.output.warn('Warning')\n * this.output.error('Error')\n * ```\n */\n public output: Output = {\n error: this.error.bind(this),\n log: this.log.bind(this),\n warn: this.warn.bind(this),\n }\n\n /**\n * The telemetry store.\n *\n * @returns The telemetry store.\n */\n protected telemetry!: CLITelemetryStore\n\n /**\n * Report real command errors to the CLI command trace.\n * User aborts (SIGINT, ExitPromptError) are not reported — the trace is left\n * incomplete, which accurately represents that the command was interrupted.\n */\n protected override async catch(err: CommandError): Promise<void> {\n // ExitPromptError is thrown by `@inquirer/prompts` when the user cancels a prompt\n // The `message === 'SIGINT'` check matches oclif's own convention (see handle.js in @oclif/core)\n if (err.name === 'ExitPromptError' || err.message === 'SIGINT') {\n this.logToStderr(styleText('yellow', '\\u{203A}') + ' Aborted by user')\n return this.exit(exitCodes.SIGINT)\n }\n\n // In other cases, we _do_ want to report the error\n reportCliTraceError(err)\n\n // oclif's base `catch` sets `process.exitCode` as a side effect\n // we do not want to write to the host's own exit status.\n if (getCliExecutionContext()) {\n if (this.jsonEnabled()) {\n this.logJson(this.toErrorJson(err))\n return\n }\n throw err\n }\n\n return super.catch(err)\n }\n\n /**\n * Get the CLI config.\n *\n * @returns The CLI config.\n */\n public async getCliConfig(): Promise<CliConfig> {\n const root = await this.getProjectRoot()\n\n debug(`Using project root`, root)\n return getCliConfig(root.directory)\n }\n\n /**\n * Get the project ID from passed flags or (if not provided) the CLI config.\n *\n * Optionally accepts a `fallback` function that is called when no project ID\n * can be determined from flags or config. This allows commands to provide\n * interactive project selection while keeping the prompt logic in the CLI package.\n *\n * If the fallback throws a `NonInteractiveError` (e.g. because the terminal is\n * not interactive), it falls through to the standard error with suggestions.\n *\n * Optionally accepts a `deprecatedFlagName` for commands that have a deprecated\n * flag (e.g. `--project`) that should be checked after `--project-id` but before\n * the CLI config.\n *\n * @returns The project ID.\n */\n public async getProjectId(options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }): Promise<string> {\n const hasProjectFlag = this.ctor.flags != null && 'project-id' in this.ctor.flags\n\n // Check --project-id flag first\n if (hasProjectFlag) {\n const flagProjectId =\n 'project-id' in this.flags && typeof this.flags['project-id'] === 'string'\n ? this.flags['project-id']\n : undefined\n\n if (flagProjectId) return flagProjectId\n }\n\n // Check deprecated flag (e.g. --project) before CLI config\n if (options?.deprecatedFlagName) {\n const deprecatedValue =\n options.deprecatedFlagName in this.flags &&\n typeof this.flags[options.deprecatedFlagName] === 'string'\n ? (this.flags[options.deprecatedFlagName] as string)\n : undefined\n\n if (deprecatedValue) return deprecatedValue\n }\n\n // Fall back to CLI config\n try {\n const config = await this.getCliConfig()\n const configProjectId = config.api?.projectId\n if (configProjectId) return configProjectId\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n // No project root — fall through to fallback/error\n }\n\n // Offer interactive selection if a fallback was provided\n if (options?.fallback) {\n try {\n return await options.fallback()\n } catch (err) {\n if (!(err instanceof NonInteractiveError)) throw err\n // Non-interactive: throw with actionable suggestions\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n cause: err,\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n 'Running in an interactive terminal to get a project selection prompt',\n ],\n })\n }\n }\n\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n ],\n })\n }\n\n /**\n * Get the project's root directory by resolving the config\n *\n * @returns The project root result.\n */\n public getProjectRoot(): Promise<ProjectRootResult> {\n if (getCliExecutionContext()) {\n throw new ProjectRootNotFoundError(\n 'Project root resolution from the filesystem is disabled for programmatic invocations',\n )\n }\n return findProjectRoot(process.cwd())\n }\n\n public async init(): Promise<void> {\n const {args, flags} = await this.parse({\n args: this.ctor.args,\n baseFlags: (super.ctor as typeof SanityCommand).baseFlags,\n enableJsonFlag: this.ctor.enableJsonFlag,\n flags: this.ctor.flags,\n strict: this.ctor.strict,\n })\n\n this.args = args as Args<T>\n this.flags = flags as Flags<T>\n this.telemetry = getCliTelemetry()\n\n await super.init()\n }\n\n /**\n * Check if the command is running in unattended mode.\n *\n * This means the command should not ask for user input, instead using defaults where\n * possible, and if that does not make sense (eg there's missing information), then we\n * should error out (remember to exit with a non-zero code).\n *\n * Most commands should take an explicit `--yes` flag to enable unattended mode, but\n * some commands may also be run in unattended mode if `process.stdin` is not a TTY\n * (eg when running in a CI environment), or when `--json` asks for machine-readable\n * output (a caller parsing JSON can't answer a prompt).\n */\n public isUnattended(): boolean {\n return this.flags.yes || this.flags.json || !this.resolveIsInteractive()\n }\n\n /**\n * Write to stdout — or, when running under an execution context (e.g. from\n * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`\n * semantics: suppressed when `--json` is enabled, printf-style formatting.\n */\n public override log(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.log(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stdout(format(message, ...args))\n }\n\n /**\n * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the\n * execution context's `stdout` sink, so programmatic callers don't have to\n * strip ANSI codes.\n */\n public override logJson(json: unknown): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.logJson(json)\n return\n }\n context.stdout(JSON.stringify(json, null, 2))\n }\n\n /**\n * Like `log`, but for stderr / the context's `stderr` sink.\n */\n public override logToStderr(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stderr) {\n super.logToStderr(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stderr(format(message, ...args))\n }\n\n /**\n * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.\n *\n * @returns Whether the terminal is interactive.\n */\n public resolveIsInteractive(): boolean {\n return isInteractive()\n }\n\n /**\n * Execute an already-constructed command without oclif's static runner:\n * `Command.run()` performs a full `Config.load()` — filesystem reads, env\n * consultation, and a process-global config cache write — on every call,\n * which programmatic invocations must not repeat per request.\n */\n public runInExecutionContext<TResult>(): Promise<TResult> {\n if (!getCliExecutionContext()) {\n throw new Error('runInExecutionContext requires a CLI execution context')\n }\n return this._run<TResult>()\n }\n\n /**\n * Get the CLI config, returning an empty config if no project root is found.\n *\n * Use this instead of `getCliConfig()` in commands that can operate without a\n * project directory (e.g. when `--project-id` and `--dataset` flags are provided).\n *\n * @returns The CLI config, or an empty config object if no project root is found.\n */\n protected async tryGetCliConfig(): Promise<CliConfig> {\n try {\n return await this.getCliConfig()\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n return {}\n }\n }\n\n /**\n * Emit a warning — routed to the execution context's `stderr` sink when one\n * is active, otherwise through oclif's standard warning printer.\n */\n public override warn(input: Error | string): Error | string {\n const context = getCliExecutionContext()\n if (!context?.stderr) return super.warn(input)\n\n if (!this.jsonEnabled()) {\n context.stderr(`Warning: ${input instanceof Error ? input.message : input}`)\n }\n return input\n }\n}\n"],"names":["format","styleText","Command","subdebug","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","NonInteractiveError","ProjectRootNotFoundError","getCliExecutionContext","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","debug","SanityCommand","args","flags","getGlobalApiClient","getProjectApiClient","output","error","bind","log","warn","telemetry","catch","err","name","message","logToStderr","exit","SIGINT","jsonEnabled","logJson","toErrorJson","root","getProjectRoot","directory","getProjectId","options","hasProjectFlag","ctor","flagProjectId","undefined","deprecatedFlagName","deprecatedValue","config","configProjectId","api","projectId","fallback","cause","suggestions","process","cwd","init","parse","baseFlags","enableJsonFlag","strict","isUnattended","yes","json","resolveIsInteractive","context","stdout","JSON","stringify","stderr","runInExecutionContext","Error","_run","tryGetCliConfig","input"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO,QAAmB,cAAa;AAG/C,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SACEC,kBAAkB,EAClBC,mBAAmB,QAGd,iBAAgB;AACvB,SAAQC,YAAY,QAAO,+BAA8B;AAEzD,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,SAAQC,mBAAmB,QAAO,kCAAiC;AACnE,SAAQC,wBAAwB,QAAO,uCAAsC;AAC7E,SAAQC,sBAAsB,QAAO,wBAAuB;AAC5D,SAAQC,SAAS,QAAO,iBAAgB;AACxC,SAAQC,eAAe,EAAEC,mBAAmB,QAAO,iCAAgC;AAGnF,SAAQC,aAAa,QAAO,0BAAyB;AAQrD,MAAMC,QAAQZ,SAAS;AAmBvB,OAAO,MAAea,sBACZd;IAGEe,KAAc;IACdC,MAAgB;IAE1B;;;;;;;GAOC,GACD,AAAUC,qBAAqB,CAACF,OAAiCb,mBAAmBa,MAAK;IAEzF;;;;;;;GAOC,GACD,AAAUG,sBAAsB,CAACH,OAAkCZ,oBAAoBY,MAAK;IAE5F;;;;;;;;;GASC,GACD,AAAOI,SAAiB;QACtBC,OAAO,IAAI,CAACA,KAAK,CAACC,IAAI,CAAC,IAAI;QAC3BC,KAAK,IAAI,CAACA,GAAG,CAACD,IAAI,CAAC,IAAI;QACvBE,MAAM,IAAI,CAACA,IAAI,CAACF,IAAI,CAAC,IAAI;IAC3B,EAAC;IAED;;;;GAIC,GACD,AAAUG,UAA6B;IAEvC;;;;GAIC,GACD,MAAyBC,MAAMC,GAAiB,EAAiB;QAC/D,kFAAkF;QAClF,iGAAiG;QACjG,IAAIA,IAAIC,IAAI,KAAK,qBAAqBD,IAAIE,OAAO,KAAK,UAAU;YAC9D,IAAI,CAACC,WAAW,CAAC9B,UAAU,UAAU,cAAc;YACnD,OAAO,IA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AAI,MAAMmB;YACtD,OAAO,CAAC;QACV;IACF;IAEA;;;GAGC,GACD,AAAgBH,KAAKkD,KAAqB,EAAkB;QAC1D,MAAMT,UAAUxD;QAChB,IAAI,CAACwD,SAASI,QAAQ,OAAO,KAAK,CAAC7C,KAAKkD;QAExC,IAAI,CAAC,IAAI,CAACzC,WAAW,IAAI;YACvBgC,QAAQI,MAAM,CAAC,CAAC,SAAS,EAAEK,iBAAiBH,QAAQG,MAAM7C,OAAO,GAAG6C,OAAO;QAC7E;QACA,OAAOA;IACT;AACF"}
|
|
@@ -37,8 +37,6 @@ export declare interface CliConfig {
|
|
|
37
37
|
app?: {
|
|
38
38
|
/** The entrypoint for your custom app. By default, `src/App.tsx` */
|
|
39
39
|
entry?: string;
|
|
40
|
-
/** Dock group the app renders in. Defaults to `dock.applications`. */
|
|
41
|
-
group?: "dock.applications" | "dock.system" | "dock.user";
|
|
42
40
|
/**
|
|
43
41
|
* Path to an icon file relative to project root.
|
|
44
42
|
* The file must be an SVG.
|
|
@@ -48,8 +46,6 @@ export declare interface CliConfig {
|
|
|
48
46
|
id?: string;
|
|
49
47
|
/** The ID for the Sanity organization that manages this application */
|
|
50
48
|
organizationId?: string;
|
|
51
|
-
/** Sort position within the dock group, ascending. Defaults to `100`. */
|
|
52
|
-
priority?: number;
|
|
53
49
|
/** The title of the custom app, as it is seen in Dashboard UI */
|
|
54
50
|
title?: string;
|
|
55
51
|
/** Dashboard visibility of the application. Defaults to `default`. */
|
package/dist/_exports/index.d.ts
CHANGED
|
@@ -80,8 +80,6 @@ export declare interface CliConfig {
|
|
|
80
80
|
app?: {
|
|
81
81
|
/** The entrypoint for your custom app. By default, `src/App.tsx` */
|
|
82
82
|
entry?: string;
|
|
83
|
-
/** Dock group the app renders in. Defaults to `dock.applications`. */
|
|
84
|
-
group?: "dock.applications" | "dock.system" | "dock.user";
|
|
85
83
|
/**
|
|
86
84
|
* Path to an icon file relative to project root.
|
|
87
85
|
* The file must be an SVG.
|
|
@@ -91,8 +89,6 @@ export declare interface CliConfig {
|
|
|
91
89
|
id?: string;
|
|
92
90
|
/** The ID for the Sanity organization that manages this application */
|
|
93
91
|
organizationId?: string;
|
|
94
|
-
/** Sort position within the dock group, ascending. Defaults to `100`. */
|
|
95
|
-
priority?: number;
|
|
96
92
|
/** The title of the custom app, as it is seen in Dashboard UI */
|
|
97
93
|
title?: string;
|
|
98
94
|
/** Dashboard visibility of the application. Defaults to `default`. */
|
|
@@ -1422,6 +1418,13 @@ export declare abstract class SanityCommand<T extends typeof Command>
|
|
|
1422
1418
|
* @returns Whether the terminal is interactive.
|
|
1423
1419
|
*/
|
|
1424
1420
|
resolveIsInteractive(): boolean;
|
|
1421
|
+
/**
|
|
1422
|
+
* Execute an already-constructed command without oclif's static runner:
|
|
1423
|
+
* `Command.run()` performs a full `Config.load()` — filesystem reads, env
|
|
1424
|
+
* consultation, and a process-global config cache write — on every call,
|
|
1425
|
+
* which programmatic invocations must not repeat per request.
|
|
1426
|
+
*/
|
|
1427
|
+
runInExecutionContext<TResult>(): Promise<TResult>;
|
|
1425
1428
|
/**
|
|
1426
1429
|
* Get the CLI config, returning an empty config if no project root is found.
|
|
1427
1430
|
*
|
package/dist/_exports/types.d.ts
CHANGED
|
@@ -38,8 +38,6 @@ export declare interface CliConfig {
|
|
|
38
38
|
app?: {
|
|
39
39
|
/** The entrypoint for your custom app. By default, `src/App.tsx` */
|
|
40
40
|
entry?: string;
|
|
41
|
-
/** Dock group the app renders in. Defaults to `dock.applications`. */
|
|
42
|
-
group?: "dock.applications" | "dock.system" | "dock.user";
|
|
43
41
|
/**
|
|
44
42
|
* Path to an icon file relative to project root.
|
|
45
43
|
* The file must be an SVG.
|
|
@@ -49,8 +47,6 @@ export declare interface CliConfig {
|
|
|
49
47
|
id?: string;
|
|
50
48
|
/** The ID for the Sanity organization that manages this application */
|
|
51
49
|
organizationId?: string;
|
|
52
|
-
/** Sort position within the dock group, ascending. Defaults to `100`. */
|
|
53
|
-
priority?: number;
|
|
54
50
|
/** The title of the custom app, as it is seen in Dashboard UI */
|
|
55
51
|
title?: string;
|
|
56
52
|
/** Dashboard visibility of the application. Defaults to `default`. */
|
package/dist/_exports/ux.d.ts
CHANGED
|
@@ -5,14 +5,12 @@ import { CLIError } from "@oclif/core/errors";
|
|
|
5
5
|
import { CustomBorderStyle } from "boxen";
|
|
6
6
|
import * as inquirer from "@inquirer/prompts";
|
|
7
7
|
import { default as logSymbols } from "log-symbols";
|
|
8
|
+
import { Options } from "ora";
|
|
9
|
+
import { Ora } from "ora";
|
|
10
|
+
import { PromiseOptions } from "ora";
|
|
8
11
|
import { Separator } from "@inquirer/prompts";
|
|
9
12
|
import { Spacing } from "boxen";
|
|
10
|
-
import { Spinner } from "ora";
|
|
11
|
-
import { default as spinner } from "ora";
|
|
12
|
-
import { Ora as SpinnerInstance } from "ora";
|
|
13
|
-
import { Options as SpinnerOptions } from "ora";
|
|
14
|
-
import { oraPromise as spinnerPromise } from "ora";
|
|
15
|
-
import { PromiseOptions as SpinnerPromiseOptions } from "ora";
|
|
13
|
+
import { Spinner as Spinner_2 } from "ora";
|
|
16
14
|
|
|
17
15
|
export { boxen };
|
|
18
16
|
|
|
@@ -26,12 +24,50 @@ export declare function colorizeJson(input: unknown): string;
|
|
|
26
24
|
|
|
27
25
|
export declare const confirm: typeof inquirer.confirm;
|
|
28
26
|
|
|
27
|
+
/** Create a {@link Flow} that writes rail lines through `log`. */
|
|
28
|
+
export declare function createFlow(log: LogFn): Flow;
|
|
29
|
+
|
|
29
30
|
export { CustomBorderStyle };
|
|
30
31
|
|
|
31
32
|
export declare const editor: typeof inquirer.editor;
|
|
32
33
|
|
|
33
34
|
export declare const expand: typeof inquirer.expand;
|
|
34
35
|
|
|
36
|
+
export declare interface Flow {
|
|
37
|
+
/** A copyable command belonging to the preceding action. */
|
|
38
|
+
command(command: string): void;
|
|
39
|
+
/** `│` — a blank rail line separating steps. */
|
|
40
|
+
gap(): void;
|
|
41
|
+
/** `◆` — an outcome the user should act on or remember. */
|
|
42
|
+
highlight(text: string): void;
|
|
43
|
+
/** `┌` — opening line of the story. */
|
|
44
|
+
intro(text: string): void;
|
|
45
|
+
/** `│ <text>` — a continuation line belonging to the previous step. */
|
|
46
|
+
line(text: string): void;
|
|
47
|
+
/** A copy-safe URL. Long URLs are never hard-wrapped. */
|
|
48
|
+
link(
|
|
49
|
+
url: string,
|
|
50
|
+
options?: {
|
|
51
|
+
label?: string;
|
|
52
|
+
outro?: boolean;
|
|
53
|
+
},
|
|
54
|
+
): void;
|
|
55
|
+
/** `●` — a step happening behind the scenes, or a tip. */
|
|
56
|
+
note(text: string): void;
|
|
57
|
+
/** `└` — closing line of the story. */
|
|
58
|
+
outro(text: string): void;
|
|
59
|
+
/** `◇` — a completed step or produced value. */
|
|
60
|
+
result(text: string): void;
|
|
61
|
+
/**
|
|
62
|
+
* An in-flight step. Resolve it with `succeed(text)` (persists as a `◇` line) or `fail(text)`;
|
|
63
|
+
* renders on stderr so machine-readable stdout is never corrupted.
|
|
64
|
+
*/
|
|
65
|
+
spin(text: string): {
|
|
66
|
+
fail(text: string): void;
|
|
67
|
+
succeed(text: string): void;
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
35
71
|
/**
|
|
36
72
|
* Starts a terminal timer
|
|
37
73
|
*
|
|
@@ -41,6 +77,8 @@ export declare function getTimer(): TimeMeasurer;
|
|
|
41
77
|
|
|
42
78
|
export declare const input: typeof inquirer.input;
|
|
43
79
|
|
|
80
|
+
declare type LogFn = (message?: string) => void;
|
|
81
|
+
|
|
44
82
|
export { logSymbols };
|
|
45
83
|
|
|
46
84
|
/**
|
|
@@ -68,17 +106,20 @@ export { Separator };
|
|
|
68
106
|
|
|
69
107
|
export { Spacing };
|
|
70
108
|
|
|
71
|
-
export
|
|
109
|
+
export declare type Spinner = Spinner_2;
|
|
72
110
|
|
|
73
|
-
export
|
|
111
|
+
export declare function spinner(options?: Options | string): Ora;
|
|
74
112
|
|
|
75
|
-
export
|
|
113
|
+
export declare type SpinnerInstance = Ora;
|
|
76
114
|
|
|
77
|
-
export
|
|
115
|
+
export declare type SpinnerOptions = Options;
|
|
78
116
|
|
|
79
|
-
export
|
|
117
|
+
export declare function spinnerPromise<T>(
|
|
118
|
+
action: ((instance: Ora) => PromiseLike<T>) | PromiseLike<T>,
|
|
119
|
+
options?: PromiseOptions<T> | string,
|
|
120
|
+
): Promise<T>;
|
|
80
121
|
|
|
81
|
-
export
|
|
122
|
+
export declare type SpinnerPromiseOptions<T> = PromiseOptions<T>;
|
|
82
123
|
|
|
83
124
|
declare interface TimeMeasurer {
|
|
84
125
|
end: (name: string) => number;
|
package/dist/_exports/ux.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { NonInteractiveError } from '../errors/NonInteractiveError.js';
|
|
2
2
|
export { boxen } from '../ux/boxen.js';
|
|
3
3
|
export { colorizeJson } from '../ux/colorizeJson.js';
|
|
4
|
+
export { createFlow } from '../ux/flowOutput.js';
|
|
4
5
|
export { logSymbols } from '../ux/logSymbols.js';
|
|
5
6
|
export { checkbox, confirm, editor, expand, input, number, password, rawlist, search, select, Separator } from '../ux/prompts.js';
|
|
6
7
|
export { spinner, spinnerPromise } from '../ux/spinner.js';
|
package/dist/_exports/ux.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/_exports/ux.ts"],"sourcesContent":["export {NonInteractiveError} from '../errors/NonInteractiveError.js'\nexport {\n boxen,\n type BoxenOptions,\n type Boxes,\n type CustomBorderStyle,\n type Spacing,\n} from '../ux/boxen.js'\nexport {colorizeJson} from '../ux/colorizeJson.js'\nexport {logSymbols} from '../ux/logSymbols.js'\nexport {\n checkbox,\n confirm,\n editor,\n expand,\n input,\n number,\n password,\n rawlist,\n search,\n select,\n Separator,\n} from '../ux/prompts.js'\nexport {\n spinner,\n type Spinner,\n type SpinnerInstance,\n type SpinnerOptions,\n spinnerPromise,\n type SpinnerPromiseOptions,\n} from '../ux/spinner.js'\nexport {getTimer} from '../ux/timer.js'\n"],"names":["NonInteractiveError","boxen","colorizeJson","logSymbols","checkbox","confirm","editor","expand","input","number","password","rawlist","search","select","Separator","spinner","spinnerPromise","getTimer"],"mappings":"AAAA,SAAQA,mBAAmB,QAAO,mCAAkC;AACpE,SACEC,KAAK,QAKA,iBAAgB;AACvB,SAAQC,YAAY,QAAO,wBAAuB;AAClD,SAAQC,UAAU,QAAO,sBAAqB;AAC9C,SACEC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,SAAS,QACJ,mBAAkB;AACzB,SACEC,OAAO,EAIPC,cAAc,QAET,mBAAkB;AACzB,SAAQC,QAAQ,QAAO,iBAAgB"}
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/ux.ts"],"sourcesContent":["export {NonInteractiveError} from '../errors/NonInteractiveError.js'\nexport {\n boxen,\n type BoxenOptions,\n type Boxes,\n type CustomBorderStyle,\n type Spacing,\n} from '../ux/boxen.js'\nexport {colorizeJson} from '../ux/colorizeJson.js'\nexport {createFlow, type Flow} from '../ux/flowOutput.js'\nexport {logSymbols} from '../ux/logSymbols.js'\nexport {\n checkbox,\n confirm,\n editor,\n expand,\n input,\n number,\n password,\n rawlist,\n search,\n select,\n Separator,\n} from '../ux/prompts.js'\nexport {\n spinner,\n type Spinner,\n type SpinnerInstance,\n type SpinnerOptions,\n spinnerPromise,\n type SpinnerPromiseOptions,\n} from '../ux/spinner.js'\nexport {getTimer} from '../ux/timer.js'\n"],"names":["NonInteractiveError","boxen","colorizeJson","createFlow","logSymbols","checkbox","confirm","editor","expand","input","number","password","rawlist","search","select","Separator","spinner","spinnerPromise","getTimer"],"mappings":"AAAA,SAAQA,mBAAmB,QAAO,mCAAkC;AACpE,SACEC,KAAK,QAKA,iBAAgB;AACvB,SAAQC,YAAY,QAAO,wBAAuB;AAClD,SAAQC,UAAU,QAAkB,sBAAqB;AACzD,SAAQC,UAAU,QAAO,sBAAqB;AAC9C,SACEC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,SAAS,QACJ,mBAAkB;AACzB,SACEC,OAAO,EAIPC,cAAc,QAET,mBAAkB;AACzB,SAAQC,QAAQ,QAAO,iBAAgB"}
|
|
@@ -23,10 +23,8 @@ export const _internals = {
|
|
|
23
23
|
// server) takes precedence and must bypass the process-wide cache entirely:
|
|
24
24
|
// reading the cache would leak another invocation's token, and writing it
|
|
25
25
|
// would leak this one's.
|
|
26
|
-
const
|
|
27
|
-
if (
|
|
28
|
-
return contextToken;
|
|
29
|
-
}
|
|
26
|
+
const context = getCliExecutionContext();
|
|
27
|
+
if (context) return context.token;
|
|
30
28
|
const cached = getCachedToken();
|
|
31
29
|
if (cached !== undefined) {
|
|
32
30
|
return cached;
|
|
@@ -52,6 +50,7 @@ const cliUserConfigSchema = {
|
|
|
52
50
|
* @param value - The value to set
|
|
53
51
|
* @internal
|
|
54
52
|
*/ export function setCliUserConfig(prop, value) {
|
|
53
|
+
assertCanAccessHostUserConfig();
|
|
55
54
|
const config = readConfig();
|
|
56
55
|
const result = cliUserConfigSchema[prop].safeParse(value);
|
|
57
56
|
if (!result.success) {
|
|
@@ -87,6 +86,7 @@ const cliUserConfigSchema = {
|
|
|
87
86
|
* @param prop - The property to get the value for
|
|
88
87
|
* @returns The value of the given property
|
|
89
88
|
*/ export function getCliUserConfig(prop) {
|
|
89
|
+
assertCanAccessHostUserConfig();
|
|
90
90
|
const config = readConfig();
|
|
91
91
|
const result = cliUserConfigSchema[prop].safeParse(config[prop]);
|
|
92
92
|
if (!result.success) {
|
|
@@ -111,6 +111,7 @@ const cliUserConfigSchema = {
|
|
|
111
111
|
* @returns A {@link ConfigStore} for the CLI config file
|
|
112
112
|
* @public
|
|
113
113
|
*/ export function getUserConfig() {
|
|
114
|
+
assertCanAccessHostUserConfig();
|
|
114
115
|
return {
|
|
115
116
|
get (key) {
|
|
116
117
|
const config = readConfig();
|
|
@@ -142,6 +143,11 @@ const cliUserConfigSchema = {
|
|
|
142
143
|
}
|
|
143
144
|
};
|
|
144
145
|
}
|
|
146
|
+
function assertCanAccessHostUserConfig() {
|
|
147
|
+
if (getCliExecutionContext()) {
|
|
148
|
+
throw new Error('Host CLI user configuration is unavailable during programmatic invocations');
|
|
149
|
+
}
|
|
150
|
+
}
|
|
145
151
|
/**
|
|
146
152
|
* Read the whole configuration from file system. If the file does not exist,
|
|
147
153
|
* is corrupt, or otherwise unreadable, an empty object is returned. This is
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/cli/cliUserConfig.ts"],"sourcesContent":["import {mkdirSync} from 'node:fs'\nimport {dirname, join as joinPath} from 'node:path'\n\nimport {z} from 'zod/mini'\n\nimport {debug} from '../../_exports/debug.js'\nimport {getCliExecutionContext} from '../../executionContext.js'\nimport {getSanityConfigDir} from '../../util/getSanityConfigDir.js'\nimport {readJsonFileSync} from '../../util/readJsonFileSync.js'\nimport {writeJsonFileSync} from '../../util/writeJsonFileSync.js'\nimport {clearCliTokenCache, getCachedToken, setCachedToken} from './cliTokenCache.js'\nimport {type ConfigStore} from './types/cliConfig.js'\n\n// Re-export so existing consumers don't break\nexport {clearCliTokenCache} from './cliTokenCache.js'\n\n// Only used for testing\nexport const _internals = {\n getCliUserConfig,\n}\n\n/**\n * Get the CLI authentication token from the environment or the config file\n *\n * @returns A promise that resolves to a CLI token, or undefined if no token is found\n * @internal\n */\nexport async function getCliToken(): Promise<string | undefined> {\n // A per-invocation execution context token (e.g. per-request from an MCP\n // server) takes precedence and must bypass the process-wide cache entirely:\n // reading the cache would leak another invocation's token, and writing it\n // would leak this one's.\n const contextToken = getCliExecutionContext()?.token\n if (contextToken) {\n return contextToken\n }\n\n const cached = getCachedToken()\n if (cached !== undefined) {\n return cached\n }\n\n const token = process.env.SANITY_AUTH_TOKEN\n if (token) {\n const trimmed = token.trim()\n setCachedToken(trimmed)\n return trimmed\n }\n\n const configToken = _internals.getCliUserConfig('authToken')\n setCachedToken(configToken)\n return configToken\n}\nconst cliUserConfigSchema = {\n authToken: z.optional(z.string()),\n}\n\n/**\n * Set the config value for the given property.\n * Validates that the passed value adheres to the defined CLI config schema.\n *\n * @param prop - The property to set the value for\n * @param value - The value to set\n * @internal\n */\nexport function setCliUserConfig(prop: 'authToken', value: string | undefined): void {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(value)\n if (!result.success) {\n const message = result.error.issues\n .map(({message, path}) => `[${path.join('.')}] ${message}`)\n .join('\\n')\n\n throw new Error(`Invalid value for config property \"${prop}\": ${message}`)\n }\n\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n\n // When value is undefined, explicitly delete the key rather than relying\n // on JSON.stringify silently dropping undefined values.\n if (value === undefined) {\n const {[prop]: _, ...rest} = config\n writeJsonFileSync(configPath, rest, {pretty: true})\n } else {\n writeJsonFileSync(configPath, {...config, [prop]: value}, {pretty: true})\n }\n\n // Invalidate the in-process token cache so subsequent getCliToken() calls\n // pick up the new value from disk.\n clearCliTokenCache()\n}\n\n/**\n * Get the config value for the given property\n *\n * @param prop - The property to get the value for\n * @returns The value of the given property\n */\nexport function getCliUserConfig(prop: 'authToken'): string | undefined {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(config[prop])\n if (!result.success) {\n debug('Ignoring invalid stored value for \"%s\", returning undefined', prop)\n return undefined\n }\n\n return result.data\n}\n\n/**\n * Get a key-value store backed by the CLI user configuration file\n * (`~/.config/sanity/config.json`).\n *\n * Each call to `get`, `set`, or `delete` performs a full synchronous\n * read-modify-write cycle. This is intentional: sync I/O prevents\n * intra-process race conditions that occurred with the previous async\n * (configstore-backed) implementation.\n *\n * Note: there is no file-level locking, so concurrent writes from\n * separate CLI processes could still conflict. In practice this is\n * unlikely since CLI config writes are rare and user-initiated.\n *\n * @returns A {@link ConfigStore} for the CLI config file\n * @public\n */\nexport function getUserConfig(): ConfigStore {\n return {\n get(key: string): unknown {\n const config = readConfig()\n return config[key]\n },\n\n set(key: string, value: unknown): void {\n const config = readConfig()\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n writeJsonFileSync(configPath, {...config, [key]: value}, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n\n // No mkdirSync needed: if readConfig() succeeded the directory already exists.\n delete(key: string): void {\n const config = readConfig()\n if (!(key in config)) return\n const {[key]: _, ...rest} = config\n writeJsonFileSync(getCliUserConfigPath(), rest, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n }\n}\n\n/**\n * Read the whole configuration from file system. If the file does not exist,\n * is corrupt, or otherwise unreadable, an empty object is returned. This is\n * intentional: the config only holds recoverable data (auth tokens, telemetry\n * consent) so silently resetting is preferable to blocking the user.\n *\n * @returns The whole CLI configuration.\n * @internal\n */\nfunction readConfig(): Record<string, unknown> {\n try {\n const config = readJsonFileSync(getCliUserConfigPath())\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error('Invalid config file - expected an object')\n }\n return config\n } catch (err: unknown) {\n debug('Failed to read CLI config file: %s', err instanceof Error ? err.message : `${err}`)\n return {}\n }\n}\n\n/**\n * Get the file system location for the CLI user configuration file.\n * Takes into account the active environment (staging vs production).\n * The file is located in the user's home directory under the `.config` directory.\n *\n * @returns The path to the CLI configuration file.\n * @internal\n */\nfunction getCliUserConfigPath() {\n return process.env.SANITY_CLI_CONFIG_PATH || joinPath(getSanityConfigDir(), 'config.json')\n}\n"],"names":["mkdirSync","dirname","join","joinPath","z","debug","getCliExecutionContext","getSanityConfigDir","readJsonFileSync","writeJsonFileSync","clearCliTokenCache","getCachedToken","setCachedToken","_internals","getCliUserConfig","getCliToken","contextToken","token","cached","undefined","process","env","SANITY_AUTH_TOKEN","trimmed","trim","configToken","cliUserConfigSchema","authToken","optional","string","setCliUserConfig","prop","value","config","readConfig","result","safeParse","success","message","error","issues","map","path","Error","configPath","getCliUserConfigPath","recursive","_","rest","pretty","data","getUserConfig","get","key","set","delete","Array","isArray","err","SANITY_CLI_CONFIG_PATH"],"mappings":"AAAA,SAAQA,SAAS,QAAO,UAAS;AACjC,SAAQC,OAAO,EAAEC,QAAQC,QAAQ,QAAO,YAAW;AAEnD,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,KAAK,QAAO,0BAAyB;AAC7C,SAAQC,sBAAsB,QAAO,4BAA2B;AAChE,SAAQC,kBAAkB,QAAO,mCAAkC;AACnE,SAAQC,gBAAgB,QAAO,iCAAgC;AAC/D,SAAQC,iBAAiB,QAAO,kCAAiC;AACjE,SAAQC,kBAAkB,EAAEC,cAAc,EAAEC,cAAc,QAAO,qBAAoB;AAGrF,8CAA8C;AAC9C,SAAQF,kBAAkB,QAAO,qBAAoB;AAErD,wBAAwB;AACxB,OAAO,MAAMG,aAAa;IACxBC;AACF,EAAC;AAED;;;;;CAKC,GACD,OAAO,eAAeC;IACpB,yEAAyE;IACzE,4EAA4E;IAC5E,0EAA0E;IAC1E,yBAAyB;IACzB,MAAMC,eAAeV,0BAA0BW;IAC/C,IAAID,cAAc;QAChB,OAAOA;IACT;IAEA,MAAME,SAASP;IACf,IAAIO,WAAWC,WAAW;QACxB,OAAOD;IACT;IAEA,MAAMD,QAAQG,QAAQC,GAAG,CAACC,iBAAiB;IAC3C,IAAIL,OAAO;QACT,MAAMM,UAAUN,MAAMO,IAAI;QAC1BZ,eAAeW;QACf,OAAOA;IACT;IAEA,MAAME,cAAcZ,WAAWC,gBAAgB,CAAC;IAChDF,eAAea;IACf,OAAOA;AACT;AACA,MAAMC,sBAAsB;IAC1BC,WAAWvB,EAAEwB,QAAQ,CAACxB,EAAEyB,MAAM;AAChC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,iBAAiBC,IAAiB,EAAEC,KAAyB;IAC3E,MAAMC,SAAS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ACf,MAAMU,aAAaC;YACnB7C,UAAUC,QAAQ2C,aAAa;gBAACE,WAAW;YAAI;YAC/CrC,kBAAkBmC,YAAY;gBAAC,GAAGX,MAAM;gBAAE,CAACoB,IAAI,EAAErB;YAAK,GAAG;gBAACiB,QAAQ;YAAI;YACtE,IAAII,QAAQ,aAAa3C;QAC3B;QAEA,+EAA+E;QAC/E6C,QAAOF,GAAW;YAChB,MAAMpB,SAASC;YACf,IAAI,CAAEmB,CAAAA,OAAOpB,MAAK,GAAI;YACtB,MAAM,EAAC,CAACoB,IAAI,EAAEN,CAAC,EAAE,GAAGC,MAAK,GAAGf;YAC5BxB,kBAAkBoC,wBAAwBG,MAAM;gBAACC,QAAQ;YAAI;YAC7D,IAAII,QAAQ,aAAa3C;QAC3B;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,SAASwB;IACP,IAAI;QACF,MAAMD,SAASzB,iBAAiBqC;QAChC,IAAI,CAACZ,UAAU,OAAOA,WAAW,YAAYuB,MAAMC,OAAO,CAACxB,SAAS;YAClE,MAAM,IAAIU,MAAM;QAClB;QACA,OAAOV;IACT,EAAE,OAAOyB,KAAc;QACrBrD,MAAM,sCAAsCqD,eAAef,QAAQe,IAAIpB,OAAO,GAAG,GAAGoB,KAAK;QACzF,OAAO,CAAC;IACV;AACF;AAEA;;;;;;;CAOC,GACD,SAASb;IACP,OAAOzB,QAAQC,GAAG,CAACsC,sBAAsB,IAAIxD,SAASI,sBAAsB;AAC9E"}
|
|
1
|
+
{"version":3,"sources":["../../../src/config/cli/cliUserConfig.ts"],"sourcesContent":["import {mkdirSync} from 'node:fs'\nimport {dirname, join as joinPath} from 'node:path'\n\nimport {z} from 'zod/mini'\n\nimport {debug} from '../../_exports/debug.js'\nimport {getCliExecutionContext} from '../../executionContext.js'\nimport {getSanityConfigDir} from '../../util/getSanityConfigDir.js'\nimport {readJsonFileSync} from '../../util/readJsonFileSync.js'\nimport {writeJsonFileSync} from '../../util/writeJsonFileSync.js'\nimport {clearCliTokenCache, getCachedToken, setCachedToken} from './cliTokenCache.js'\nimport {type ConfigStore} from './types/cliConfig.js'\n\n// Re-export so existing consumers don't break\nexport {clearCliTokenCache} from './cliTokenCache.js'\n\n// Only used for testing\nexport const _internals = {\n getCliUserConfig,\n}\n\n/**\n * Get the CLI authentication token from the environment or the config file\n *\n * @returns A promise that resolves to a CLI token, or undefined if no token is found\n * @internal\n */\nexport async function getCliToken(): Promise<string | undefined> {\n // A per-invocation execution context token (e.g. per-request from an MCP\n // server) takes precedence and must bypass the process-wide cache entirely:\n // reading the cache would leak another invocation's token, and writing it\n // would leak this one's.\n const context = getCliExecutionContext()\n if (context) return context.token\n\n const cached = getCachedToken()\n if (cached !== undefined) {\n return cached\n }\n\n const token = process.env.SANITY_AUTH_TOKEN\n if (token) {\n const trimmed = token.trim()\n setCachedToken(trimmed)\n return trimmed\n }\n\n const configToken = _internals.getCliUserConfig('authToken')\n setCachedToken(configToken)\n return configToken\n}\nconst cliUserConfigSchema = {\n authToken: z.optional(z.string()),\n}\n\n/**\n * Set the config value for the given property.\n * Validates that the passed value adheres to the defined CLI config schema.\n *\n * @param prop - The property to set the value for\n * @param value - The value to set\n * @internal\n */\nexport function setCliUserConfig(prop: 'authToken', value: string | undefined): void {\n assertCanAccessHostUserConfig()\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(value)\n if (!result.success) {\n const message = result.error.issues\n .map(({message, path}) => `[${path.join('.')}] ${message}`)\n .join('\\n')\n\n throw new Error(`Invalid value for config property \"${prop}\": ${message}`)\n }\n\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n\n // When value is undefined, explicitly delete the key rather than relying\n // on JSON.stringify silently dropping undefined values.\n if (value === undefined) {\n const {[prop]: _, ...rest} = config\n writeJsonFileSync(configPath, rest, {pretty: true})\n } else {\n writeJsonFileSync(configPath, {...config, [prop]: value}, {pretty: true})\n }\n\n // Invalidate the in-process token cache so subsequent getCliToken() calls\n // pick up the new value from disk.\n clearCliTokenCache()\n}\n\n/**\n * Get the config value for the given property\n *\n * @param prop - The property to get the value for\n * @returns The value of the given property\n */\nexport function getCliUserConfig(prop: 'authToken'): string | undefined {\n assertCanAccessHostUserConfig()\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(config[prop])\n if (!result.success) {\n debug('Ignoring invalid stored value for \"%s\", returning undefined', prop)\n return undefined\n }\n\n return result.data\n}\n\n/**\n * Get a key-value store backed by the CLI user configuration file\n * (`~/.config/sanity/config.json`).\n *\n * Each call to `get`, `set`, or `delete` performs a full synchronous\n * read-modify-write cycle. This is intentional: sync I/O prevents\n * intra-process race conditions that occurred with the previous async\n * (configstore-backed) implementation.\n *\n * Note: there is no file-level locking, so concurrent writes from\n * separate CLI processes could still conflict. In practice this is\n * unlikely since CLI config writes are rare and user-initiated.\n *\n * @returns A {@link ConfigStore} for the CLI config file\n * @public\n */\nexport function getUserConfig(): ConfigStore {\n assertCanAccessHostUserConfig()\n return {\n get(key: string): unknown {\n const config = readConfig()\n return config[key]\n },\n\n set(key: string, value: unknown): void {\n const config = readConfig()\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n writeJsonFileSync(configPath, {...config, [key]: value}, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n\n // No mkdirSync needed: if readConfig() succeeded the directory already exists.\n delete(key: string): void {\n const config = readConfig()\n if (!(key in config)) return\n const {[key]: _, ...rest} = config\n writeJsonFileSync(getCliUserConfigPath(), rest, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n }\n}\n\nfunction assertCanAccessHostUserConfig(): void {\n if (getCliExecutionContext()) {\n throw new Error('Host CLI user configuration is unavailable during programmatic invocations')\n }\n}\n\n/**\n * Read the whole configuration from file system. If the file does not exist,\n * is corrupt, or otherwise unreadable, an empty object is returned. This is\n * intentional: the config only holds recoverable data (auth tokens, telemetry\n * consent) so silently resetting is preferable to blocking the user.\n *\n * @returns The whole CLI configuration.\n * @internal\n */\nfunction readConfig(): Record<string, unknown> {\n try {\n const config = readJsonFileSync(getCliUserConfigPath())\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error('Invalid config file - expected an object')\n }\n return config\n } catch (err: unknown) {\n debug('Failed to read CLI config file: %s', err instanceof Error ? err.message : `${err}`)\n return {}\n }\n}\n\n/**\n * Get the file system location for the CLI user configuration file.\n * Takes into account the active environment (staging vs production).\n * The file is located in the user's home directory under the `.config` directory.\n *\n * @returns The path to the CLI configuration file.\n * @internal\n */\nfunction getCliUserConfigPath() {\n return process.env.SANITY_CLI_CONFIG_PATH || joinPath(getSanityConfigDir(), 'config.json')\n}\n"],"names":["mkdirSync","dirname","join","joinPath","z","debug","getCliExecutionContext","getSanityConfigDir","readJsonFileSync","writeJsonFileSync","clearCliTokenCache","getCachedToken","setCachedToken","_internals","getCliUserConfig","getCliToken","context","token","cached","undefined","process","env","SANITY_AUTH_TOKEN","trimmed","trim","configToken","cliUserConfigSchema","authToken","optional","string","setCliUserConfig","prop","value","assertCanAccessHostUserConfig","config","readConfig","result","safeParse","success","message","error","issues","map","path","Error","configPath","getCliUserConfigPath","recursive","_","rest","pretty","data","getUserConfig","get","key","set","delete","Array","isArray","err","SANITY_CLI_CONFIG_PATH"],"mappings":"AAAA,SAAQA,SAAS,QAAO,UAAS;AACjC,SAAQC,OAAO,EAAEC,QAAQC,QAAQ,QAAO,YAAW;AAEnD,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,KAAK,QAAO,0BAAyB;AAC7C,SAAQC,sBAAsB,QAAO,4BAA2B;AAChE,SAAQC,kBAAkB,QAAO,mCAAkC;AACnE,SAAQC,gBAAgB,QAAO,iCAAgC;AAC/D,SAAQC,iBAAiB,QAAO,kCAAiC;AACjE,SAAQC,kBAAkB,EAAEC,cAAc,EAAEC,cAAc,QAAO,qBAAoB;AAGrF,8CAA8C;AAC9C,SAAQF,kBAAkB,QAAO,qBAAoB;AAErD,wBAAwB;AACxB,OAAO,MAAMG,aAAa;IAC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I;QACF,MAAMD,SAAS1B,iBAAiBsC;QAChC,IAAI,CAACZ,UAAU,OAAOA,WAAW,YAAYuB,MAAMC,OAAO,CAACxB,SAAS;YAClE,MAAM,IAAIU,MAAM;QAClB;QACA,OAAOV;IACT,EAAE,OAAOyB,KAAc;QACrBtD,MAAM,sCAAsCsD,eAAef,QAAQe,IAAIpB,OAAO,GAAG,GAAGoB,KAAK;QACzF,OAAO,CAAC;IACV;AACF;AAEA;;;;;;;CAOC,GACD,SAASb;IACP,OAAO1B,QAAQC,GAAG,CAACuC,sBAAsB,IAAIzD,SAASI,sBAAsB;AAC9E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/config/cli/types/cliConfig.ts"],"sourcesContent":["import {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\n\nimport {type UserViteConfig} from './userViteConfig'\n\nexport interface TypeGenConfig {\n formatGeneratedCode: boolean\n generates: string\n overloadClientMethods: boolean\n path: string | string[]\n schema: string\n}\n\n/**\n * Dashboard visibility an application can declare. Mirrors Brett's canonical\n * `VISIBILITIES` — the source of truth lives in the application service.\n * @public\n */\nexport const APP_VISIBILITIES = ['default', 'unlisted', 'disabled'] as const\n/** @public */\nexport type AppVisibility = (typeof APP_VISIBILITIES)[number]\n\n/**\n * @public\n */\nexport interface CliConfig {\n /** The project ID and dataset the Sanity CLI should use to run its commands */\n api?: {\n dataset?: string\n projectId?: string\n }\n\n /** Configuration for custom Sanity apps built with the App SDK */\n app?: {\n /** The entrypoint for your custom app. By default, `src/App.tsx` */\n entry?: string\n
|
|
1
|
+
{"version":3,"sources":["../../../../src/config/cli/types/cliConfig.ts"],"sourcesContent":["import {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\n\nimport {type UserViteConfig} from './userViteConfig'\n\nexport interface TypeGenConfig {\n formatGeneratedCode: boolean\n generates: string\n overloadClientMethods: boolean\n path: string | string[]\n schema: string\n}\n\n/**\n * Dashboard visibility an application can declare. Mirrors Brett's canonical\n * `VISIBILITIES` — the source of truth lives in the application service.\n * @public\n */\nexport const APP_VISIBILITIES = ['default', 'unlisted', 'disabled'] as const\n/** @public */\nexport type AppVisibility = (typeof APP_VISIBILITIES)[number]\n\n/**\n * @public\n */\nexport interface CliConfig {\n /** The project ID and dataset the Sanity CLI should use to run its commands */\n api?: {\n dataset?: string\n projectId?: string\n }\n\n /** Configuration for custom Sanity apps built with the App SDK */\n app?: {\n /** The entrypoint for your custom app. By default, `src/App.tsx` */\n entry?: string\n /**\n * Path to an icon file relative to project root.\n * The file must be an SVG.\n */\n icon?: string\n /** @deprecated Use deployment.appId */\n id?: string\n /** The ID for the Sanity organization that manages this application */\n organizationId?: string\n /** The title of the custom app, as it is seen in Dashboard UI */\n title?: string\n /** Dashboard visibility of the application. Defaults to `default`. */\n visibility?: AppVisibility\n }\n\n /** @deprecated Use deployment.autoUpdates */\n autoUpdates?: boolean\n\n /** Options for custom app and Studio deployments */\n deployment?: {\n /**\n * The ID for your custom app or Studio. Generated when deploying your app or Studio for the first time.\n * Get your app ID by either:\n * 1. Checking the output of `sanity deploy`, or\n * 2. Checking your project’s Studio tab at https://sanity.io/manage\n *\n * @remarks This is required for all custom app deployments, and for Studios opting in to fine grained version control.\n * {@link https://www.sanity.io/docs/studio/latest-version-of-sanity#k0896ed4574b7}\n */\n appId?: string\n /**\n * Enable automatic updates for your Studio or custom app’s Sanity dependencies.\n * {@link https://www.sanity.io/docs/studio/latest-version-of-sanity}\n */\n autoUpdates?: boolean\n }\n\n /** Define the GraphQL APIs that the CLI can deploy and interact with */\n graphql?: Array<{\n filterSuffix?: string\n generation?: 'gen1' | 'gen2' | 'gen3'\n id?: string\n nonNullDocumentFields?: boolean\n playground?: boolean\n source?: string\n tag?: string\n workspace?: string\n }>\n\n /** Configuration for the Media Library */\n mediaLibrary?: {\n /** The path to the Media Library aspects directory. When using the CLI to manage aspects, this is the directory they will be read from and written to. */\n aspectsPath?: string\n }\n\n /** Contains the property `basePath` which lets you change the top-level slug for the Studio. You typically need to set this if you embed the Studio in another application where it is one of many routes. Defaults to an empty string. */\n project?: {\n basePath?: string\n }\n\n /** Configuration options for React Compiler */\n reactCompiler?: boolean | ReactCompilerConfig\n\n /** Wraps the Studio in \\<React.StrictMode\\> root to aid in flagging potential problems related to concurrent features (startTransition, useTransition, useDeferredValue, Suspense). Can also be enabled by setting SANITY_STUDIO_REACT_STRICT_MODE=\"true\"|\"false\". It only applies to sanity dev in development mode and is ignored in sanity build and in production. Defaults to true. */\n reactStrictMode?: boolean\n\n /**\n * Configuration for schema extraction (`sanity schema extract`)\n */\n schemaExtraction?: {\n /**\n * Enable schema extraction as part of sanity dev and sanity build\n */\n enabled?: boolean\n\n /**\n * When true, schema fields marked as required will be non-optional in the output.\n * Defaults to `false`\n */\n enforceRequiredFields?: boolean\n\n /**\n * Output path for the extracted schema file.\n * Defaults to `schema.json` in the working directory.\n */\n path?: string\n\n /**\n * Additional glob patterns to watch for schema changes in watch mode.\n * These extend the default patterns:\n * - `sanity.config.{js,jsx,ts,tsx,mjs}`\n * - `schema*\\/**\\/*.{js,jsx,ts,tsx,mjs}`\n */\n watchPatterns?: string[]\n\n /**\n * The name of the workspace to generate a schema for. Required if your Sanity project has more than one\n * workspace.\n */\n workspace?: string\n }\n\n /** Defines the hostname and port that the development server should run on. hostname defaults to localhost, and port to 3333. */\n server?: {\n hostname?: string\n port?: number\n }\n\n /** @deprecated Use deployment.appId */\n studioHost?: string\n\n /**\n * Configuration for Sanity typegen\n */\n typegen?: Partial<TypeGenConfig> & {\n /**\n * Enable typegen as part of sanity dev and sanity build.\n * When enabled, types are generated on startup and when files change.\n * Defaults to `false`\n */\n enabled?: boolean\n }\n\n /**\n * Enable Vite's experimental bundled dev mode for `sanity dev`. This serves bundled\n * files during development, which can speed up startup and reloads for large projects.\n * Defaults to `false`.\n *\n * Unstable: may change or be removed without notice while the underlying Vite\n * feature (`experimental.bundledDev`) is experimental.\n * {@link https://vite.dev/guide/rolldown#full-bundle-mode}\n */\n unstable_bundledDev?: boolean\n\n /** Exposes the default Vite configuration for custom apps and the Studio so it can be changed and extended. */\n vite?: UserViteConfig\n}\n\n/**\n * A raw key-value store for CLI user configuration.\n * Unlike the typed `getCliUserConfig`/`setCliUserConfig`, this operates on\n * arbitrary keys without schema validation.\n *\n * @public\n */\nexport interface ConfigStore {\n /** Remove a key from the config file. */\n delete: (key: string) => void\n /** Read a value by key. Returns `undefined` if the key does not exist. */\n get: (key: string) => unknown\n /** Write a value by key, merging it into the existing config. */\n set: (key: string, value: unknown) => void\n}\n"],"names":["APP_VISIBILITIES"],"mappings":"AAYA;;;;CAIC,GACD,OAAO,MAAMA,mBAAmB;IAAC;IAAW;IAAY;CAAW,CAAS"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ux } from '@oclif/core'; // TODO: should telemetry helpers be importing oclif? cli-build imports this... we should remove this.
|
|
2
|
+
import { getCliExecutionContext } from '../executionContext.js';
|
|
2
3
|
import { noopLogger } from './noopTelemetry.js';
|
|
3
4
|
/**
|
|
4
5
|
* @public
|
|
@@ -12,6 +13,9 @@ function getState() {
|
|
|
12
13
|
* @public
|
|
13
14
|
*/ // TODO: change this API so that it accepts a channel for passing warnings through, otherwise this is pumped through OCLIF UX via singleton
|
|
14
15
|
export function getCliTelemetry() {
|
|
16
|
+
// Programmatic invocations must neither consume nor replace telemetry state
|
|
17
|
+
// owned by the embedding host.
|
|
18
|
+
if (getCliExecutionContext()) return noopLogger;
|
|
15
19
|
const state = getState();
|
|
16
20
|
// This should never happen, but if it does, we return a noop logger to avoid errors.
|
|
17
21
|
if (!state) {
|
|
@@ -35,6 +39,7 @@ export function getCliTelemetry() {
|
|
|
35
39
|
* for real command errors (not user aborts).
|
|
36
40
|
* @internal
|
|
37
41
|
*/ export function reportCliTraceError(error) {
|
|
42
|
+
if (getCliExecutionContext()) return;
|
|
38
43
|
getState()?.reportTraceError?.(error);
|
|
39
44
|
}
|
|
40
45
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/telemetry/getCliTelemetry.ts"],"sourcesContent":["import {ux} from '@oclif/core' // TODO: should telemetry helpers be importing oclif? cli-build imports this... we should remove this.\n\nimport {noopLogger} from './noopTelemetry.js'\nimport {type CLITelemetryStore} from './types.js'\n\n/**\n * @public\n * Symbol used to store CLI telemetry state on globalThis.\n * Use the accessor functions instead of accessing this directly.\n */\nexport const CLI_TELEMETRY_SYMBOL = Symbol.for('sanity.cli.telemetry')\n\ntype TraceErrorReporter = (error: Error) => void\n\ninterface CliTelemetryState {\n logger: CLITelemetryStore\n\n reportTraceError?: TraceErrorReporter\n}\n\ntype GlobalWithTelemetry = typeof globalThis & {\n [CLI_TELEMETRY_SYMBOL]?: CliTelemetryState\n}\n\nfunction getState(): CliTelemetryState | undefined {\n return (globalThis as GlobalWithTelemetry)[CLI_TELEMETRY_SYMBOL]\n}\n\n/**\n * @public\n */\n// TODO: change this API so that it accepts a channel for passing warnings through, otherwise this is pumped through OCLIF UX via singleton\nexport function getCliTelemetry(): CLITelemetryStore {\n const state = getState()\n // This should never happen, but if it does, we return a noop logger to avoid errors.\n if (!state) {\n ux.warn('CLI telemetry not initialized, returning noop logger')\n return noopLogger\n }\n\n return state.logger\n}\n\n/**\n * Sets the global CLI telemetry state.\n * @internal\n */\nexport function setCliTelemetry(\n telemetry: CLITelemetryStore,\n options?: {reportTraceError?: TraceErrorReporter},\n): void {\n ;(globalThis as GlobalWithTelemetry)[CLI_TELEMETRY_SYMBOL] = {\n logger: telemetry,\n reportTraceError: options?.reportTraceError,\n }\n}\n\n/**\n * Reports an error to the CLI command trace. Called from SanityCommand.catch()\n * for real command errors (not user aborts).\n * @internal\n */\nexport function reportCliTraceError(error: Error): void {\n getState()?.reportTraceError?.(error)\n}\n\n/**\n * Clears the global CLI telemetry store.\n * @internal\n */\nexport function clearCliTelemetry(): void {\n const global = globalThis as GlobalWithTelemetry\n delete global[CLI_TELEMETRY_SYMBOL]\n}\n"],"names":["ux","noopLogger","CLI_TELEMETRY_SYMBOL","Symbol","for","getState","globalThis","getCliTelemetry","state","warn","logger","setCliTelemetry","telemetry","options","reportTraceError","reportCliTraceError","error","clearCliTelemetry","global"],"mappings":"AAAA,SAAQA,EAAE,QAAO,cAAa,CAAC,sGAAsG;AAErI,SAAQC,UAAU,QAAO,qBAAoB;AAG7C;;;;CAIC,GACD,OAAO,MAAMC,uBAAuBC,OAAOC,GAAG,CAAC,wBAAuB;AActE,SAASC;IACP,OAAO,AAACC,UAAkC,CAACJ,qBAAqB;AAClE;AAEA;;CAEC,GACD,2IAA2I;AAC3I,OAAO,SAASK;IACd,
|
|
1
|
+
{"version":3,"sources":["../../src/telemetry/getCliTelemetry.ts"],"sourcesContent":["import {ux} from '@oclif/core' // TODO: should telemetry helpers be importing oclif? cli-build imports this... we should remove this.\n\nimport {getCliExecutionContext} from '../executionContext.js'\nimport {noopLogger} from './noopTelemetry.js'\nimport {type CLITelemetryStore} from './types.js'\n\n/**\n * @public\n * Symbol used to store CLI telemetry state on globalThis.\n * Use the accessor functions instead of accessing this directly.\n */\nexport const CLI_TELEMETRY_SYMBOL = Symbol.for('sanity.cli.telemetry')\n\ntype TraceErrorReporter = (error: Error) => void\n\ninterface CliTelemetryState {\n logger: CLITelemetryStore\n\n reportTraceError?: TraceErrorReporter\n}\n\ntype GlobalWithTelemetry = typeof globalThis & {\n [CLI_TELEMETRY_SYMBOL]?: CliTelemetryState\n}\n\nfunction getState(): CliTelemetryState | undefined {\n return (globalThis as GlobalWithTelemetry)[CLI_TELEMETRY_SYMBOL]\n}\n\n/**\n * @public\n */\n// TODO: change this API so that it accepts a channel for passing warnings through, otherwise this is pumped through OCLIF UX via singleton\nexport function getCliTelemetry(): CLITelemetryStore {\n // Programmatic invocations must neither consume nor replace telemetry state\n // owned by the embedding host.\n if (getCliExecutionContext()) return noopLogger\n\n const state = getState()\n // This should never happen, but if it does, we return a noop logger to avoid errors.\n if (!state) {\n ux.warn('CLI telemetry not initialized, returning noop logger')\n return noopLogger\n }\n\n return state.logger\n}\n\n/**\n * Sets the global CLI telemetry state.\n * @internal\n */\nexport function setCliTelemetry(\n telemetry: CLITelemetryStore,\n options?: {reportTraceError?: TraceErrorReporter},\n): void {\n ;(globalThis as GlobalWithTelemetry)[CLI_TELEMETRY_SYMBOL] = {\n logger: telemetry,\n reportTraceError: options?.reportTraceError,\n }\n}\n\n/**\n * Reports an error to the CLI command trace. Called from SanityCommand.catch()\n * for real command errors (not user aborts).\n * @internal\n */\nexport function reportCliTraceError(error: Error): void {\n if (getCliExecutionContext()) return\n getState()?.reportTraceError?.(error)\n}\n\n/**\n * Clears the global CLI telemetry store.\n * @internal\n */\nexport function clearCliTelemetry(): void {\n const global = globalThis as GlobalWithTelemetry\n delete global[CLI_TELEMETRY_SYMBOL]\n}\n"],"names":["ux","getCliExecutionContext","noopLogger","CLI_TELEMETRY_SYMBOL","Symbol","for","getState","globalThis","getCliTelemetry","state","warn","logger","setCliTelemetry","telemetry","options","reportTraceError","reportCliTraceError","error","clearCliTelemetry","global"],"mappings":"AAAA,SAAQA,EAAE,QAAO,cAAa,CAAC,sGAAsG;AAErI,SAAQC,sBAAsB,QAAO,yBAAwB;AAC7D,SAAQC,UAAU,QAAO,qBAAoB;AAG7C;;;;CAIC,GACD,OAAO,MAAMC,uBAAuBC,OAAOC,GAAG,CAAC,wBAAuB;AActE,SAASC;IACP,OAAO,AAACC,UAAkC,CAACJ,qBAAqB;AAClE;AAEA;;CAEC,GACD,2IAA2I;AAC3I,OAAO,SAASK;IACd,4EAA4E;IAC5E,+BAA+B;IAC/B,IAAIP,0BAA0B,OAAOC;IAErC,MAAMO,QAAQH;IACd,qFAAqF;IACrF,IAAI,CAACG,OAAO;QACVT,GAAGU,IAAI,CAAC;QACR,OAAOR;IACT;IAEA,OAAOO,MAAME,MAAM;AACrB;AAEA;;;CAGC,GACD,OAAO,SAASC,gBACdC,SAA4B,EAC5BC,OAAiD;;IAE/CP,UAAkC,CAACJ,qBAAqB,GAAG;QAC3DQ,QAAQE;QACRE,kBAAkBD,SAASC;IAC7B;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,KAAY;IAC9C,IAAIhB,0BAA0B;IAC9BK,YAAYS,mBAAmBE;AACjC;AAEA;;;CAGC,GACD,OAAO,SAASC;IACd,MAAMC,SAASZ;IACf,OAAOY,MAAM,CAAChB,qBAAqB;AACrC"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { styleText } from 'node:util';
|
|
2
|
+
import wrapAnsi from 'wrap-ansi';
|
|
3
|
+
import { isInteractive } from '../util/isInteractive.js';
|
|
4
|
+
import { spinner } from './spinner.js';
|
|
5
|
+
const SPINNER_FRAMES = [
|
|
6
|
+
'◐ ',
|
|
7
|
+
'◓ ',
|
|
8
|
+
'◑ ',
|
|
9
|
+
'◒ '
|
|
10
|
+
];
|
|
11
|
+
const RAIL_PREFIX_WIDTH = 3;
|
|
12
|
+
const MAX_RENDERED_LINE_WIDTH = 79;
|
|
13
|
+
function rail(glyph) {
|
|
14
|
+
return styleText('gray', glyph);
|
|
15
|
+
}
|
|
16
|
+
function wrapText(text) {
|
|
17
|
+
const terminalWidth = process.stdout.isTTY && Number.isFinite(process.stdout.columns) && process.stdout.columns > 0 ? process.stdout.columns : MAX_RENDERED_LINE_WIDTH + 1;
|
|
18
|
+
const renderedWidth = Math.min(terminalWidth - 1, MAX_RENDERED_LINE_WIDTH);
|
|
19
|
+
const width = Math.max(renderedWidth - RAIL_PREFIX_WIDTH, 1);
|
|
20
|
+
return wrapAnsi(text, width, {
|
|
21
|
+
hard: false,
|
|
22
|
+
wordWrap: true
|
|
23
|
+
}).split('\n');
|
|
24
|
+
}
|
|
25
|
+
function writeRailed(log, glyph, text) {
|
|
26
|
+
for (const [index, line] of wrapText(text).entries()){
|
|
27
|
+
const marker = index === 0 && glyph === '◆' ? styleText('green', glyph) : rail(index === 0 ? glyph : '│');
|
|
28
|
+
log(`${marker} ${line}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function writeStderr(message = '') {
|
|
32
|
+
process.stderr.write(`${message}\n`);
|
|
33
|
+
}
|
|
34
|
+
function isTerminalControl(character) {
|
|
35
|
+
const codePoint = character.codePointAt(0);
|
|
36
|
+
return codePoint !== undefined && (codePoint <= 0x1f || codePoint >= 0x7f && codePoint <= 0x9f);
|
|
37
|
+
}
|
|
38
|
+
function isSafeTerminalLink(url) {
|
|
39
|
+
if ([
|
|
40
|
+
...url
|
|
41
|
+
].some((character)=>isTerminalControl(character))) return false;
|
|
42
|
+
try {
|
|
43
|
+
const protocol = new URL(url).protocol;
|
|
44
|
+
return protocol === 'http:' || protocol === 'https:';
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function encodeTerminalControls(value) {
|
|
50
|
+
return [
|
|
51
|
+
...value
|
|
52
|
+
].map((character)=>isTerminalControl(character) ? encodeURIComponent(character) : character).join('');
|
|
53
|
+
}
|
|
54
|
+
function terminalLink(url) {
|
|
55
|
+
const sanitizedUrl = encodeTerminalControls(url);
|
|
56
|
+
if (!process.stdout.isTTY || sanitizedUrl !== url || !isSafeTerminalLink(url)) {
|
|
57
|
+
return sanitizedUrl;
|
|
58
|
+
}
|
|
59
|
+
return `\u001B]8;;${url}\u0007${styleText([
|
|
60
|
+
'cyan',
|
|
61
|
+
'underline'
|
|
62
|
+
], url)}\u001B]8;;\u0007`;
|
|
63
|
+
}
|
|
64
|
+
/** Create a {@link Flow} that writes rail lines through `log`. */ export function createFlow(log) {
|
|
65
|
+
return {
|
|
66
|
+
command (command) {
|
|
67
|
+
log(`${rail('│')} ${styleText('cyan', encodeTerminalControls(command))}`);
|
|
68
|
+
},
|
|
69
|
+
gap () {
|
|
70
|
+
log(rail('│'));
|
|
71
|
+
},
|
|
72
|
+
highlight (text) {
|
|
73
|
+
writeRailed(log, '◆', text);
|
|
74
|
+
},
|
|
75
|
+
intro (text) {
|
|
76
|
+
writeRailed(log, '┌', text);
|
|
77
|
+
},
|
|
78
|
+
line (text) {
|
|
79
|
+
writeRailed(log, '│', text);
|
|
80
|
+
},
|
|
81
|
+
link (url, options = {}) {
|
|
82
|
+
const label = options.label ? `${options.label} ` : '';
|
|
83
|
+
log(`${rail(options.outro ? '└' : '│')} ${label}${terminalLink(url)}`);
|
|
84
|
+
},
|
|
85
|
+
note (text) {
|
|
86
|
+
writeRailed(log, '●', text);
|
|
87
|
+
},
|
|
88
|
+
outro (text) {
|
|
89
|
+
writeRailed(log, '└', text);
|
|
90
|
+
},
|
|
91
|
+
result (text) {
|
|
92
|
+
writeRailed(log, '◇', text);
|
|
93
|
+
},
|
|
94
|
+
spin (text) {
|
|
95
|
+
const sanitizedText = encodeTerminalControls(text);
|
|
96
|
+
if (!isInteractive() || !process.stderr.isTTY || !process.stderr.columns) {
|
|
97
|
+
writeRailed(writeStderr, '●', sanitizedText);
|
|
98
|
+
return {
|
|
99
|
+
fail: (failText)=>writeStderr(`${styleText('red', '✖')} ${encodeTerminalControls(failText)}`),
|
|
100
|
+
succeed: (successText)=>writeStderr(`${rail('◇')} ${encodeTerminalControls(successText)}`)
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
const spin = spinner({
|
|
104
|
+
spinner: {
|
|
105
|
+
frames: SPINNER_FRAMES,
|
|
106
|
+
interval: 120
|
|
107
|
+
},
|
|
108
|
+
text: sanitizedText
|
|
109
|
+
}).start();
|
|
110
|
+
return {
|
|
111
|
+
fail (failText) {
|
|
112
|
+
spin.stopAndPersist({
|
|
113
|
+
symbol: `${styleText('red', '✖')} `,
|
|
114
|
+
text: encodeTerminalControls(failText)
|
|
115
|
+
});
|
|
116
|
+
},
|
|
117
|
+
succeed (successText) {
|
|
118
|
+
spin.stopAndPersist({
|
|
119
|
+
symbol: `${rail('◇')} `,
|
|
120
|
+
text: encodeTerminalControls(successText)
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
//# sourceMappingURL=flowOutput.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/ux/flowOutput.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport wrapAnsi from 'wrap-ansi'\n\nimport {isInteractive} from '../util/isInteractive.js'\nimport {spinner, type SpinnerInstance} from './spinner.js'\n\ntype LogFn = (message?: string) => void\n\nconst SPINNER_FRAMES = ['◐ ', '◓ ', '◑ ', '◒ ']\nconst RAIL_PREFIX_WIDTH = 3\nconst MAX_RENDERED_LINE_WIDTH = 79\n\nfunction rail(glyph: string): string {\n return styleText('gray', glyph)\n}\n\nfunction wrapText(text: string): string[] {\n const terminalWidth =\n process.stdout.isTTY && Number.isFinite(process.stdout.columns) && process.stdout.columns > 0\n ? process.stdout.columns\n : MAX_RENDERED_LINE_WIDTH + 1\n const renderedWidth = Math.min(terminalWidth - 1, MAX_RENDERED_LINE_WIDTH)\n const width = Math.max(renderedWidth - RAIL_PREFIX_WIDTH, 1)\n return wrapAnsi(text, width, {hard: false, wordWrap: true}).split('\\n')\n}\n\nfunction writeRailed(log: LogFn, glyph: string, text: string): void {\n for (const [index, line] of wrapText(text).entries()) {\n const marker =\n index === 0 && glyph === '◆' ? styleText('green', glyph) : rail(index === 0 ? glyph : '│')\n log(`${marker} ${line}`)\n }\n}\n\nfunction writeStderr(message = ''): void {\n process.stderr.write(`${message}\\n`)\n}\n\nfunction isTerminalControl(character: string): boolean {\n const codePoint = character.codePointAt(0)\n return codePoint !== undefined && (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f))\n}\n\nfunction isSafeTerminalLink(url: string): boolean {\n if ([...url].some((character) => isTerminalControl(character))) return false\n try {\n const protocol = new URL(url).protocol\n return protocol === 'http:' || protocol === 'https:'\n } catch {\n return false\n }\n}\n\nfunction encodeTerminalControls(value: string): string {\n return [...value]\n .map((character) => (isTerminalControl(character) ? encodeURIComponent(character) : character))\n .join('')\n}\n\nfunction terminalLink(url: string): string {\n const sanitizedUrl = encodeTerminalControls(url)\n if (!process.stdout.isTTY || sanitizedUrl !== url || !isSafeTerminalLink(url)) {\n return sanitizedUrl\n }\n return `\\u001B]8;;${url}\\u0007${styleText(['cyan', 'underline'], url)}\\u001B]8;;\\u0007`\n}\n\nexport interface Flow {\n /** A copyable command belonging to the preceding action. */\n command(command: string): void\n /** `│` — a blank rail line separating steps. */\n gap(): void\n /** `◆` — an outcome the user should act on or remember. */\n highlight(text: string): void\n /** `┌` — opening line of the story. */\n intro(text: string): void\n /** `│ <text>` — a continuation line belonging to the previous step. */\n line(text: string): void\n /** A copy-safe URL. Long URLs are never hard-wrapped. */\n link(url: string, options?: {label?: string; outro?: boolean}): void\n /** `●` — a step happening behind the scenes, or a tip. */\n note(text: string): void\n /** `└` — closing line of the story. */\n outro(text: string): void\n /** `◇` — a completed step or produced value. */\n result(text: string): void\n /**\n * An in-flight step. Resolve it with `succeed(text)` (persists as a `◇` line) or `fail(text)`;\n * renders on stderr so machine-readable stdout is never corrupted.\n */\n spin(text: string): {fail(text: string): void; succeed(text: string): void}\n}\n\n/** Create a {@link Flow} that writes rail lines through `log`. */\nexport function createFlow(log: LogFn): Flow {\n return {\n command(command: string) {\n log(`${rail('│')} ${styleText('cyan', encodeTerminalControls(command))}`)\n },\n gap() {\n log(rail('│'))\n },\n highlight(text: string) {\n writeRailed(log, '◆', text)\n },\n intro(text: string) {\n writeRailed(log, '┌', text)\n },\n line(text: string) {\n writeRailed(log, '│', text)\n },\n link(url: string, options = {}) {\n const label = options.label ? `${options.label} ` : ''\n log(`${rail(options.outro ? '└' : '│')} ${label}${terminalLink(url)}`)\n },\n note(text: string) {\n writeRailed(log, '●', text)\n },\n outro(text: string) {\n writeRailed(log, '└', text)\n },\n result(text: string) {\n writeRailed(log, '◇', text)\n },\n spin(text: string) {\n const sanitizedText = encodeTerminalControls(text)\n if (!isInteractive() || !process.stderr.isTTY || !process.stderr.columns) {\n writeRailed(writeStderr, '●', sanitizedText)\n return {\n fail: (failText: string) =>\n writeStderr(`${styleText('red', '✖')} ${encodeTerminalControls(failText)}`),\n succeed: (successText: string) =>\n writeStderr(`${rail('◇')} ${encodeTerminalControls(successText)}`),\n }\n }\n\n const spin: SpinnerInstance = spinner({\n spinner: {frames: SPINNER_FRAMES, interval: 120},\n text: sanitizedText,\n }).start()\n return {\n fail(failText: string) {\n spin.stopAndPersist({\n symbol: `${styleText('red', '✖')} `,\n text: encodeTerminalControls(failText),\n })\n },\n succeed(successText: string) {\n spin.stopAndPersist({symbol: `${rail('◇')} `, text: encodeTerminalControls(successText)})\n },\n }\n },\n }\n}\n"],"names":["styleText","wrapAnsi","isInteractive","spinner","SPINNER_FRAMES","RAIL_PREFIX_WIDTH","MAX_RENDERED_LINE_WIDTH","rail","glyph","wrapText","text","terminalWidth","process","stdout","isTTY","Number","isFinite","columns","renderedWidth","Math","min","width","max","hard","wordWrap","split","writeRailed","log","index","line","entries","marker","writeStderr","message","stderr","write","isTerminalControl","character","codePoint","codePointAt","undefined","isSafeTerminalLink","url","some","protocol","URL","encodeTerminalControls","value","map","encodeURIComponent","join","terminalLink","sanitizedUrl","createFlow","command","gap","highlight","intro","link","options","label","outro","note","result","spin","sanitizedText","fail","failText","succeed","successText","frames","interval","start","stopAndPersist","symbol"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,OAAOC,cAAc,YAAW;AAEhC,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,OAAO,QAA6B,eAAc;AAI1D,MAAMC,iBAAiB;IAAC;IAAM;IAAM;IAAM;CAAK;AAC/C,MAAMC,oBAAoB;AAC1B,MAAMC,0BAA0B;AAEhC,SAASC,KAAKC,KAAa;IACzB,OAAOR,UAAU,QAAQQ;AAC3B;AAEA,SAASC,SAASC,IAAY;IAC5B,MAAMC,gBACJC,QAAQC,MAAM,CAACC,KAAK,IAAIC,OAAOC,QAAQ,CAACJ,QAAQC,MA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M,aAAa,KAAKiC;gBAC9B,OAAO;oBACLC,MAAM,CAACC,WACLnC,YAAY,GAAGhC,UAAU,OAAO,KAAK,EAAE,EAAE8C,uBAAuBqB,WAAW;oBAC7EC,SAAS,CAACC,cACRrC,YAAY,GAAGzB,KAAK,KAAK,EAAE,EAAEuC,uBAAuBuB,cAAc;gBACtE;YACF;YAEA,MAAML,OAAwB7D,QAAQ;gBACpCA,SAAS;oBAACmE,QAAQlE;oBAAgBmE,UAAU;gBAAG;gBAC/C7D,MAAMuD;YACR,GAAGO,KAAK;YACR,OAAO;gBACLN,MAAKC,QAAgB;oBACnBH,KAAKS,cAAc,CAAC;wBAClBC,QAAQ,GAAG1E,UAAU,OAAO,KAAK,CAAC,CAAC;wBACnCU,MAAMoC,uBAAuBqB;oBAC/B;gBACF;gBACAC,SAAQC,WAAmB;oBACzBL,KAAKS,cAAc,CAAC;wBAACC,QAAQ,GAAGnE,KAAK,KAAK,CAAC,CAAC;wBAAEG,MAAMoC,uBAAuBuB;oBAAY;gBACzF;YACF;QACF;IACF;AACF"}
|
package/dist/ux/spinner.js
CHANGED
|
@@ -1,3 +1,30 @@
|
|
|
1
|
-
|
|
1
|
+
import ora, { oraPromise } from 'ora';
|
|
2
|
+
import { getCliExecutionContext } from '../executionContext.js';
|
|
3
|
+
function silentSpinner(options) {
|
|
4
|
+
const instance = {
|
|
5
|
+
clear: ()=>instance,
|
|
6
|
+
fail: ()=>instance,
|
|
7
|
+
frame: ()=>'',
|
|
8
|
+
info: ()=>instance,
|
|
9
|
+
isSpinning: false,
|
|
10
|
+
prefixText: typeof options === 'object' ? options.prefixText ?? '' : '',
|
|
11
|
+
render: ()=>instance,
|
|
12
|
+
start: ()=>instance,
|
|
13
|
+
stop: ()=>instance,
|
|
14
|
+
stopAndPersist: ()=>instance,
|
|
15
|
+
succeed: ()=>instance,
|
|
16
|
+
suffixText: typeof options === 'object' ? options.suffixText ?? '' : '',
|
|
17
|
+
text: typeof options === 'string' ? options : options?.text ?? '',
|
|
18
|
+
warn: ()=>instance
|
|
19
|
+
};
|
|
20
|
+
return instance;
|
|
21
|
+
}
|
|
22
|
+
export function spinner(options) {
|
|
23
|
+
return getCliExecutionContext() ? silentSpinner(options) : ora(options);
|
|
24
|
+
}
|
|
25
|
+
export function spinnerPromise(action, options) {
|
|
26
|
+
if (!getCliExecutionContext()) return oraPromise(action, options);
|
|
27
|
+
return Promise.resolve(typeof action === 'function' ? action(silentSpinner(options)) : action);
|
|
28
|
+
}
|
|
2
29
|
|
|
3
30
|
//# sourceMappingURL=spinner.js.map
|
package/dist/ux/spinner.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ux/spinner.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"sources":["../../src/ux/spinner.ts"],"sourcesContent":["import ora, {\n type Options,\n type Ora,\n oraPromise,\n type Spinner as OraSpinner,\n type PromiseOptions,\n} from 'ora'\n\nimport {getCliExecutionContext} from '../executionContext.js'\n\nfunction silentSpinner(options?: Options | string): Ora {\n const instance = {\n clear: () => instance,\n fail: () => instance,\n frame: () => '',\n info: () => instance,\n isSpinning: false,\n prefixText: typeof options === 'object' ? (options.prefixText ?? '') : '',\n render: () => instance,\n start: () => instance,\n stop: () => instance,\n stopAndPersist: () => instance,\n succeed: () => instance,\n suffixText: typeof options === 'object' ? (options.suffixText ?? '') : '',\n text: typeof options === 'string' ? options : (options?.text ?? ''),\n warn: () => instance,\n }\n return instance as unknown as Ora\n}\n\nexport function spinner(options?: Options | string): Ora {\n return getCliExecutionContext() ? silentSpinner(options) : ora(options)\n}\n\nexport function spinnerPromise<T>(\n action: ((instance: Ora) => PromiseLike<T>) | PromiseLike<T>,\n options?: PromiseOptions<T> | string,\n): Promise<T> {\n if (!getCliExecutionContext()) return oraPromise(action, options)\n return Promise.resolve(typeof action === 'function' ? action(silentSpinner(options)) : action)\n}\n\nexport type Spinner = OraSpinner\nexport type SpinnerInstance = Ora\nexport type SpinnerOptions = Options\nexport type SpinnerPromiseOptions<T> = PromiseOptions<T>\n"],"names":["ora","oraPromise","getCliExecutionContext","silentSpinner","options","instance","clear","fail","frame","info","isSpinning","prefixText","render","start","stop","stopAndPersist","succeed","suffixText","text","warn","spinner","spinnerPromise","action","Promise","resolve"],"mappings":"AAAA,OAAOA,OAGLC,UAAU,QAGL,MAAK;AAEZ,SAAQC,sBAAsB,QAAO,yBAAwB;AAE7D,SAASC,cAAcC,OAA0B;IAC/C,MAAMC,WAAW;QACfC,OAAO,IAAMD;QACbE,MAAM,IAAMF;QACZG,OAAO,IAAM;QACbC,MAAM,IAAMJ;QACZK,YAAY;QACZC,YAAY,OAAOP,YAAY,WAAYA,QAAQO,UAAU,IAAI,KAAM;QACvEC,QAAQ,IAAMP;QACdQ,OAAO,IAAMR;QACbS,MAAM,IAAMT;QACZU,gBAAgB,IAAMV;QACtBW,SAAS,IAAMX;QACfY,YAAY,OAAOb,YAAY,WAAYA,QAAQa,UAAU,IAAI,KAAM;QACvEC,MAAM,OAAOd,YAAY,WAAWA,UAAWA,SAASc,QAAQ;QAChEC,MAAM,IAAMd;IACd;IACA,OAAOA;AACT;AAEA,OAAO,SAASe,QAAQhB,OAA0B;IAChD,OAAOF,2BAA2BC,cAAcC,WAAWJ,IAAII;AACjE;AAEA,OAAO,SAASiB,eACdC,MAA4D,EAC5DlB,OAAoC;IAEpC,IAAI,CAACF,0BAA0B,OAAOD,WAAWqB,QAAQlB;IACzD,OAAOmB,QAAQC,OAAO,CAAC,OAAOF,WAAW,aAAaA,OAAOnB,cAAcC,YAAYkB;AACzF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/cli-core",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.8.0",
|
|
4
4
|
"description": "Sanity CLI core package",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -109,7 +109,7 @@
|
|
|
109
109
|
"dependencies": {
|
|
110
110
|
"@inquirer/prompts": "^8.5.2",
|
|
111
111
|
"@oclif/core": "^4.11.14",
|
|
112
|
-
"@sanity/client": "^7.
|
|
112
|
+
"@sanity/client": "^7.25.0",
|
|
113
113
|
"boxen": "^8.0.1",
|
|
114
114
|
"debug": "^4.4.3",
|
|
115
115
|
"empathic": "^2.0.1",
|
|
@@ -125,11 +125,12 @@
|
|
|
125
125
|
"tsx": "^4.23.1",
|
|
126
126
|
"vite": "^8.1.5",
|
|
127
127
|
"vite-node": "^6.0.0",
|
|
128
|
+
"wrap-ansi": "^9.0.2",
|
|
128
129
|
"zod": "^4.4.3"
|
|
129
130
|
},
|
|
130
131
|
"devDependencies": {
|
|
131
132
|
"@eslint/compat": "^2.1.0",
|
|
132
|
-
"@sanity/pkg-utils": "^11.0.
|
|
133
|
+
"@sanity/pkg-utils": "^11.0.17",
|
|
133
134
|
"@sanity/telemetry": "^1.1.0",
|
|
134
135
|
"@swc/cli": "^0.8.1",
|
|
135
136
|
"@swc/core": "^1.15.43",
|