@sanity/cli-core 3.4.0 → 3.5.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 +3 -1
- package/dist/SanityCommand.js +23 -1
- package/dist/SanityCommand.js.map +1 -1
- package/dist/_exports/flags.d.ts +7 -0
- package/dist/_exports/flags.js +21 -0
- package/dist/_exports/flags.js.map +1 -0
- package/dist/_exports/index.d.ts +1 -1
- package/dist/_exports/tasks.d.ts +1 -1
- package/dist/_exports/util.d.ts +13 -2
- package/dist/_exports/util.js +1 -0
- package/dist/_exports/util.js.map +1 -1
- package/dist/loaders/studio/studioWorkerLoader.worker.js +11 -4
- package/dist/loaders/studio/studioWorkerLoader.worker.js.map +1 -1
- package/dist/loaders/studio/studioWorkerTask.js +10 -3
- package/dist/loaders/studio/studioWorkerTask.js.map +1 -1
- package/dist/{tsxWorkerTask-CxG3fWbU.d.ts → tsxWorkerTask-MHWcAqb6.d.ts} +2 -1
- package/dist/util/isUnattended.js +15 -0
- package/dist/util/isUnattended.js.map +1 -0
- package/package.json +5 -1
package/dist/SanityCommand.d.ts
CHANGED
|
@@ -4,9 +4,10 @@ import { t as ProjectRootResult } from "./recursivelyResolveProjectRoot-BE54uEP6
|
|
|
4
4
|
import { t as CLITelemetryStore } from "./types-ZNH3prAd.js";
|
|
5
5
|
import { t as Output } from "./types-CwJLTYDj.js";
|
|
6
6
|
import { Command, Interfaces } from "@oclif/core";
|
|
7
|
-
import { CommandError } from "@oclif/core/interfaces";
|
|
7
|
+
import { CommandError, Input, ParserOutput } from "@oclif/core/interfaces";
|
|
8
8
|
type Flags<T extends typeof Command> = Interfaces.InferredFlags<(typeof SanityCommand)['baseFlags'] & T['flags']>;
|
|
9
9
|
type Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>;
|
|
10
|
+
type ParserValues = Record<string, unknown>;
|
|
10
11
|
/**
|
|
11
12
|
* Interface for `SanityCommand`, a wrapper around OCLIF's Command class.
|
|
12
13
|
* Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.
|
|
@@ -129,6 +130,7 @@ declare abstract class SanityCommand<T extends typeof Command> extends Command i
|
|
|
129
130
|
* Like `log`, but for stderr / the context's `stderr` sink.
|
|
130
131
|
*/
|
|
131
132
|
logToStderr(message?: string, ...args: unknown[]): void;
|
|
133
|
+
protected parse<F extends ParserValues, B extends ParserValues, A extends ParserValues>(options?: Input<F, B, A>, argv?: string[]): Promise<ParserOutput<F, B, A>>;
|
|
132
134
|
/**
|
|
133
135
|
* Resolver for checking if the terminal is interactive. Override in tests to provide mock values.
|
|
134
136
|
*
|
package/dist/SanityCommand.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { format, styleText } from 'node:util';
|
|
2
2
|
import { Command } from '@oclif/core';
|
|
3
3
|
import { subdebug } from './_exports/debug.js';
|
|
4
|
+
import { resolveUnattendedFlagRequirements } from './_exports/flags.js';
|
|
4
5
|
import { getGlobalCliClient, getProjectCliClient } from './apiClient.js';
|
|
5
6
|
import { getCliConfig } from './config/cli/getCliConfig.js';
|
|
6
7
|
import { findProjectRoot } from './config/findProjectRoot.js';
|
|
@@ -11,6 +12,7 @@ import { getCliExecutionContext } from './executionContext.js';
|
|
|
11
12
|
import { exitCodes } from './exitCodes.js';
|
|
12
13
|
import { getCliTelemetry, reportCliTraceError } from './telemetry/getCliTelemetry.js';
|
|
13
14
|
import { isInteractive } from './util/isInteractive.js';
|
|
15
|
+
import { isUnattendedInvocation, isUnattended as resolveIsUnattended } from './util/isUnattended.js';
|
|
14
16
|
const debug = subdebug('sanityCommand');
|
|
15
17
|
export class SanityCommand extends Command {
|
|
16
18
|
args;
|
|
@@ -186,7 +188,11 @@ export class SanityCommand extends Command {
|
|
|
186
188
|
* (eg when running in a CI environment), or when `--json` asks for machine-readable
|
|
187
189
|
* output (a caller parsing JSON can't answer a prompt).
|
|
188
190
|
*/ isUnattended() {
|
|
189
|
-
return
|
|
191
|
+
return resolveIsUnattended({
|
|
192
|
+
isInteractive: this.resolveIsInteractive(),
|
|
193
|
+
json: this.flags.json,
|
|
194
|
+
yes: this.flags.yes
|
|
195
|
+
});
|
|
190
196
|
}
|
|
191
197
|
/**
|
|
192
198
|
* Write to stdout — or, when running under an execution context (e.g. from
|
|
@@ -222,6 +228,22 @@ export class SanityCommand extends Command {
|
|
|
222
228
|
}
|
|
223
229
|
if (!this.jsonEnabled()) context.stderr(format(message, ...args));
|
|
224
230
|
}
|
|
231
|
+
parse(options, argv = this.argv) {
|
|
232
|
+
// If no flags defined, exit to default parser early
|
|
233
|
+
if (!options?.flags) return super.parse(options, argv);
|
|
234
|
+
// Resolve the actual required flags based on the current unattended mode value
|
|
235
|
+
const resolvedFlags = resolveUnattendedFlagRequirements(options.flags, isUnattendedInvocation({
|
|
236
|
+
argv,
|
|
237
|
+
isInteractive: this.resolveIsInteractive()
|
|
238
|
+
}));
|
|
239
|
+
// If flags weren't modified, use original options object
|
|
240
|
+
// Otherwise create a new options object with the resolved flag values
|
|
241
|
+
const resolvedOptions = resolvedFlags === options.flags ? options : {
|
|
242
|
+
...options,
|
|
243
|
+
flags: resolvedFlags
|
|
244
|
+
};
|
|
245
|
+
return super.parse(resolvedOptions, argv);
|
|
246
|
+
}
|
|
225
247
|
/**
|
|
226
248
|
* Resolver for checking if the terminal is interactive. Override in tests to provide mock values.
|
|
227
249
|
*
|
|
@@ -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 {enrichAuthError} from './errors/enrichAuthError.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 // 401s carry login/membership guidance in their message. Applied here\n // rather than in transport middleware since client v8 dropped custom\n // requesters.\n enrichAuthError(err)\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","enrichAuthError","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,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;;;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"}
|
|
1
|
+
{"version":3,"sources":["../src/SanityCommand.ts"],"sourcesContent":["import {format, styleText} from 'node:util'\n\nimport {Command, Interfaces} from '@oclif/core'\nimport {type CommandError, type Input, type ParserOutput} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {resolveUnattendedFlagRequirements} from './_exports/flags.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 {enrichAuthError} from './errors/enrichAuthError.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'\nimport {isUnattendedInvocation, isUnattended as resolveIsUnattended} from './util/isUnattended.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\ntype ParserValues = Record<string, unknown>\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 // 401s carry login/membership guidance in their message. Applied here\n // rather than in transport middleware since client v8 dropped custom\n // requesters.\n enrichAuthError(err)\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 resolveIsUnattended({\n isInteractive: this.resolveIsInteractive(),\n json: this.flags.json,\n yes: this.flags.yes,\n })\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 protected override parse<F extends ParserValues, B extends ParserValues, A extends ParserValues>(\n options?: Input<F, B, A>,\n argv: string[] = this.argv,\n ): Promise<ParserOutput<F, B, A>> {\n // If no flags defined, exit to default parser early\n if (!options?.flags) return super.parse(options, argv)\n\n // Resolve the actual required flags based on the current unattended mode value\n const resolvedFlags = resolveUnattendedFlagRequirements(\n options.flags,\n isUnattendedInvocation({argv, isInteractive: this.resolveIsInteractive()}),\n )\n // If flags weren't modified, use original options object\n // Otherwise create a new options object with the resolved flag values\n const resolvedOptions =\n resolvedFlags === options.flags\n ? options\n : {...options, flags: resolvedFlags as Interfaces.FlagInput<F>}\n\n return super.parse(resolvedOptions, argv)\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","resolveUnattendedFlagRequirements","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","enrichAuthError","NonInteractiveError","ProjectRootNotFoundError","getCliExecutionContext","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","isUnattendedInvocation","isUnattended","resolveIsUnattended","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","resolveIsInteractive","json","yes","context","stdout","JSON","stringify","stderr","argv","resolvedFlags","resolvedOptions","runInExecutionContext","Error","_run","tryGetCliConfig","input"],"mappings":"AAAA,SAAQA,MA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C,QAAQvB,KAAK,EACbN,uBAAuB;YAAC0D;YAAM3D,eAAe,IAAI,CAACmD,oBAAoB;QAAE;QAE1E,yDAAyD;QACzD,sEAAsE;QACtE,MAAMU,kBACJD,kBAAkB9B,QAAQvB,KAAK,GAC3BuB,UACA;YAAC,GAAGA,OAAO;YAAEvB,OAAOqD;QAAwC;QAElE,OAAO,KAAK,CAACb,MAAMc,iBAAiBF;IACtC;IAEA;;;;GAIC,GACD,AAAOR,uBAAgC;QACrC,OAAOnD;IACT;IAEA;;;;;GAKC,GACD,AAAO8D,wBAAmD;QACxD,IAAI,CAAClE,0BAA0B;YAC7B,MAAM,IAAImE,MAAM;QAClB;QACA,OAAO,IAAI,CAACC,IAAI;IAClB;IAEA;;;;;;;GAOC,GACD,MAAgBC,kBAAsC;QACpD,IAAI;YACF,OAAO,MAAM,IAAI,CAAC1E,YAAY;QAChC,EAAE,OAAO0B,KAAK;YACZ,IAAI,CAAEA,CAAAA,eAAetB,wBAAuB,GAAI,MAAMsB;YACtD,OAAO,CAAC;QACV;IACF;IAEA;;;GAGC,GACD,AAAgBH,KAAKoD,KAAqB,EAAkB;QAC1D,MAAMZ,UAAU1D;QAChB,IAAI,CAAC0D,SAASI,QAAQ,OAAO,KAAK,CAAC5C,KAAKoD;QAExC,IAAI,CAAC,IAAI,CAAC3C,WAAW,IAAI;YACvB+B,QAAQI,MAAM,CAAC,CAAC,SAAS,EAAEQ,iBAAiBH,QAAQG,MAAM/C,OAAO,GAAG+C,OAAO;QAC7E;QACA,OAAOA;IACT;AACF"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Interfaces } from "@oclif/core";
|
|
2
|
+
type AnyFlag = Interfaces.Flag<any>;
|
|
3
|
+
/** Marks an optional flag as required whenever the command is invoked in unattended mode. */
|
|
4
|
+
declare function requiredWhenUnattended<T extends AnyFlag>(flag: T): T;
|
|
5
|
+
declare function resolveUnattendedFlagRequirements(flags: Interfaces.FlagInput, unattended: boolean): Interfaces.FlagInput;
|
|
6
|
+
export { requiredWhenUnattended, resolveUnattendedFlagRequirements };
|
|
7
|
+
//# sourceMappingURL=flags.d.ts.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const requiredWhenUnattendedSymbol = Symbol.for('@sanity/cli-core/requiredWhenUnattended');
|
|
2
|
+
/** Marks an optional flag as required whenever the command is invoked in unattended mode. */ export function requiredWhenUnattended(flag) {
|
|
3
|
+
Object.defineProperty(flag, requiredWhenUnattendedSymbol, {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
return flag;
|
|
7
|
+
}
|
|
8
|
+
export function resolveUnattendedFlagRequirements(flags, unattended) {
|
|
9
|
+
if (!Object.values(flags).some((flag)=>flag[requiredWhenUnattendedSymbol])) {
|
|
10
|
+
return flags;
|
|
11
|
+
}
|
|
12
|
+
return Object.fromEntries(Object.entries(flags).map(([name, flag])=>[
|
|
13
|
+
name,
|
|
14
|
+
flag[requiredWhenUnattendedSymbol] ? {
|
|
15
|
+
...flag,
|
|
16
|
+
required: unattended
|
|
17
|
+
} : flag
|
|
18
|
+
]));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=flags.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/flags.ts"],"sourcesContent":["import {type Interfaces} from '@oclif/core'\n\nconst requiredWhenUnattendedSymbol = Symbol.for('@sanity/cli-core/requiredWhenUnattended')\n\n// `Flag` is invariant in its parsed value, so `unknown` would reject concrete flag types.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyFlag = Interfaces.Flag<any>\n\ntype UnattendedFlag = AnyFlag & {\n [requiredWhenUnattendedSymbol]?: true\n}\n\n/** Marks an optional flag as required whenever the command is invoked in unattended mode. */\nexport function requiredWhenUnattended<T extends AnyFlag>(flag: T): T {\n Object.defineProperty(flag, requiredWhenUnattendedSymbol, {value: true})\n return flag\n}\n\nexport function resolveUnattendedFlagRequirements(\n flags: Interfaces.FlagInput,\n unattended: boolean,\n): Interfaces.FlagInput {\n if (\n !Object.values(flags).some((flag) => (flag as UnattendedFlag)[requiredWhenUnattendedSymbol])\n ) {\n return flags\n }\n\n return Object.fromEntries(\n Object.entries(flags).map(([name, flag]) => [\n name,\n (flag as UnattendedFlag)[requiredWhenUnattendedSymbol]\n ? {...flag, required: unattended}\n : flag,\n ]),\n )\n}\n"],"names":["requiredWhenUnattendedSymbol","Symbol","for","requiredWhenUnattended","flag","Object","defineProperty","value","resolveUnattendedFlagRequirements","flags","unattended","values","some","fromEntries","entries","map","name","required"],"mappings":"AAEA,MAAMA,+BAA+BC,OAAOC,GAAG,CAAC;AAUhD,2FAA2F,GAC3F,OAAO,SAASC,uBAA0CC,IAAO;IAC/DC,OAAOC,cAAc,CAACF,MAAMJ,8BAA8B;QAACO,OAAO;IAAI;IACtE,OAAOH;AACT;AAEA,OAAO,SAASI,kCACdC,KAA2B,EAC3BC,UAAmB;IAEnB,IACE,CAACL,OAAOM,MAAM,CAACF,OAAOG,IAAI,CAAC,CAACR,OAAS,AAACA,IAAuB,CAACJ,6BAA6B,GAC3F;QACA,OAAOS;IACT;IAEA,OAAOJ,OAAOQ,WAAW,CACvBR,OAAOS,OAAO,CAACL,OAAOM,GAAG,CAAC,CAAC,CAACC,MAAMZ,KAAK,GAAK;YAC1CY;YACCZ,IAAuB,CAACJ,6BAA6B,GAClD;gBAAC,GAAGI,IAAI;gBAAEa,UAAUP;YAAU,IAC9BN;SACL;AAEL"}
|
package/dist/_exports/index.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { debug, subdebug } from "./debug.js";
|
|
|
12
12
|
import { t as NonInteractiveError } from "../NonInteractiveError-CSLT5y93.js";
|
|
13
13
|
import { i as isNotFoundError, n as isProjectRootNotFoundError, r as NotFoundError, t as ProjectRootNotFoundError } from "../ProjectRootNotFoundError-RgthN9uy.js";
|
|
14
14
|
import { exitCodes } from "../exitCodes.js";
|
|
15
|
-
import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-
|
|
15
|
+
import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-MHWcAqb6.js";
|
|
16
16
|
import { a as getCliTelemetry, i as clearCliTelemetry, n as getTelemetryBaseInfo, o as reportCliTraceError, r as CLI_TELEMETRY_SYMBOL, s as setCliTelemetry, t as noopLogger } from "../noopTelemetry-BJRIvASI.js";
|
|
17
17
|
import { a as isCi, i as isInteractive, n as normalizePath, o as importModule, r as isStaging, s as doImport, t as safeStructuredClone } from "../safeStructuredClone-CWB0MXmH.js";
|
|
18
18
|
import { a as getLocalPackageVersion, i as getLocalPackageDir, n as resolveLocalPackageFrom, r as resolveLocalPackagePath, t as resolveLocalPackage } from "../resolveLocalPackage-Dr-TNTyk.js";
|
package/dist/_exports/tasks.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-
|
|
1
|
+
import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-MHWcAqb6.js";
|
|
2
2
|
export { createStudioWorker, studioWorkerTask, tsxWorkerTask };
|
package/dist/_exports/util.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as getSanityDataDir, i as getSanityConfigDir, n as getSanityUrl, r as getSanityEnvVar, t as getWorkspace } from "../getWorkspace-CU32E6Uo.js";
|
|
2
|
-
import { a as isCi, i as isInteractive, n as normalizePath, o as importModule, r as isStaging, s as doImport, t as safeStructuredClone } from "../safeStructuredClone-CWB0MXmH.js";
|
|
2
|
+
import { a as isCi, i as isInteractive$1, n as normalizePath, o as importModule, r as isStaging, s as doImport, t as safeStructuredClone } from "../safeStructuredClone-CWB0MXmH.js";
|
|
3
3
|
declare function getCoreAppUrl(organizationId: string, appId: string): string;
|
|
4
4
|
/**
|
|
5
5
|
* Checks if the given value is a record (javascript objectish)
|
|
@@ -10,5 +10,16 @@ declare function getCoreAppUrl(organizationId: string, appId: string): string;
|
|
|
10
10
|
*/
|
|
11
11
|
declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
12
12
|
declare function isTrueish(value: string | undefined): boolean;
|
|
13
|
-
|
|
13
|
+
interface IsUnattendedOptions {
|
|
14
|
+
isInteractive: boolean;
|
|
15
|
+
json?: boolean;
|
|
16
|
+
yes?: boolean;
|
|
17
|
+
}
|
|
18
|
+
interface IsUnattendedInvocationOptions {
|
|
19
|
+
argv: string[];
|
|
20
|
+
isInteractive: boolean;
|
|
21
|
+
}
|
|
22
|
+
declare function isUnattended({ isInteractive, json, yes }: IsUnattendedOptions): boolean;
|
|
23
|
+
declare function isUnattendedInvocation({ argv, isInteractive }: IsUnattendedInvocationOptions): boolean;
|
|
24
|
+
export { doImport, getCoreAppUrl, getSanityConfigDir, getSanityDataDir, getSanityEnvVar, getSanityUrl, getWorkspace, importModule, isCi, isInteractive$1 as isInteractive, isRecord, isStaging, isTrueish, isUnattended, isUnattendedInvocation, normalizePath, safeStructuredClone };
|
|
14
25
|
//# sourceMappingURL=util.d.ts.map
|
package/dist/_exports/util.js
CHANGED
|
@@ -12,6 +12,7 @@ export { isInteractive } from '../util/isInteractive.js';
|
|
|
12
12
|
export { isRecord } from '../util/isRecord.js';
|
|
13
13
|
export { isStaging } from '../util/isStaging.js';
|
|
14
14
|
export { isTrueish } from '../util/isTrueish.js';
|
|
15
|
+
export { isUnattended, isUnattendedInvocation } from '../util/isUnattended.js';
|
|
15
16
|
export { normalizePath } from '../util/normalizePath.js';
|
|
16
17
|
export { safeStructuredClone } from '../util/safeStructuredClone.js';
|
|
17
18
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/_exports/util.ts"],"sourcesContent":["// Pure in-memory and zero dep utilities\n//\nexport {doImport} from '../util/doImport.js'\nexport {getCoreAppUrl} from '../util/getCoreAppUrl.js'\nexport {getSanityConfigDir, getSanityDataDir} from '../util/getSanityConfigDir.js'\nexport {getSanityEnvVar} from '../util/getSanityEnvVar.js'\nexport {getSanityUrl} from '../util/getSanityUrl.js'\nexport {getWorkspace} from '../util/getWorkspace.js'\nexport {importModule} from '../util/importModule.js'\nexport {isCi} from '../util/isCi.js'\nexport {isInteractive} from '../util/isInteractive.js'\nexport {isRecord} from '../util/isRecord.js'\nexport {isStaging} from '../util/isStaging.js'\nexport {isTrueish} from '../util/isTrueish.js'\nexport {normalizePath} from '../util/normalizePath.js'\nexport {safeStructuredClone} from '../util/safeStructuredClone.js'\n"],"names":["doImport","getCoreAppUrl","getSanityConfigDir","getSanityDataDir","getSanityEnvVar","getSanityUrl","getWorkspace","importModule","isCi","isInteractive","isRecord","isStaging","isTrueish","normalizePath","safeStructuredClone"],"mappings":"AAAA,wCAAwC;AACxC,EAAE;AACF,SAAQA,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,gCAA+B;AAClF,SAAQC,eAAe,QAAO,6BAA4B;AAC1D,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,IAAI,QAAO,kBAAiB;AACpC,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,mBAAmB,QAAO,iCAAgC"}
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/util.ts"],"sourcesContent":["// Pure in-memory and zero dep utilities\n//\nexport {doImport} from '../util/doImport.js'\nexport {getCoreAppUrl} from '../util/getCoreAppUrl.js'\nexport {getSanityConfigDir, getSanityDataDir} from '../util/getSanityConfigDir.js'\nexport {getSanityEnvVar} from '../util/getSanityEnvVar.js'\nexport {getSanityUrl} from '../util/getSanityUrl.js'\nexport {getWorkspace} from '../util/getWorkspace.js'\nexport {importModule} from '../util/importModule.js'\nexport {isCi} from '../util/isCi.js'\nexport {isInteractive} from '../util/isInteractive.js'\nexport {isRecord} from '../util/isRecord.js'\nexport {isStaging} from '../util/isStaging.js'\nexport {isTrueish} from '../util/isTrueish.js'\nexport {isUnattended, isUnattendedInvocation} from '../util/isUnattended.js'\nexport {normalizePath} from '../util/normalizePath.js'\nexport {safeStructuredClone} from '../util/safeStructuredClone.js'\n"],"names":["doImport","getCoreAppUrl","getSanityConfigDir","getSanityDataDir","getSanityEnvVar","getSanityUrl","getWorkspace","importModule","isCi","isInteractive","isRecord","isStaging","isTrueish","isUnattended","isUnattendedInvocation","normalizePath","safeStructuredClone"],"mappings":"AAAA,wCAAwC;AACxC,EAAE;AACF,SAAQA,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,gCAA+B;AAClF,SAAQC,eAAe,QAAO,6BAA4B;AAC1D,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,IAAI,QAAO,kBAAiB;AACpC,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,YAAY,EAAEC,sBAAsB,QAAO,0BAAyB;AAC5E,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,mBAAmB,QAAO,iCAAgC"}
|
|
@@ -24,6 +24,7 @@ if (!workerScriptPath) {
|
|
|
24
24
|
}
|
|
25
25
|
await setupBrowserStubs();
|
|
26
26
|
const studioEnvVars = await getStudioEnvironmentVariables(rootPath);
|
|
27
|
+
const applicationId = process.env.STUDIO_WORKER_APPLICATION_ID;
|
|
27
28
|
// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can
|
|
28
29
|
// extend/modify the default vite configuration for the studio.
|
|
29
30
|
let cliConfig;
|
|
@@ -68,10 +69,16 @@ const defaultViteConfig = {
|
|
|
68
69
|
},
|
|
69
70
|
configFile: false,
|
|
70
71
|
// Inject environment variables as compile-time constants for Vite
|
|
71
|
-
define:
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
72
|
+
define: {
|
|
73
|
+
// Config imports must use the same bus identity as the surrounding app bundle.
|
|
74
|
+
...applicationId ? {
|
|
75
|
+
__SANITY_APP_ID__: JSON.stringify(applicationId)
|
|
76
|
+
} : {},
|
|
77
|
+
...Object.fromEntries(Object.entries(studioEnvVars).map(([key, value])=>[
|
|
78
|
+
`process.env.${key}`,
|
|
79
|
+
JSON.stringify(value)
|
|
80
|
+
]))
|
|
81
|
+
},
|
|
75
82
|
envPrefix: cliConfig && 'app' in cliConfig ? 'SANITY_APP_' : 'SANITY_STUDIO_',
|
|
76
83
|
esbuild: {
|
|
77
84
|
jsx: 'automatic'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {isMainThread, parentPort} from 'node:worker_threads'\n\nimport {createServer, type InlineConfig, loadEnv, mergeConfig} from 'vite'\nimport {ViteNodeRunner} from 'vite-node/client'\nimport {ViteNodeServer} from 'vite-node/server'\nimport {installSourcemapsSupport} from 'vite-node/source-map'\n\nimport {subdebug} from '../../_exports/debug.js'\nimport {getCliConfig} from '../../config/cli/getCliConfig.js'\nimport {type CliConfig} from '../../config/cli/types/cliConfig.js'\nimport {isNotFoundError} from '../../errors/NotFoundError.js'\nimport {getStudioEnvironmentVariables} from '../../util/environment/getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from '../../util/environment/setupBrowserStubs.js' // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB\nimport {isRecord} from '../../util/isRecord.js'\nimport {createOneShotWorkerLifecycle} from './studioWorkerLifecycle.js'\n\nif (isMainThread) {\n throw new Error('Should be child of thread, not the main thread')\n}\n\nconst rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH\nif (!rootPath) {\n throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable')\n}\n\nconst debug = subdebug('studio:worker')\n\nconst workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE\nif (!workerScriptPath) {\n throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable')\n}\n\nawait setupBrowserStubs()\n\nconst studioEnvVars = await getStudioEnvironmentVariables(rootPath)\n\n// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can\n// extend/modify the default vite configuration for the studio.\nlet cliConfig: CliConfig | undefined\ntry {\n cliConfig = await getCliConfig(rootPath)\n} catch (err) {\n debug('Failed to load CLI config: %o', err)\n if (!isNotFoundError(err)) {\n // eslint-disable-next-line no-console\n console.warn('[warn] Failed to load CLI config:', err)\n }\n}\n\n/**\n * Fetches and caches modules from HTTP/HTTPS URLs.\n * Vite's SSR transform treats `https://` imports as external and bypasses the plugin\n * resolve pipeline entirely, so we intercept them at the ViteNodeRunner level instead.\n */\nconst httpModuleCache = new Map<string, string>()\nasync function fetchHttpModule(url: string): Promise<{code: string}> {\n const cached = httpModuleCache.get(url)\n if (cached) return {code: cached}\n\n debug('Fetching HTTP import: %s', url)\n const response = await fetch(url, {signal: AbortSignal.timeout(30_000)})\n if (!response.ok) {\n throw new Error(`Failed to fetch module from ${url}: ${response.status} ${response.statusText}`)\n }\n\n const code = await response.text()\n httpModuleCache.set(url, code)\n return {code}\n}\n\nfunction isHttpsUrl(id: string): boolean {\n return id.startsWith('https://')\n}\n\nconst defaultViteConfig: InlineConfig = {\n build: {target: 'node'},\n configFile: false,\n // Inject environment variables as compile-time constants for Vite\n define: Object.fromEntries(\n Object.entries(studioEnvVars).map(([key, value]) => [\n `process.env.${key}`,\n JSON.stringify(value),\n ]),\n ),\n envPrefix: cliConfig && 'app' in cliConfig ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n esbuild: {\n jsx: 'automatic',\n },\n logLevel: 'error',\n optimizeDeps: {\n include: undefined,\n noDiscovery: true,\n },\n resolve: {\n // Resolve the studio's tsconfig `paths` natively (Vite 8+), replacing the\n // custom alias mapping and the need for a user-added `vite-tsconfig-paths`.\n tsconfigPaths: true,\n },\n root: rootPath,\n server: {\n hmr: false,\n watch: null,\n },\n ssr: {\n /**\n * We don't want to externalize any dependencies, we want everything to run thru vite.\n * Especially for CJS compatibility, etc.\n */\n noExternal: true,\n },\n}\n\n// Merge the CLI config's Vite config with the default Vite config\nlet viteConfig = defaultViteConfig\nif (typeof cliConfig?.vite === 'function') {\n viteConfig = (await cliConfig.vite(viteConfig, {\n command: 'build',\n isSsrBuild: true,\n mode: 'production',\n })) as InlineConfig\n} else if (isRecord(cliConfig?.vite)) {\n viteConfig = mergeConfig(viteConfig, cliConfig.vite)\n}\n\ndebug('Creating Vite server with config: %o', viteConfig)\n// Vite will build the files we give it - targetting Node.js instead of the browser.\n// We include the inject plugin in order to provide the stubs for the undefined global APIs.\nconst server = await createServer(viteConfig)\n\n// One-shot tasks (`studioWorkerTask`) resolve on their first message, and the\n// main thread historically terminate()d the worker right after — destroying\n// the worker's libuv loop while rolldown's native threads were still live.\n// The next `napi_call_threadsafe_function` then locked a destroyed mutex and\n// aborted the whole process (silent SIGABRT / exit code 134, reliably\n// reproduced on macOS). The lifecycle closes the Vite server BEFORE any\n// message reaches the main thread, and the main thread no longer terminates\n// one-shot workers at all (see `terminateOnSettle` in promisifyWorker).\nconst lifecycle =\n process.env.STUDIO_WORKER_ONE_SHOT === '1' && parentPort\n ? createOneShotWorkerLifecycle({\n closeServer: async () => {\n debug('Closing Vite server')\n await server.close()\n debug('Vite server closed')\n },\n onCloseError: (error) => debug('Failed to close Vite server: %o', error),\n parentPort,\n })\n : undefined\n\ntry {\n // Bit of a hack, but seems necessary based on the `node-vite` binary implementation\n await server.pluginContainer.buildStart({})\n\n // Load environment variables from `.env` files in the same way as Vite does.\n // Note that Sanity also provides environment variables through `process.env.*` for compat reasons,\n // and so we need to do the same here.\n // Load ALL env vars from .env files (not just studio-prefixed ones) so non-Sanity-prefixed\n // vars (e.g. NEXT_PUBLIC_*, VITE_*) are available via process.env at runtime.\n // The ??= on the next line prevents overwriting existing process.env values.\n const env = loadEnv(server.config.mode, server.config.envDir, '')\n for (const key in env) {\n process.env[key] ??= env[key]\n }\n\n // Now we're providing the glue that ensures node-specific loading and execution works.\n const node = new ViteNodeServer(server)\n\n // Should make it easier to debug any crashes in the imported code…\n installSourcemapsSupport({\n getSourceMap: (source) => node.getSourceMap(source),\n })\n\n const runner = new ViteNodeRunner({\n base: server.config.base,\n async fetchModule(id) {\n // Vite's SSR transform externalizes https:// imports, so Node's ESM loader\n // would reject them. We fetch the module over HTTP and run it through Vite's\n // SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*\n // format that ViteNodeRunner expects.\n if (isHttpsUrl(id)) {\n const {code: rawCode} = await fetchHttpModule(id)\n const result = await server.ssrTransform(rawCode, null, id)\n return {code: result?.code || rawCode}\n }\n return node.fetchModule(id)\n },\n resolveId(id, importer) {\n // Prevent vite-node from trying to resolve HTTP URLs through Node's resolver\n if (isHttpsUrl(id)) return {id}\n // Resolve any import from an HTTP-fetched module against the remote origin\n // (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)\n if (importer && isHttpsUrl(importer)) {\n return {id: new URL(id, importer).href}\n }\n return node.resolveId(id, importer)\n },\n root: server.config.root,\n })\n\n // Copied from `vite-node` - it appears that this applies the `define` config from\n // vite, but it also takes a surprisingly long time to execute. Not clear at this\n // point why this is, so we should investigate whether it's necessary or not.\n await runner.executeId('/@vite/env')\n\n await runner.executeId(workerScriptPath)\n} catch (error) {\n // Long-lived workers keep the original behavior: the error surfaces as a\n // Worker 'error' event.\n if (!lifecycle) {\n throw error\n }\n\n // One-shot workers close the server first and post a serialized error the\n // main thread rethrows, so the worker exits cleanly (code 0) and the real\n // error (e.g. a broken `sanity.config.ts`) isn't masked by a teardown abort.\n await lifecycle.postError(error)\n} finally {\n await lifecycle?.close()\n}\n"],"names":["isMainThread","parentPort","createServer","loadEnv","mergeConfig","ViteNodeRunner","ViteNodeServer","installSourcemapsSupport","subdebug","getCliConfig","isNotFoundError","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","createOneShotWorkerLifecycle","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","debug","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","cliConfig","err","console","warn","httpModuleCache","Map","fetchHttpModule","url","cached","get","code","response","fetch","signal","AbortSignal","timeout","ok","status","statusText","text","set","isHttpsUrl","id","startsWith","defaultViteConfig","build","target","configFile","define","Object","fromEntries","entries","map","key","value","JSON","stringify","envPrefix","esbuild","jsx","logLevel","optimizeDeps","include","undefined","noDiscovery","resolve","tsconfigPaths","root","server","hmr","watch","ssr","noExternal","viteConfig","vite","command","isSsrBuild","mode","lifecycle","STUDIO_WORKER_ONE_SHOT","closeServer","close","onCloseError","error","pluginContainer","buildStart","config","envDir","node","getSourceMap","source","runner","base","fetchModule","rawCode","result","ssrTransform","resolveId","importer","URL","href","executeId","postError"],"mappings":"AAAA,SAAQA,YAAY,EAAEC,UAAU,QAAO,sBAAqB;AAE5D,SAAQC,YAAY,EAAqBC,OAAO,EAAEC,WAAW,QAAO,OAAM;AAC1E,SAAQC,cAAc,QAAO,mBAAkB;AAC/C,SAAQC,cAAc,QAAO,mBAAkB;AAC/C,SAAQC,wBAAwB,QAAO,uBAAsB;AAE7D,SAAQC,QAAQ,QAAO,0BAAyB;AAChD,SAAQC,YAAY,QAAO,mCAAkC;AAE7D,SAAQC,eAAe,QAAO,gCAA+B;AAC7D,SAAQC,6BAA6B,QAAO,0DAAyD;AACrG,SAAQC,iBAAiB,QAAO,8C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AAS,CAACvD,IAAIwD;QAC5B;QACA/B,MAAMC,OAAOkB,MAAM,CAACnB,IAAI;IAC1B;IAEA,kFAAkF;IAClF,iFAAiF;IACjF,6EAA6E;IAC7E,MAAMwB,OAAOU,SAAS,CAAC;IAEvB,MAAMV,OAAOU,SAAS,CAACpF;AACzB,EAAE,OAAOkE,OAAO;IACd,yEAAyE;IACzE,wBAAwB;IACxB,IAAI,CAACL,WAAW;QACd,MAAMK;IACR;IAEA,0EAA0E;IAC1E,0EAA0E;IAC1E,6EAA6E;IAC7E,MAAML,UAAUwB,SAAS,CAACnB;AAC5B,SAAU;IACR,MAAML,WAAWG;AACnB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {isMainThread, parentPort} from 'node:worker_threads'\n\nimport {createServer, type InlineConfig, loadEnv, mergeConfig} from 'vite'\nimport {ViteNodeRunner} from 'vite-node/client'\nimport {ViteNodeServer} from 'vite-node/server'\nimport {installSourcemapsSupport} from 'vite-node/source-map'\n\nimport {subdebug} from '../../_exports/debug.js'\nimport {getCliConfig} from '../../config/cli/getCliConfig.js'\nimport {type CliConfig} from '../../config/cli/types/cliConfig.js'\nimport {isNotFoundError} from '../../errors/NotFoundError.js'\nimport {getStudioEnvironmentVariables} from '../../util/environment/getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from '../../util/environment/setupBrowserStubs.js' // TODO: this imports jsdom!!! Unpacked Size (module + dependencies): 26 MB\nimport {isRecord} from '../../util/isRecord.js'\nimport {createOneShotWorkerLifecycle} from './studioWorkerLifecycle.js'\n\nif (isMainThread) {\n throw new Error('Should be child of thread, not the main thread')\n}\n\nconst rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH\nif (!rootPath) {\n throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable')\n}\n\nconst debug = subdebug('studio:worker')\n\nconst workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE\nif (!workerScriptPath) {\n throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable')\n}\n\nawait setupBrowserStubs()\n\nconst studioEnvVars = await getStudioEnvironmentVariables(rootPath)\nconst applicationId = process.env.STUDIO_WORKER_APPLICATION_ID\n\n// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can\n// extend/modify the default vite configuration for the studio.\nlet cliConfig: CliConfig | undefined\ntry {\n cliConfig = await getCliConfig(rootPath)\n} catch (err) {\n debug('Failed to load CLI config: %o', err)\n if (!isNotFoundError(err)) {\n // eslint-disable-next-line no-console\n console.warn('[warn] Failed to load CLI config:', err)\n }\n}\n\n/**\n * Fetches and caches modules from HTTP/HTTPS URLs.\n * Vite's SSR transform treats `https://` imports as external and bypasses the plugin\n * resolve pipeline entirely, so we intercept them at the ViteNodeRunner level instead.\n */\nconst httpModuleCache = new Map<string, string>()\nasync function fetchHttpModule(url: string): Promise<{code: string}> {\n const cached = httpModuleCache.get(url)\n if (cached) return {code: cached}\n\n debug('Fetching HTTP import: %s', url)\n const response = await fetch(url, {signal: AbortSignal.timeout(30_000)})\n if (!response.ok) {\n throw new Error(`Failed to fetch module from ${url}: ${response.status} ${response.statusText}`)\n }\n\n const code = await response.text()\n httpModuleCache.set(url, code)\n return {code}\n}\n\nfunction isHttpsUrl(id: string): boolean {\n return id.startsWith('https://')\n}\n\nconst defaultViteConfig: InlineConfig = {\n build: {target: 'node'},\n configFile: false,\n // Inject environment variables as compile-time constants for Vite\n define: {\n // Config imports must use the same bus identity as the surrounding app bundle.\n ...(applicationId ? {__SANITY_APP_ID__: JSON.stringify(applicationId)} : {}),\n ...Object.fromEntries(\n Object.entries(studioEnvVars).map(([key, value]) => [\n `process.env.${key}`,\n JSON.stringify(value),\n ]),\n ),\n },\n envPrefix: cliConfig && 'app' in cliConfig ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n esbuild: {\n jsx: 'automatic',\n },\n logLevel: 'error',\n optimizeDeps: {\n include: undefined,\n noDiscovery: true,\n },\n resolve: {\n // Resolve the studio's tsconfig `paths` natively (Vite 8+), replacing the\n // custom alias mapping and the need for a user-added `vite-tsconfig-paths`.\n tsconfigPaths: true,\n },\n root: rootPath,\n server: {\n hmr: false,\n watch: null,\n },\n ssr: {\n /**\n * We don't want to externalize any dependencies, we want everything to run thru vite.\n * Especially for CJS compatibility, etc.\n */\n noExternal: true,\n },\n}\n\n// Merge the CLI config's Vite config with the default Vite config\nlet viteConfig = defaultViteConfig\nif (typeof cliConfig?.vite === 'function') {\n viteConfig = (await cliConfig.vite(viteConfig, {\n command: 'build',\n isSsrBuild: true,\n mode: 'production',\n })) as InlineConfig\n} else if (isRecord(cliConfig?.vite)) {\n viteConfig = mergeConfig(viteConfig, cliConfig.vite)\n}\n\ndebug('Creating Vite server with config: %o', viteConfig)\n// Vite will build the files we give it - targetting Node.js instead of the browser.\n// We include the inject plugin in order to provide the stubs for the undefined global APIs.\nconst server = await createServer(viteConfig)\n\n// One-shot tasks (`studioWorkerTask`) resolve on their first message, and the\n// main thread historically terminate()d the worker right after — destroying\n// the worker's libuv loop while rolldown's native threads were still live.\n// The next `napi_call_threadsafe_function` then locked a destroyed mutex and\n// aborted the whole process (silent SIGABRT / exit code 134, reliably\n// reproduced on macOS). The lifecycle closes the Vite server BEFORE any\n// message reaches the main thread, and the main thread no longer terminates\n// one-shot workers at all (see `terminateOnSettle` in promisifyWorker).\nconst lifecycle =\n process.env.STUDIO_WORKER_ONE_SHOT === '1' && parentPort\n ? createOneShotWorkerLifecycle({\n closeServer: async () => {\n debug('Closing Vite server')\n await server.close()\n debug('Vite server closed')\n },\n onCloseError: (error) => debug('Failed to close Vite server: %o', error),\n parentPort,\n })\n : undefined\n\ntry {\n // Bit of a hack, but seems necessary based on the `node-vite` binary implementation\n await server.pluginContainer.buildStart({})\n\n // Load environment variables from `.env` files in the same way as Vite does.\n // Note that Sanity also provides environment variables through `process.env.*` for compat reasons,\n // and so we need to do the same here.\n // Load ALL env vars from .env files (not just studio-prefixed ones) so non-Sanity-prefixed\n // vars (e.g. NEXT_PUBLIC_*, VITE_*) are available via process.env at runtime.\n // The ??= on the next line prevents overwriting existing process.env values.\n const env = loadEnv(server.config.mode, server.config.envDir, '')\n for (const key in env) {\n process.env[key] ??= env[key]\n }\n\n // Now we're providing the glue that ensures node-specific loading and execution works.\n const node = new ViteNodeServer(server)\n\n // Should make it easier to debug any crashes in the imported code…\n installSourcemapsSupport({\n getSourceMap: (source) => node.getSourceMap(source),\n })\n\n const runner = new ViteNodeRunner({\n base: server.config.base,\n async fetchModule(id) {\n // Vite's SSR transform externalizes https:// imports, so Node's ESM loader\n // would reject them. We fetch the module over HTTP and run it through Vite's\n // SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*\n // format that ViteNodeRunner expects.\n if (isHttpsUrl(id)) {\n const {code: rawCode} = await fetchHttpModule(id)\n const result = await server.ssrTransform(rawCode, null, id)\n return {code: result?.code || rawCode}\n }\n return node.fetchModule(id)\n },\n resolveId(id, importer) {\n // Prevent vite-node from trying to resolve HTTP URLs through Node's resolver\n if (isHttpsUrl(id)) return {id}\n // Resolve any import from an HTTP-fetched module against the remote origin\n // (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)\n if (importer && isHttpsUrl(importer)) {\n return {id: new URL(id, importer).href}\n }\n return node.resolveId(id, importer)\n },\n root: server.config.root,\n })\n\n // Copied from `vite-node` - it appears that this applies the `define` config from\n // vite, but it also takes a surprisingly long time to execute. Not clear at this\n // point why this is, so we should investigate whether it's necessary or not.\n await runner.executeId('/@vite/env')\n\n await runner.executeId(workerScriptPath)\n} catch (error) {\n // Long-lived workers keep the original behavior: the error surfaces as a\n // Worker 'error' event.\n if (!lifecycle) {\n throw error\n }\n\n // One-shot workers close the server first and post a serialized error the\n // main thread rethrows, so the worker exits cleanly (code 0) and the real\n // error (e.g. a broken `sanity.config.ts`) isn't masked by a teardown abort.\n await lifecycle.postError(error)\n} finally {\n await lifecycle?.close()\n}\n"],"names":["isMainThread","parentPort","createServer","loadEnv","mergeConfig","ViteNodeRunner","ViteNodeServer","installSourcemapsSupport","subdebug","getCliConfig","isNotFoundError","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","createOneShotWorkerLifecycle","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","debug","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","applicationId","STUDIO_WORKER_APPLICATION_ID","cliConfig","err","console","warn","httpModuleCache","Map","fetchHttpModule","url","cached","get","code","response","fetch","signal","AbortSignal","timeout","ok","status","statusText","text","set","isHttpsUrl","id","startsWith","defaultViteConfig","build","target","configFile","define","__SANITY_APP_ID__","JSON","stringify","Object","fromEntries","entries","map","key","value","envPrefix","esbuild","jsx","logLevel","optimizeDeps","include","undefined","noDiscovery","resolve","tsconfigPaths","root","server","hmr","watch","ssr","noExternal","viteConfig","vite","command","isSsrBuild","mode","lifecycle","STUDIO_WORKER_ONE_SHOT","closeServer","close","onCloseError","error","pluginContainer","buildStart","config","envDir","node","getSourceMap","source","runner","base","fetchModule","rawCode","result","ssrTransform","resolveId","importer","URL","href","executeId","postError"],"mappings":"AAAA,SAAQA,YAAY,EAAEC,UAAU,QAAO,sBAAqB;AAE5D,SAAQC,YAAY,EAAqBC,OAAO,EAAEC,WAAW,QAAO,OAAM;AAC1E,SAAQC,cAAc,QAAO,mBAAkB;AAC/C,SAAQC,cAAc,QAAO,mBAAkB;AAC/C,SAAQC,wBAAwB,QAAO,uBAAsB;AAE7D,SAAQC,QAAQ,QAAO,0BAAyB;AAChD,SAAQC,YAAY,QAAO,mCAAkC;AAE7D,SAAQC,eAAe,QAAO,gCAA+B;AAC7D,SAAQC,6BAA6B,QAAO,0DAAyD;AACrG,SAAQC,iBAAiB,QAAO,8CAA6C,CAAC,2EAA2E;AACzJ,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,4BAA4B,QAAO,6BAA4B;AAEvE,IAAId,cAAc;IAChB,MAAM,IAAIe,MAAM;AAClB;A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AAI;gBAAA;YACxC;YACA,OAAOZ,KAAKS,SAAS,CAACxD,IAAIyD;QAC5B;QACA/B,MAAMC,OAAOkB,MAAM,CAACnB,IAAI;IAC1B;IAEA,kFAAkF;IAClF,iFAAiF;IACjF,6EAA6E;IAC7E,MAAMwB,OAAOU,SAAS,CAAC;IAEvB,MAAMV,OAAOU,SAAS,CAACvF;AACzB,EAAE,OAAOqE,OAAO;IACd,yEAAyE;IACzE,wBAAwB;IACxB,IAAI,CAACL,WAAW;QACd,MAAMK;IACR;IAEA,0EAA0E;IAC1E,0EAA0E;IAC1E,6EAA6E;IAC7E,MAAML,UAAUwB,SAAS,CAACnB;AAC5B,SAAU;IACR,MAAML,WAAWG;AACnB"}
|
|
@@ -35,11 +35,14 @@ import { deserializeStudioWorkerError, isStudioWorkerErrorMessage } from './stud
|
|
|
35
35
|
if (!/\.worker\.(js|ts)$/.test(normalizedFilePath)) {
|
|
36
36
|
throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path');
|
|
37
37
|
}
|
|
38
|
-
const { studioRootPath, timeout, ...workerOptions } = options;
|
|
38
|
+
const { applicationId, studioRootPath, timeout, ...workerOptions } = options;
|
|
39
39
|
const workerPromise = promisifyWorker(new URL('studioWorkerLoader.worker.js', import.meta.url), {
|
|
40
40
|
...workerOptions,
|
|
41
41
|
env: {
|
|
42
42
|
...isRecord(workerOptions.env) ? workerOptions.env : process.env,
|
|
43
|
+
...applicationId ? {
|
|
44
|
+
STUDIO_WORKER_APPLICATION_ID: applicationId
|
|
45
|
+
} : {},
|
|
43
46
|
// Tasks spawned here are one-shot: the loader closes its Vite
|
|
44
47
|
// (rolldown) server before any message reaches the main thread, so
|
|
45
48
|
// teardown can never race rolldown's native threads (SIGABRT on
|
|
@@ -93,10 +96,14 @@ import { deserializeStudioWorkerError, isStudioWorkerErrorMessage } from './stud
|
|
|
93
96
|
if (!/\.worker\.(js|ts)$/.test(normalizedFilePath)) {
|
|
94
97
|
throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path');
|
|
95
98
|
}
|
|
99
|
+
const { applicationId, ...workerOptions } = options;
|
|
96
100
|
return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {
|
|
97
|
-
...
|
|
101
|
+
...workerOptions,
|
|
98
102
|
env: {
|
|
99
|
-
...isRecord(
|
|
103
|
+
...isRecord(workerOptions.env) ? workerOptions.env : process.env,
|
|
104
|
+
...applicationId ? {
|
|
105
|
+
STUDIO_WORKER_APPLICATION_ID: applicationId
|
|
106
|
+
} : {},
|
|
100
107
|
STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,
|
|
101
108
|
STUDIO_WORKER_TASK_FILE: normalizedFilePath
|
|
102
109
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerTask.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\nimport {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\nimport {\n deserializeStudioWorkerError,\n isStudioWorkerErrorMessage,\n type StudioWorkerErrorMessage,\n} from './studioWorkerLifecycle.js'\n\n/**\n * Options for the studio worker task\n *\n * @internal\n */\ninterface StudioWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n studioRootPath: string\n\n /** Optional timeout in milliseconds. If the worker does not respond within this time, the promise is rejected. */\n timeout?: number\n}\n\n/**\n * Executes a worker file in a Sanity Studio browser context.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function studioWorkerTask<T = unknown>(\n filePath: URL,\n options: StudioWorkerTaskOptions,\n): Promise<T> {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n const {studioRootPath, timeout, ...workerOptions} = options\n const workerPromise = promisifyWorker<StudioWorkerErrorMessage | T>(\n new URL('studioWorkerLoader.worker.js', import.meta.url),\n {\n ...workerOptions,\n env: {\n ...(isRecord(workerOptions.env) ? workerOptions.env : process.env),\n // Tasks spawned here are one-shot: the loader closes its Vite\n // (rolldown) server before any message reaches the main thread, so\n // teardown can never race rolldown's native threads (SIGABRT on\n // macOS). Long-lived workers (`createStudioWorker`) must NOT set it.\n STUDIO_WORKER_ONE_SHOT: '1',\n STUDIO_WORKER_STUDIO_ROOT_PATH: studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n // Never terminate() a worker hosting rolldown's native threads — let it\n // exit on its own (it closes its server first) or tear down with the\n // process.\n terminateOnSettle: false,\n timeout,\n },\n )\n\n return workerPromise.then((result) => {\n if (isStudioWorkerErrorMessage(result)) {\n throw deserializeStudioWorkerError(result)\n }\n\n return result\n })\n}\n\n/**\n * Creates a new worker for a studio worker task.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function createStudioWorker(filePath: URL, options: StudioWorkerTaskOptions) {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {\n ...
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerTask.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\nimport {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\nimport {\n deserializeStudioWorkerError,\n isStudioWorkerErrorMessage,\n type StudioWorkerErrorMessage,\n} from './studioWorkerLifecycle.js'\n\n/**\n * Options for the studio worker task\n *\n * @internal\n */\ninterface StudioWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n studioRootPath: string\n\n applicationId?: string\n\n /** Optional timeout in milliseconds. If the worker does not respond within this time, the promise is rejected. */\n timeout?: number\n}\n\n/**\n * Executes a worker file in a Sanity Studio browser context.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function studioWorkerTask<T = unknown>(\n filePath: URL,\n options: StudioWorkerTaskOptions,\n): Promise<T> {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n const {applicationId, studioRootPath, timeout, ...workerOptions} = options\n const workerPromise = promisifyWorker<StudioWorkerErrorMessage | T>(\n new URL('studioWorkerLoader.worker.js', import.meta.url),\n {\n ...workerOptions,\n env: {\n ...(isRecord(workerOptions.env) ? workerOptions.env : process.env),\n ...(applicationId ? {STUDIO_WORKER_APPLICATION_ID: applicationId} : {}),\n // Tasks spawned here are one-shot: the loader closes its Vite\n // (rolldown) server before any message reaches the main thread, so\n // teardown can never race rolldown's native threads (SIGABRT on\n // macOS). Long-lived workers (`createStudioWorker`) must NOT set it.\n STUDIO_WORKER_ONE_SHOT: '1',\n STUDIO_WORKER_STUDIO_ROOT_PATH: studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n // Never terminate() a worker hosting rolldown's native threads — let it\n // exit on its own (it closes its server first) or tear down with the\n // process.\n terminateOnSettle: false,\n timeout,\n },\n )\n\n return workerPromise.then((result) => {\n if (isStudioWorkerErrorMessage(result)) {\n throw deserializeStudioWorkerError(result)\n }\n\n return result\n })\n}\n\n/**\n * Creates a new worker for a studio worker task.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function createStudioWorker(filePath: URL, options: StudioWorkerTaskOptions) {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n const {applicationId, ...workerOptions} = options\n\n return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {\n ...workerOptions,\n env: {\n ...(isRecord(workerOptions.env) ? workerOptions.env : process.env),\n ...(applicationId ? {STUDIO_WORKER_APPLICATION_ID: applicationId} : {}),\n STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n })\n}\n"],"names":["fileURLToPath","Worker","isRecord","promisifyWorker","deserializeStudioWorkerError","isStudioWorkerErrorMessage","studioWorkerTask","filePath","options","normalizedFilePath","test","Error","applicationId","studioRootPath","timeout","workerOptions","workerPromise","URL","url","env","process","STUDIO_WORKER_APPLICATION_ID","STUDIO_WORKER_ONE_SHOT","STUDIO_WORKER_STUDIO_ROOT_PATH","STUDIO_WORKER_TASK_FILE","terminateOnSettle","then","result","createStudioWorker"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AACtC,SAAQC,MAAM,QAA2B,sBAAqB;AAG9D,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,gCAA+B;AAC7D,SACEC,4BAA4B,EAC5BC,0BAA0B,QAErB,6BAA4B;AAgBnC;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,iBACdC,QAAa,EACbC,OAAgC;IAEhC,MAAMC,qBAAqBT,cAAcO;IAEzC,IAAI,CAAC,qBAAqBG,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,MAAM,EAACC,aAAa,EAAEC,cAAc,EAAEC,OAAO,EAAE,GAAGC,eAAc,GAAGP;IACnE,MAAMQ,gBAAgBb,gBACpB,IAAIc,IAAI,gCAAgC,YAAYC,GAAG,GACvD;QACE,GAAGH,aAAa;QAChBI,KAAK;YACH,GAAIjB,SAASa,cAAcI,GAAG,IAAIJ,cAAcI,GAAG,GAAGC,QAAQD,GAAG;YACjE,GAAIP,gBAAgB;gBAACS,8BAA8BT;YAAa,IAAI,CAAC,CAAC;YACtE,8DAA8D;YAC9D,mEAAmE;YACnE,gEAAgE;YAChE,qEAAqE;YACrEU,wBAAwB;YACxBC,gCAAgCV;YAChCW,yBAAyBf;QAC3B;QACA,wEAAwE;QACxE,qEAAqE;QACrE,WAAW;QACXgB,mBAAmB;QACnBX;IACF;IAGF,OAAOE,cAAcU,IAAI,CAAC,CAACC;QACzB,IAAItB,2BAA2BsB,SAAS;YACtC,MAAMvB,6BAA6BuB;QACrC;QAEA,OAAOA;IACT;AACF;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,mBAAmBrB,QAAa,EAAEC,OAAgC;IAChF,MAAMC,qBAAqBT,cAAcO;IAEzC,IAAI,CAAC,qBAAqBG,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,MAAM,EAACC,aAAa,EAAE,GAAGG,eAAc,GAAGP;IAE1C,OAAO,IAAIP,OAAO,IAAIgB,IAAI,gCAAgC,YAAYC,GAAG,GAAG;QAC1E,GAAGH,aAAa;QAChBI,KAAK;YACH,GAAIjB,SAASa,cAAcI,GAAG,IAAIJ,cAAcI,GAAG,GAAGC,QAAQD,GAAG;YACjE,GAAIP,gBAAgB;gBAACS,8BAA8BT;YAAa,IAAI,CAAC,CAAC;YACtEW,gCAAgCf,QAAQK,cAAc;YACtDW,yBAAyBf;QAC3B;IACF;AACF"}
|
|
@@ -8,6 +8,7 @@ import { URL as URL$1 } from "node:url";
|
|
|
8
8
|
*/
|
|
9
9
|
interface StudioWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {
|
|
10
10
|
studioRootPath: string;
|
|
11
|
+
applicationId?: string;
|
|
11
12
|
/** Optional timeout in milliseconds. If the worker does not respond within this time, the promise is rejected. */
|
|
12
13
|
timeout?: number;
|
|
13
14
|
}
|
|
@@ -94,4 +95,4 @@ interface TsxWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {
|
|
|
94
95
|
*/
|
|
95
96
|
declare function tsxWorkerTask<T = unknown>(filePath: URL$1, options: TsxWorkerTaskOptions): Promise<T>;
|
|
96
97
|
export { createStudioWorker as n, studioWorkerTask as r, tsxWorkerTask as t };
|
|
97
|
-
//# sourceMappingURL=tsxWorkerTask-
|
|
98
|
+
//# sourceMappingURL=tsxWorkerTask-MHWcAqb6.d.ts.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export function isUnattended({ isInteractive, json, yes }) {
|
|
2
|
+
return Boolean(yes || json || !isInteractive);
|
|
3
|
+
}
|
|
4
|
+
export function isUnattendedInvocation({ argv, isInteractive }) {
|
|
5
|
+
const separatorIndex = argv.indexOf('--');
|
|
6
|
+
const optionArguments = argv.slice(0, separatorIndex === -1 ? argv.length : separatorIndex);
|
|
7
|
+
return isUnattended({
|
|
8
|
+
isInteractive,
|
|
9
|
+
json: optionArguments.includes('--json'),
|
|
10
|
+
// oclif splits alphabetic short flag bundles from left to right, so a leading -y is unambiguous.
|
|
11
|
+
yes: optionArguments.some((argument)=>argument === '--yes' || /^-y[a-zA-Z]*$/.test(argument))
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=isUnattended.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/util/isUnattended.ts"],"sourcesContent":["interface IsUnattendedOptions {\n isInteractive: boolean\n\n json?: boolean\n yes?: boolean\n}\n\ninterface IsUnattendedInvocationOptions {\n argv: string[]\n isInteractive: boolean\n}\n\nexport function isUnattended({isInteractive, json, yes}: IsUnattendedOptions): boolean {\n return Boolean(yes || json || !isInteractive)\n}\n\nexport function isUnattendedInvocation({\n argv,\n isInteractive,\n}: IsUnattendedInvocationOptions): boolean {\n const separatorIndex = argv.indexOf('--')\n const optionArguments = argv.slice(0, separatorIndex === -1 ? argv.length : separatorIndex)\n\n return isUnattended({\n isInteractive,\n json: optionArguments.includes('--json'),\n // oclif splits alphabetic short flag bundles from left to right, so a leading -y is unambiguous.\n yes: optionArguments.some((argument) => argument === '--yes' || /^-y[a-zA-Z]*$/.test(argument)),\n })\n}\n"],"names":["isUnattended","isInteractive","json","yes","Boolean","isUnattendedInvocation","argv","separatorIndex","indexOf","optionArguments","slice","length","includes","some","argument","test"],"mappings":"AAYA,OAAO,SAASA,aAAa,EAACC,aAAa,EAAEC,IAAI,EAAEC,GAAG,EAAsB;IAC1E,OAAOC,QAAQD,OAAOD,QAAQ,CAACD;AACjC;AAEA,OAAO,SAASI,uBAAuB,EACrCC,IAAI,EACJL,aAAa,EACiB;IAC9B,MAAMM,iBAAiBD,KAAKE,OAAO,CAAC;IACpC,MAAMC,kBAAkBH,KAAKI,KAAK,CAAC,GAAGH,mBAAmB,CAAC,IAAID,KAAKK,MAAM,GAAGJ;IAE5E,OAAOP,aAAa;QAClBC;QACAC,MAAMO,gBAAgBG,QAAQ,CAAC;QAC/B,iGAAiG;QACjGT,KAAKM,gBAAgBI,IAAI,CAAC,CAACC,WAAaA,aAAa,WAAW,gBAAgBC,IAAI,CAACD;IACvF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/cli-core",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.5.0",
|
|
4
4
|
"description": "Sanity CLI core package",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -57,6 +57,10 @@
|
|
|
57
57
|
"source": "./src/executionContext.ts",
|
|
58
58
|
"default": "./dist/executionContext.js"
|
|
59
59
|
},
|
|
60
|
+
"./flags": {
|
|
61
|
+
"source": "./src/_exports/flags.ts",
|
|
62
|
+
"default": "./dist/_exports/flags.js"
|
|
63
|
+
},
|
|
60
64
|
"./package-manager": {
|
|
61
65
|
"source": "./src/_exports/package-manager.ts",
|
|
62
66
|
"default": "./dist/_exports/package-manager.js"
|