@sanity/cli-core 3.3.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/config.d.ts +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 +3 -3
- package/dist/_exports/schemas.d.ts +1 -1
- package/dist/_exports/tasks.d.ts +1 -1
- package/dist/_exports/types.d.ts +2 -2
- package/dist/_exports/util.d.ts +21 -2
- package/dist/_exports/util.js +2 -0
- package/dist/_exports/util.js.map +1 -1
- package/dist/config/cli/getCliConfig.js +5 -4
- package/dist/config/cli/getCliConfig.js.map +1 -1
- package/dist/config/cli/getCliConfigSync.js +5 -4
- package/dist/config/cli/getCliConfigSync.js.map +1 -1
- package/dist/config/cli/workbenchApp.js +26 -13
- package/dist/config/cli/workbenchApp.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/manifest.js +8 -2
- package/dist/manifest.js.map +1 -1
- package/dist/{schemas-PPIe9Jz0.d.ts → schemas-D1LxkXeZ.d.ts} +9 -3
- 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/dist/{workbenchApp-BkQHUXxH.d.ts → workbenchApp-DVKwpTyU.d.ts} +11 -5
- 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,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,eAAe,QAAO,8BAA6B;AAC3D,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,QAAQb,SAAS;AAmBvB,OAAO,MAAec,sBACZf;IAGEgB,KAAc;IACdC,MAAgB;IAE1B;;;;;;;GAOC,GACD,AAAUC,qBAAqB,CAACF,OAAiCd,mBAAmBc,MAAK;IAEzF;;;;;;;GAOC,GACD,AAAUG,sBAAsB,CAACH,OAAkCb,oBAAoBa,MAAK;IAE5F;;;;;;;;;GASC,GACD,AAAOI,SAAiB;QACtBC,OAAO,IAAI,CAACA,KAAK,CAACC,IAAI,CAAC,IAAI;QAC3BC,KAAK,IAAI,CAACA,GAAG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IgC,QAAQI,MAAM,CAACvE,OAAO+B,YAAYb;IAC7D;IAEA;;;;GAIC,GACD,AAAOgD,uBAAgC;QACrC,OAAOnD;IACT;IAEA;;;;;GAKC,GACD,AAAOyD,wBAAmD;QACxD,IAAI,CAAC7D,0BAA0B;YAC7B,MAAM,IAAI8D,MAAM;QAClB;QACA,OAAO,IAAI,CAACC,IAAI;IAClB;IAEA;;;;;;;GAOC,GACD,MAAgBC,kBAAsC;QACpD,IAAI;YACF,OAAO,MAAM,IAAI,CAACrE,YAAY;QAChC,EAAE,OAAOuB,KAAK;YACZ,IAAI,CAAEA,CAAAA,eAAenB,wBAAuB,GAAI,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"}
|
|
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,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO,QAAmB,cAAa;AAG/C,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,iCAAiC,QAAO,sBAAqB;AACrE,SACEC,kBAAkB,EAClBC,mBAAmB,QAGd,iBAAgB;AACvB,SAAQC,YAAY,QAAO,+BAA8B;AAEzD,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,SAAQC,eAAe,QAAO,8BAA6B;AAC3D,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;AACrD,SAAQC,sBAAsB,EAAEC,gBAAgBC,mBAAmB,QAAO,yBAAwB;AAUlG,MAAMC,QAAQjB,SAAS;AAmBvB,OAAO,MAAekB,sBACZnB;IAGEoB,KAAc;IACdC,MAAgB;IAE1B;;;;;;;GAOC,GACD,AAAUC,qBAAqB,CAACF,OAAiCjB,mBAAmBiB,MAAK;IAEzF;;;;;;;GAOC,GACD,AAAUG,sBAAsB,CAACH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D;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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as ConfigStore, o as TypeGenConfig, r as CliConfig } from "../cliConfig-DUt8uaF6.js";
|
|
2
2
|
import { _ as CliTokenInfo, a as getStudioWorkspaces, c as findProjectRoot, d as getCliConfigUncached, f as getCliToken, g as setCliUserConfig, h as getUserConfig, i as isStudioConfig, l as getCliConfigSync, m as getCliUserConfig, n as tryFindStudioConfigPath, o as getStudioConfig, p as getCliTokenInfo, r as findPathForFiles, s as findProjectRootSync, t as findStudioConfigPath, u as getCliConfig, v as clearCliTokenCache } from "../findStudioConfigPath-BV4DCesQ.js";
|
|
3
|
-
import { n as isWorkbenchApp, r as parseWorkbenchCliConfig } from "../workbenchApp-
|
|
3
|
+
import { n as isWorkbenchApp, r as parseWorkbenchCliConfig } from "../workbenchApp-DVKwpTyU.js";
|
|
4
4
|
import { a as getSanityDataDir, i as getSanityConfigDir, n as getSanityUrl, r as getSanityEnvVar, t as getWorkspace } from "../getWorkspace-CU32E6Uo.js";
|
|
5
5
|
export { type CliConfig, type CliTokenInfo, type ConfigStore, type TypeGenConfig, clearCliTokenCache, findPathForFiles, findProjectRoot, findProjectRootSync, findStudioConfigPath, getCliConfig, getCliConfigSync, getCliConfigUncached, getCliToken, getCliTokenInfo, getCliUserConfig, getSanityConfigDir, getSanityDataDir, getSanityEnvVar, getSanityUrl, getStudioConfig, getStudioWorkspaces, getUserConfig, getWorkspace, isStudioConfig, isWorkbenchApp, parseWorkbenchCliConfig, setCliUserConfig, tryFindStudioConfigPath };
|
|
@@ -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
|
@@ -6,19 +6,19 @@ import { n as RequireProps, r as SanityOrgUser, t as Output } from "../types-CwJ
|
|
|
6
6
|
import { SanityCommand, SanityCommandInterface } from "../SanityCommand.js";
|
|
7
7
|
import { t as mockBrowserEnvironment } from "../mockBrowserEnvironment-BjFQPb2W.js";
|
|
8
8
|
import { _ as CliTokenInfo, a as getStudioWorkspaces, c as findProjectRoot, d as getCliConfigUncached, f as getCliToken, g as setCliUserConfig, h as getUserConfig, i as isStudioConfig, l as getCliConfigSync, m as getCliUserConfig, n as tryFindStudioConfigPath, o as getStudioConfig, p as getCliTokenInfo, r as findPathForFiles, s as findProjectRootSync, t as findStudioConfigPath, u as getCliConfig, v as clearCliTokenCache } from "../findStudioConfigPath-BV4DCesQ.js";
|
|
9
|
-
import { n as isWorkbenchApp, t as ApplicationType } from "../workbenchApp-
|
|
9
|
+
import { n as isWorkbenchApp, t as ApplicationType } from "../workbenchApp-DVKwpTyU.js";
|
|
10
10
|
import { a as getSanityDataDir, i as getSanityConfigDir, n as getSanityUrl, r as getSanityEnvVar, t as getWorkspace } from "../getWorkspace-CU32E6Uo.js";
|
|
11
11
|
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";
|
|
19
19
|
import { n as ReadPackageJsonOptions, r as readPackageJson, t as PackageJson } from "../readPackageJson-Cr_lbjVR.js";
|
|
20
20
|
import { n as colorizeJson, t as getTimer } from "../timer-Dwu2TIgB.js";
|
|
21
|
-
import { i as studioManifestSchema, n as StudioManifest, r as coreAppManifestSchema, t as CoreAppManifest } from "../schemas-
|
|
21
|
+
import { i as studioManifestSchema, n as StudioManifest, r as coreAppManifestSchema, t as CoreAppManifest } from "../schemas-D1LxkXeZ.js";
|
|
22
22
|
import { WorkerOptions } from "node:worker_threads";
|
|
23
23
|
interface PromisifyWorkerOptions extends WorkerOptions {
|
|
24
24
|
/**
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as cliConfigSchema, i as studioManifestSchema, n as StudioManifest, r as coreAppManifestSchema, t as CoreAppManifest } from "../schemas-
|
|
1
|
+
import { a as cliConfigSchema, i as studioManifestSchema, n as StudioManifest, r as coreAppManifestSchema, t as CoreAppManifest } from "../schemas-D1LxkXeZ.js";
|
|
2
2
|
export { type CoreAppManifest, type StudioManifest, cliConfigSchema, coreAppManifestSchema, studioManifestSchema };
|
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/types.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { t as ProjectRootResult } from "../recursivelyResolveProjectRoot-BE54uEP
|
|
|
3
3
|
import { n as ConsentInformation, r as TelemetryUserProperties, t as CLITelemetryStore } from "../types-ZNH3prAd.js";
|
|
4
4
|
import { n as RequireProps, r as SanityOrgUser, t as Output } from "../types-CwJLTYDj.js";
|
|
5
5
|
import { SanityCommandInterface } from "../SanityCommand.js";
|
|
6
|
-
import { t as ApplicationType } from "../workbenchApp-
|
|
6
|
+
import { t as ApplicationType } from "../workbenchApp-DVKwpTyU.js";
|
|
7
7
|
import { n as ReadPackageJsonOptions, t as PackageJson } from "../readPackageJson-Cr_lbjVR.js";
|
|
8
|
-
import { n as StudioManifest, t as CoreAppManifest } from "../schemas-
|
|
8
|
+
import { n as StudioManifest, t as CoreAppManifest } from "../schemas-D1LxkXeZ.js";
|
|
9
9
|
export type { ApplicationType, CLITelemetryStore, CliConfig, ConfigStore, ConsentInformation, CoreAppManifest, Output, PackageJson, ProjectRootResult, ReactCompilerConfig, ReadPackageJsonOptions, RequireProps, SanityCommandInterface, SanityOrgUser, StudioManifest, TelemetryUserProperties, TypeGenConfig, UserViteConfig };
|
package/dist/_exports/util.d.ts
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
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
|
+
/**
|
|
5
|
+
* Checks if the given value is a record (javascript objectish)
|
|
6
|
+
*
|
|
7
|
+
* @param value - Value to check
|
|
8
|
+
* @returns True if the value is a record, false otherwise
|
|
9
|
+
* @internal
|
|
10
|
+
*/
|
|
11
|
+
declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
4
12
|
declare function isTrueish(value: string | undefined): boolean;
|
|
5
|
-
|
|
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 };
|
|
6
25
|
//# sourceMappingURL=util.d.ts.map
|
package/dist/_exports/util.js
CHANGED
|
@@ -9,8 +9,10 @@ export { getWorkspace } from '../util/getWorkspace.js';
|
|
|
9
9
|
export { importModule } from '../util/importModule.js';
|
|
10
10
|
export { isCi } from '../util/isCi.js';
|
|
11
11
|
export { isInteractive } from '../util/isInteractive.js';
|
|
12
|
+
export { isRecord } from '../util/isRecord.js';
|
|
12
13
|
export { isStaging } from '../util/isStaging.js';
|
|
13
14
|
export { isTrueish } from '../util/isTrueish.js';
|
|
15
|
+
export { isUnattended, isUnattendedInvocation } from '../util/isUnattended.js';
|
|
14
16
|
export { normalizePath } from '../util/normalizePath.js';
|
|
15
17
|
export { safeStructuredClone } from '../util/safeStructuredClone.js';
|
|
16
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 {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","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,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"}
|
|
@@ -5,7 +5,7 @@ import { NotFoundError } from '../../errors/NotFoundError.js';
|
|
|
5
5
|
import { importModule } from '../../util/importModule.js';
|
|
6
6
|
import { findPathForFiles } from '../util/findConfigsPaths.js';
|
|
7
7
|
import { cliConfigSchema } from './schemas.js';
|
|
8
|
-
import { isWorkbenchApp, parseWorkbenchCliConfig } from './workbenchApp.js';
|
|
8
|
+
import { isWorkbenchApp, isWorkbenchConfig, parseWorkbenchCliConfig } from './workbenchApp.js';
|
|
9
9
|
const cache = new Map();
|
|
10
10
|
/**
|
|
11
11
|
* Get the CLI config for a project, given the root path.
|
|
@@ -83,9 +83,10 @@ const cache = new Map();
|
|
|
83
83
|
cause: err
|
|
84
84
|
});
|
|
85
85
|
}
|
|
86
|
-
// Branch as early as possible: a branded `
|
|
87
|
-
//
|
|
88
|
-
|
|
86
|
+
// Branch as early as possible: a branded `defineApplication(...)` app or a
|
|
87
|
+
// branded `unstable_defineMediaLibrary(...)` config opts into workbench
|
|
88
|
+
// behavior, so its `app` skips the legacy `app` schema entirely.
|
|
89
|
+
if (isWorkbenchApp(cliConfig?.app) || isWorkbenchConfig(cliConfig?.app)) {
|
|
89
90
|
return parseWorkbenchCliConfig(cliConfig, dirname(configPath));
|
|
90
91
|
}
|
|
91
92
|
const { data, error, success } = cliConfigSchema.safeParse(cliConfig);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/cli/getCliConfig.ts"],"sourcesContent":["import {createRequire} from 'node:module'\nimport {dirname} from 'node:path'\n\nimport {debug} from '../../_exports/debug.js'\nimport {NotFoundError} from '../../errors/NotFoundError.js'\nimport {importModule} from '../../util/importModule.js'\nimport {findPathForFiles} from '../util/findConfigsPaths.js'\nimport {cliConfigSchema} from './schemas.js'\nimport {type CliConfig} from './types/cliConfig.js'\nimport {isWorkbenchApp, parseWorkbenchCliConfig} from './workbenchApp.js'\n\nconst cache = new Map<string, Promise<CliConfig>>()\n\n/**\n * Get the CLI config for a project, given the root path.\n *\n * Results are cached in-memory keyed by rootPath for the lifetime of the\n * process. Since the CLI always runs from a single project root, the config\n * won't change during a command's execution, so caching avoids redundant\n * filesystem reads and jiti imports from the prerun hook, SanityCommand\n * helpers, and action files.\n *\n * If loading fails the cached promise is evicted so the next call retries.\n *\n * Long-lived processes that need to observe edits to `sanity.cli.(ts|js)`\n * (e.g. a dev-server watcher) should use {@link getCliConfigUncached}\n * instead — it bypasses both this in-memory cache and Node's module cache.\n *\n * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.\n * @returns The CLI config\n * @internal\n */\nexport function getCliConfig(rootPath: string): Promise<CliConfig> {\n const cached = cache.get(rootPath)\n if (cached) {\n return cached\n }\n\n const promise = getCliConfigUncached(rootPath).catch((err) => {\n cache.delete(rootPath)\n throw err\n })\n\n cache.set(rootPath, promise)\n return promise\n}\n\n/**\n * Read the CLI config for a project from disk, bypassing both the\n * `getCliConfig` in-memory cache and Node's module cache. Each call locates\n * `sanity.cli.(ts|js)`, drops any prior jiti compilation from `require.cache`,\n * re-imports, and re-validates.\n *\n * Use this when the config file is expected to change during the process's\n * lifetime — typically a dev-server watcher that needs the new values picked\n * up after each save. One-shot CLI invocations should prefer\n * {@link getCliConfig} so the prerun hook, SanityCommand helpers, and action\n * files share a single load.\n *\n * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.\n * @returns The freshly loaded CLI config\n * @internal\n */\nexport async function getCliConfigUncached(rootPath: string): Promise<CliConfig> {\n const paths = await findPathForFiles(rootPath, ['sanity.cli.ts', 'sanity.cli.js'])\n const configPaths = paths.filter((path) => path.exists)\n\n if (configPaths.length === 0) {\n throw new NotFoundError(`No CLI config found at ${rootPath}/sanity.cli.(ts|js)`)\n }\n\n if (configPaths.length > 1) {\n throw new Error(\n `Multiple CLI config files found (${configPaths.map((path) => path.path).join(', ')})`,\n )\n }\n\n const configPath = configPaths[0].path\n\n debug(`Loading CLI config from: ${configPath}`)\n\n // Drop any cached compilation of this file from Node's CJS module cache\n // (jiti compiles `sanity.cli.ts` to CJS and registers it via `require.cache`).\n // Without this, repeated calls would receive the previously imported module\n // even though the file on disk has changed. No-op on first load.\n const cjsRequire = createRequire(import.meta.url)\n delete cjsRequire.cache[configPath]\n\n let cliConfig: CliConfig | undefined\n try {\n const result = await importModule<CliConfig>(configPath)\n\n debug('CLI config loaded: %o', result)\n\n cliConfig = result\n } catch (err) {\n debug('Failed to load CLI config in worker thread: %s', err)\n\n throw new Error('CLI config cannot be loaded', {cause: err})\n }\n\n // Branch as early as possible: a branded `
|
|
1
|
+
{"version":3,"sources":["../../../src/config/cli/getCliConfig.ts"],"sourcesContent":["import {createRequire} from 'node:module'\nimport {dirname} from 'node:path'\n\nimport {debug} from '../../_exports/debug.js'\nimport {NotFoundError} from '../../errors/NotFoundError.js'\nimport {importModule} from '../../util/importModule.js'\nimport {findPathForFiles} from '../util/findConfigsPaths.js'\nimport {cliConfigSchema} from './schemas.js'\nimport {type CliConfig} from './types/cliConfig.js'\nimport {isWorkbenchApp, isWorkbenchConfig, parseWorkbenchCliConfig} from './workbenchApp.js'\n\nconst cache = new Map<string, Promise<CliConfig>>()\n\n/**\n * Get the CLI config for a project, given the root path.\n *\n * Results are cached in-memory keyed by rootPath for the lifetime of the\n * process. Since the CLI always runs from a single project root, the config\n * won't change during a command's execution, so caching avoids redundant\n * filesystem reads and jiti imports from the prerun hook, SanityCommand\n * helpers, and action files.\n *\n * If loading fails the cached promise is evicted so the next call retries.\n *\n * Long-lived processes that need to observe edits to `sanity.cli.(ts|js)`\n * (e.g. a dev-server watcher) should use {@link getCliConfigUncached}\n * instead — it bypasses both this in-memory cache and Node's module cache.\n *\n * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.\n * @returns The CLI config\n * @internal\n */\nexport function getCliConfig(rootPath: string): Promise<CliConfig> {\n const cached = cache.get(rootPath)\n if (cached) {\n return cached\n }\n\n const promise = getCliConfigUncached(rootPath).catch((err) => {\n cache.delete(rootPath)\n throw err\n })\n\n cache.set(rootPath, promise)\n return promise\n}\n\n/**\n * Read the CLI config for a project from disk, bypassing both the\n * `getCliConfig` in-memory cache and Node's module cache. Each call locates\n * `sanity.cli.(ts|js)`, drops any prior jiti compilation from `require.cache`,\n * re-imports, and re-validates.\n *\n * Use this when the config file is expected to change during the process's\n * lifetime — typically a dev-server watcher that needs the new values picked\n * up after each save. One-shot CLI invocations should prefer\n * {@link getCliConfig} so the prerun hook, SanityCommand helpers, and action\n * files share a single load.\n *\n * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.\n * @returns The freshly loaded CLI config\n * @internal\n */\nexport async function getCliConfigUncached(rootPath: string): Promise<CliConfig> {\n const paths = await findPathForFiles(rootPath, ['sanity.cli.ts', 'sanity.cli.js'])\n const configPaths = paths.filter((path) => path.exists)\n\n if (configPaths.length === 0) {\n throw new NotFoundError(`No CLI config found at ${rootPath}/sanity.cli.(ts|js)`)\n }\n\n if (configPaths.length > 1) {\n throw new Error(\n `Multiple CLI config files found (${configPaths.map((path) => path.path).join(', ')})`,\n )\n }\n\n const configPath = configPaths[0].path\n\n debug(`Loading CLI config from: ${configPath}`)\n\n // Drop any cached compilation of this file from Node's CJS module cache\n // (jiti compiles `sanity.cli.ts` to CJS and registers it via `require.cache`).\n // Without this, repeated calls would receive the previously imported module\n // even though the file on disk has changed. No-op on first load.\n const cjsRequire = createRequire(import.meta.url)\n delete cjsRequire.cache[configPath]\n\n let cliConfig: CliConfig | undefined\n try {\n const result = await importModule<CliConfig>(configPath)\n\n debug('CLI config loaded: %o', result)\n\n cliConfig = result\n } catch (err) {\n debug('Failed to load CLI config in worker thread: %s', err)\n\n throw new Error('CLI config cannot be loaded', {cause: err})\n }\n\n // Branch as early as possible: a branded `defineApplication(...)` app or a\n // branded `unstable_defineMediaLibrary(...)` config opts into workbench\n // behavior, so its `app` skips the legacy `app` schema entirely.\n if (isWorkbenchApp(cliConfig?.app) || isWorkbenchConfig(cliConfig?.app)) {\n return parseWorkbenchCliConfig(cliConfig, dirname(configPath))\n }\n\n const {data, error, success} = cliConfigSchema.safeParse(cliConfig)\n if (!success) {\n debug(`Invalid CLI config: ${error.message}`)\n throw new Error(`Invalid CLI config: ${error.message}`, {cause: error})\n }\n\n return data\n}\n"],"names":["createRequire","dirname","debug","NotFoundError","importModule","findPathForFiles","cliConfigSchema","isWorkbenchApp","isWorkbenchConfig","parseWorkbenchCliConfig","cache","Map","getCliConfig","rootPath","cached","get","promise","getCliConfigUncached","catch","err","delete","set","paths","configPaths","filter","path","exists","length","Error","map","join","configPath","cjsRequire","url","cliConfig","result","cause","app","data","error","success","safeParse","message"],"mappings":"AAAA,SAAQA,aAAa,QAAO,cAAa;AACzC,SAAQC,OAAO,QAAO,YAAW;AAEjC,SAAQC,KAAK,QAAO,0BAAyB;AAC7C,SAAQC,aAAa,QAAO,gCAA+B;AAC3D,SAAQC,YAAY,QAAO,6BAA4B;AACvD,SAAQC,gBAAgB,QAAO,8BAA6B;AAC5D,SAAQC,eAAe,QAAO,eAAc;AAE5C,SAAQC,cAAc,EAAEC,iBAAiB,EAAEC,uBAAuB,QAAO,oBAAmB;AAE5F,MAAMC,QAAQ,IAAIC;AAElB;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC,aAAaC,QAAgB;IAC3C,MAAMC,SAASJ,MAAMK,GAAG,CAACF;IACzB,IAAIC,QAAQ;QACV,OAAOA;IACT;IAEA,MAAME,UAAUC,qBAAqBJ,UAAUK,KAAK,CAAC,CAACC;QACpDT,MAAMU,MAAM,CAACP;QACb,MAAMM;IACR;IAEAT,MAAMW,GAAG,CAACR,UAAUG;IACpB,OAAOA;AACT;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,eAAeC,qBAAqBJ,QAAgB;IACzD,MAAMS,QAAQ,MAAMjB,iBAAiBQ,UAAU;QAAC;QAAiB;KAAgB;IACjF,MAAMU,cAAcD,MAAME,MAAM,CAAC,CAACC,OAASA,KAAKC,MAAM;IAEtD,IAAIH,YAAYI,MAAM,KAAK,GAAG;QAC5B,MAAM,IAAIxB,cAAc,CAAC,uBAAuB,EAAEU,SAAS,mBAAmB,CAAC;IACjF;IAEA,IAAIU,YAAYI,MAAM,GAAG,GAAG;QAC1B,MAAM,IAAIC,MACR,CAAC,iCAAiC,EAAEL,YAAYM,GAAG,CAAC,CAACJ,OAASA,KAAKA,IAAI,EAAEK,IAAI,CAAC,MAAM,CAAC,CAAC;IAE1F;IAEA,MAAMC,aAAaR,WAAW,CAAC,EAAE,CAACE,IAAI;IAEtCvB,MAAM,CAAC,yBAAyB,EAAE6B,YAAY;IAE9C,wEAAwE;IACxE,+EAA+E;IAC/E,4EAA4E;IAC5E,iEAAiE;IACjE,MAAMC,aAAahC,cAAc,YAAYiC,GAAG;IAChD,OAAOD,WAAWtB,KAAK,CAACqB,WAAW;IAEnC,IAAIG;IACJ,IAAI;QACF,MAAMC,SAAS,MAAM/B,aAAwB2B;QAE7C7B,MAAM,yBAAyBiC;QAE/BD,YAAYC;IACd,EAAE,OAAOhB,KAAK;QACZjB,MAAM,kDAAkDiB;QAExD,MAAM,IAAIS,MAAM,+BAA+B;YAACQ,OAAOjB;QAAG;IAC5D;IAEA,2EAA2E;IAC3E,wEAAwE;IACxE,iEAAiE;IACjE,IAAIZ,eAAe2B,WAAWG,QAAQ7B,kBAAkB0B,WAAWG,MAAM;QACvE,OAAO5B,wBAAwByB,WAAWjC,QAAQ8B;IACpD;IAEA,MAAM,EAACO,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGlC,gBAAgBmC,SAAS,CAACP;IACzD,IAAI,CAACM,SAAS;QACZtC,MAAM,CAAC,oBAAoB,EAAEqC,MAAMG,OAAO,EAAE;QAC5C,MAAM,IAAId,MAAM,CAAC,oBAAoB,EAAEW,MAAMG,OAAO,EAAE,EAAE;YAACN,OAAOG;QAAK;IACvE;IAEA,OAAOD;AACT"}
|
|
@@ -5,7 +5,7 @@ import { register } from 'tsx/esm/api';
|
|
|
5
5
|
import { NotFoundError } from '../../errors/NotFoundError.js';
|
|
6
6
|
import { tryGetDefaultExport } from '../../util/tryGetDefaultExport.js';
|
|
7
7
|
import { cliConfigSchema } from './schemas.js';
|
|
8
|
-
import { isWorkbenchApp, parseWorkbenchCliConfig } from './workbenchApp.js';
|
|
8
|
+
import { isWorkbenchApp, isWorkbenchConfig, parseWorkbenchCliConfig } from './workbenchApp.js';
|
|
9
9
|
/**
|
|
10
10
|
* Get the CLI config for a project synchronously, given the root path.
|
|
11
11
|
*
|
|
@@ -40,9 +40,10 @@ import { isWorkbenchApp, parseWorkbenchCliConfig } from './workbenchApp.js';
|
|
|
40
40
|
} finally{
|
|
41
41
|
unregister();
|
|
42
42
|
}
|
|
43
|
-
// Branch as early as possible: a branded `
|
|
44
|
-
//
|
|
45
|
-
|
|
43
|
+
// Branch as early as possible: a branded `defineApplication(...)` app or a
|
|
44
|
+
// branded `unstable_defineMediaLibrary(...)` config opts into workbench
|
|
45
|
+
// behavior, so its `app` skips the legacy `app` schema entirely.
|
|
46
|
+
if (isWorkbenchApp(cliConfig?.app) || isWorkbenchConfig(cliConfig?.app)) {
|
|
46
47
|
return parseWorkbenchCliConfig(cliConfig, rootPath);
|
|
47
48
|
}
|
|
48
49
|
const { data, error, success } = cliConfigSchema.safeParse(cliConfig);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/cli/getCliConfigSync.ts"],"sourcesContent":["import {existsSync} from 'node:fs'\nimport {createRequire} from 'node:module'\nimport {join} from 'node:path'\n\nimport {register} from 'tsx/esm/api'\n\nimport {NotFoundError} from '../../errors/NotFoundError.js'\nimport {tryGetDefaultExport} from '../../util/tryGetDefaultExport.js'\nimport {cliConfigSchema} from './schemas.js'\nimport {type CliConfig} from './types/cliConfig.js'\nimport {isWorkbenchApp, parseWorkbenchCliConfig} from './workbenchApp.js'\n\n/**\n * Get the CLI config for a project synchronously, given the root path.\n *\n * This loads the CLI config in the main thread using tsx/register for TypeScript support.\n * Note: This is a synchronous operation and does not use worker threads like the async version.\n *\n * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.\n * @returns The CLI config\n * @internal\n */\nexport function getCliConfigSync(rootPath: string): CliConfig {\n const possiblePaths = ['sanity.cli.ts', 'sanity.cli.js'].map((file) => join(rootPath, file))\n const configPaths = possiblePaths.filter((path) => existsSync(path))\n\n if (configPaths.length === 0) {\n throw new NotFoundError(`No CLI config found at ${rootPath}/sanity.cli.(ts|js)`)\n }\n\n if (configPaths.length > 1) {\n throw new Error(`Multiple CLI config files found (${configPaths.join(', ')})`)\n }\n\n const configPath = configPaths[0]\n\n // Register tsx for TypeScript support\n const unregister = register()\n\n let cliConfig: CliConfig | undefined\n try {\n // Use createRequire for synchronous loading in ESM contexts\n // This works when tsx loader is active\n const require = createRequire(import.meta.url)\n const loaded = require(configPath)\n cliConfig = tryGetDefaultExport(loaded) as CliConfig | undefined\n } finally {\n unregister()\n }\n\n // Branch as early as possible: a branded `
|
|
1
|
+
{"version":3,"sources":["../../../src/config/cli/getCliConfigSync.ts"],"sourcesContent":["import {existsSync} from 'node:fs'\nimport {createRequire} from 'node:module'\nimport {join} from 'node:path'\n\nimport {register} from 'tsx/esm/api'\n\nimport {NotFoundError} from '../../errors/NotFoundError.js'\nimport {tryGetDefaultExport} from '../../util/tryGetDefaultExport.js'\nimport {cliConfigSchema} from './schemas.js'\nimport {type CliConfig} from './types/cliConfig.js'\nimport {isWorkbenchApp, isWorkbenchConfig, parseWorkbenchCliConfig} from './workbenchApp.js'\n\n/**\n * Get the CLI config for a project synchronously, given the root path.\n *\n * This loads the CLI config in the main thread using tsx/register for TypeScript support.\n * Note: This is a synchronous operation and does not use worker threads like the async version.\n *\n * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.\n * @returns The CLI config\n * @internal\n */\nexport function getCliConfigSync(rootPath: string): CliConfig {\n const possiblePaths = ['sanity.cli.ts', 'sanity.cli.js'].map((file) => join(rootPath, file))\n const configPaths = possiblePaths.filter((path) => existsSync(path))\n\n if (configPaths.length === 0) {\n throw new NotFoundError(`No CLI config found at ${rootPath}/sanity.cli.(ts|js)`)\n }\n\n if (configPaths.length > 1) {\n throw new Error(`Multiple CLI config files found (${configPaths.join(', ')})`)\n }\n\n const configPath = configPaths[0]\n\n // Register tsx for TypeScript support\n const unregister = register()\n\n let cliConfig: CliConfig | undefined\n try {\n // Use createRequire for synchronous loading in ESM contexts\n // This works when tsx loader is active\n const require = createRequire(import.meta.url)\n const loaded = require(configPath)\n cliConfig = tryGetDefaultExport(loaded) as CliConfig | undefined\n } finally {\n unregister()\n }\n\n // Branch as early as possible: a branded `defineApplication(...)` app or a\n // branded `unstable_defineMediaLibrary(...)` config opts into workbench\n // behavior, so its `app` skips the legacy `app` schema entirely.\n if (isWorkbenchApp(cliConfig?.app) || isWorkbenchConfig(cliConfig?.app)) {\n return parseWorkbenchCliConfig(cliConfig, rootPath)\n }\n\n const {data, error, success} = cliConfigSchema.safeParse(cliConfig)\n if (!success) {\n throw new Error(`Invalid CLI config: ${error.message}`)\n }\n\n // There is a minor difference here because of the `vite` property and how the types\n // aren't as specific as our manually typed `CliConfig` type, thus the cast.\n return data as CliConfig\n}\n"],"names":["existsSync","createRequire","join","register","NotFoundError","tryGetDefaultExport","cliConfigSchema","isWorkbenchApp","isWorkbenchConfig","parseWorkbenchCliConfig","getCliConfigSync","rootPath","possiblePaths","map","file","configPaths","filter","path","length","Error","configPath","unregister","cliConfig","require","url","loaded","app","data","error","success","safeParse","message"],"mappings":"AAAA,SAAQA,UAAU,QAAO,UAAS;AAClC,SAAQC,aAAa,QAAO,cAAa;AACzC,SAAQC,IAAI,QAAO,YAAW;AAE9B,SAAQC,QAAQ,QAAO,cAAa;AAEpC,SAAQC,aAAa,QAAO,gCAA+B;AAC3D,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,eAAe,QAAO,eAAc;AAE5C,SAAQC,cAAc,EAAEC,iBAAiB,EAAEC,uBAAuB,QAAO,oBAAmB;AAE5F;;;;;;;;;CASC,GACD,OAAO,SAASC,iBAAiBC,QAAgB;IAC/C,MAAMC,gBAAgB;QAAC;QAAiB;KAAgB,CAACC,GAAG,CAAC,CAACC,OAASZ,KAAKS,UAAUG;IACtF,MAAMC,cAAcH,cAAcI,MAAM,CAAC,CAACC,OAASjB,WAAWiB;IAE9D,IAAIF,YAAYG,MAAM,KAAK,GAAG;QAC5B,MAAM,IAAId,cAAc,CAAC,uBAAuB,EAAEO,SAAS,mBAAmB,CAAC;IACjF;IAEA,IAAII,YAAYG,MAAM,GAAG,GAAG;QAC1B,MAAM,IAAIC,MAAM,CAAC,iCAAiC,EAAEJ,YAAYb,IAAI,CAAC,MAAM,CAAC,CAAC;IAC/E;IAEA,MAAMkB,aAAaL,WAAW,CAAC,EAAE;IAEjC,sCAAsC;IACtC,MAAMM,aAAalB;IAEnB,IAAImB;IACJ,IAAI;QACF,4DAA4D;QAC5D,uCAAuC;QACvC,MAAMC,UAAUtB,cAAc,YAAYuB,GAAG;QAC7C,MAAMC,SAASF,QAAQH;QACvBE,YAAYjB,oBAAoBoB;IAClC,SAAU;QACRJ;IACF;IAEA,2EAA2E;IAC3E,wEAAwE;IACxE,iEAAiE;IACjE,IAAId,eAAee,WAAWI,QAAQlB,kBAAkBc,WAAWI,MAAM;QACvE,OAAOjB,wBAAwBa,WAAWX;IAC5C;IAEA,MAAM,EAACgB,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGvB,gBAAgBwB,SAAS,CAACR;IACzD,IAAI,CAACO,SAAS;QACZ,MAAM,IAAIV,MAAM,CAAC,oBAAoB,EAAES,MAAMG,OAAO,EAAE;IACxD;IAEA,oFAAoF;IACpF,4EAA4E;IAC5E,OAAOJ;AACT"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { existsSync } from 'node:fs';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
|
+
import { z } from 'zod/mini';
|
|
3
4
|
import { cliConfigSchema } from './schemas.js';
|
|
4
5
|
// Re-derived via `Symbol.for`, not imported from `@sanity/workbench-cli`: that
|
|
5
6
|
// import would cycle (it depends on cli-core) and pull workbench code into the
|
|
6
7
|
// hot config-load path.
|
|
7
8
|
const WORKBENCH_APP_BRAND = Symbol.for('sanity.workbench.defineApp');
|
|
9
|
+
const WORKBENCH_CONFIG_BRAND = Symbol.for('sanity.workbench.defineConfig');
|
|
8
10
|
/**
|
|
9
11
|
* Boolean brand check — used for config-load routing, kept exported for
|
|
10
12
|
* backward compatibility. For the typed narrowing (the app's declared fields),
|
|
@@ -12,6 +14,13 @@ const WORKBENCH_APP_BRAND = Symbol.for('sanity.workbench.defineApp');
|
|
|
12
14
|
*/ export function isWorkbenchApp(app) {
|
|
13
15
|
return typeof app === 'object' && app !== null && WORKBENCH_APP_BRAND in app;
|
|
14
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* Boolean brand check for a branded `unstable_defineMediaLibrary(...)` config.
|
|
19
|
+
* A config is not an app — it lives in `cliConfig.app` but skips the legacy `app`
|
|
20
|
+
* schema and `applicationType` stamping, and resolves via `resolveWorkbenchConfig`.
|
|
21
|
+
*/ export function isWorkbenchConfig(app) {
|
|
22
|
+
return typeof app === 'object' && app !== null && WORKBENCH_CONFIG_BRAND in app;
|
|
23
|
+
}
|
|
15
24
|
const STUDIO_CONFIG_FILES = [
|
|
16
25
|
'sanity.config.ts',
|
|
17
26
|
'sanity.config.tsx',
|
|
@@ -21,23 +30,20 @@ const STUDIO_CONFIG_FILES = [
|
|
|
21
30
|
'sanity.config.cjs'
|
|
22
31
|
];
|
|
23
32
|
// Mirrors the `ApplicationType` enum in `@sanity/workbench-cli`'s `defineApp`
|
|
24
|
-
// schema — `
|
|
33
|
+
// schema — `defineApplication` doesn't validate, so the loader is the first
|
|
25
34
|
// place `applicationType` can be checked. Kept in sync by a test there.
|
|
26
35
|
const APPLICATION_TYPES = [
|
|
27
36
|
'coreApp',
|
|
28
37
|
'studio',
|
|
29
38
|
'canvas',
|
|
30
|
-
'dashboard'
|
|
31
|
-
'media-library'
|
|
39
|
+
'dashboard'
|
|
32
40
|
];
|
|
33
|
-
|
|
34
|
-
return typeof value === 'string' && APPLICATION_TYPES.includes(value);
|
|
35
|
-
}
|
|
41
|
+
const applicationTypeSchema = z.enum(APPLICATION_TYPES);
|
|
36
42
|
/** Infer the type when unset: `sanity.config.*` present → studio, else core (SDK) app. */ function detectApplicationType(projectDir) {
|
|
37
43
|
return STUDIO_CONFIG_FILES.some((file)=>existsSync(join(projectDir, file))) ? 'studio' : 'coreApp';
|
|
38
44
|
}
|
|
39
45
|
/**
|
|
40
|
-
* Parse a config whose `app` is a branded `
|
|
46
|
+
* Parse a config whose `app` is a branded `defineApplication(...)` result. The
|
|
41
47
|
* branded `app` bypasses the legacy `app` schema (which would strip its identity
|
|
42
48
|
* fields and the brand); every other field is still validated.
|
|
43
49
|
*
|
|
@@ -52,15 +58,22 @@ function isApplicationType(value) {
|
|
|
52
58
|
cause: error
|
|
53
59
|
});
|
|
54
60
|
}
|
|
55
|
-
const explicit = app.applicationType;
|
|
56
|
-
if (explicit !== undefined && !isApplicationType(explicit)) {
|
|
57
|
-
throw new Error(`Invalid \`applicationType\` "${explicit}" in \`unstable_defineApp\` — expected one of: ${APPLICATION_TYPES.join(', ')}`);
|
|
58
|
-
}
|
|
59
|
-
const applicationType = explicit ?? detectApplicationType(projectDir);
|
|
60
61
|
// Clone via property descriptors, not spread — carries over the non-enumerable
|
|
61
62
|
// brand and avoids mutating the caller's object.
|
|
62
63
|
const resolvedApp = Object.defineProperties({}, Object.getOwnPropertyDescriptors(app));
|
|
63
|
-
|
|
64
|
+
// A config is not an app: it carries no `applicationType` (it targets one by
|
|
65
|
+
// `appType`), so skip detection/stamping and pass its branded shape through.
|
|
66
|
+
if (isWorkbenchConfig(app)) {
|
|
67
|
+
return {
|
|
68
|
+
...data,
|
|
69
|
+
app: resolvedApp
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const explicit = app.applicationType;
|
|
73
|
+
if (explicit !== undefined && !applicationTypeSchema.safeParse(explicit).success) {
|
|
74
|
+
throw new Error(`Invalid \`applicationType\` "${explicit}" in \`defineApplication\` — expected one of: ${APPLICATION_TYPES.join(', ')}`);
|
|
75
|
+
}
|
|
76
|
+
resolvedApp.applicationType = explicit ?? detectApplicationType(projectDir);
|
|
64
77
|
return {
|
|
65
78
|
...data,
|
|
66
79
|
app: resolvedApp
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/cli/workbenchApp.ts"],"sourcesContent":["import {existsSync} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {cliConfigSchema} from './schemas.js'\nimport {type CliConfig} from './types/cliConfig.js'\n\n// Re-derived via `Symbol.for`, not imported from `@sanity/workbench-cli`: that\n// import would cycle (it depends on cli-core) and pull workbench code into the\n// hot config-load path.\nconst WORKBENCH_APP_BRAND = Symbol.for('sanity.workbench.defineApp')\n\n/**\n * Boolean brand check — used for config-load routing, kept exported for\n * backward compatibility. For the typed narrowing (the app's declared fields),\n * use `isWorkbenchApp` from `@sanity/workbench-cli`, derived from the schema.\n */\nexport function isWorkbenchApp(app:
|
|
1
|
+
{"version":3,"sources":["../../../src/config/cli/workbenchApp.ts"],"sourcesContent":["import {existsSync} from 'node:fs'\nimport {join} from 'node:path'\n\nimport {z} from 'zod/mini'\n\nimport {cliConfigSchema} from './schemas.js'\nimport {type CliConfig} from './types/cliConfig.js'\n\n// Re-derived via `Symbol.for`, not imported from `@sanity/workbench-cli`: that\n// import would cycle (it depends on cli-core) and pull workbench code into the\n// hot config-load path.\nconst WORKBENCH_APP_BRAND = Symbol.for('sanity.workbench.defineApp')\nconst WORKBENCH_CONFIG_BRAND = Symbol.for('sanity.workbench.defineConfig')\n\n/**\n * Boolean brand check — used for config-load routing, kept exported for\n * backward compatibility. For the typed narrowing (the app's declared fields),\n * use `isWorkbenchApp` from `@sanity/workbench-cli`, derived from the schema.\n */\nexport function isWorkbenchApp(app: unknown): boolean {\n return typeof app === 'object' && app !== null && WORKBENCH_APP_BRAND in app\n}\n\n/**\n * Boolean brand check for a branded `unstable_defineMediaLibrary(...)` config.\n * A config is not an app — it lives in `cliConfig.app` but skips the legacy `app`\n * schema and `applicationType` stamping, and resolves via `resolveWorkbenchConfig`.\n */\nexport function isWorkbenchConfig(app: unknown): boolean {\n return typeof app === 'object' && app !== null && WORKBENCH_CONFIG_BRAND in app\n}\n\nconst STUDIO_CONFIG_FILES = [\n 'sanity.config.ts',\n 'sanity.config.tsx',\n 'sanity.config.js',\n 'sanity.config.jsx',\n 'sanity.config.mjs',\n 'sanity.config.cjs',\n]\n\n// Mirrors the `ApplicationType` enum in `@sanity/workbench-cli`'s `defineApp`\n// schema — `defineApplication` doesn't validate, so the loader is the first\n// place `applicationType` can be checked. Kept in sync by a test there.\nconst APPLICATION_TYPES = ['coreApp', 'studio', 'canvas', 'dashboard'] as const\nconst applicationTypeSchema = z.enum(APPLICATION_TYPES)\n\n/** The resolved kind of a workbench app — `studio` or one of the SDK app types. */\nexport type ApplicationType = z.infer<typeof applicationTypeSchema>\n\n/** Infer the type when unset: `sanity.config.*` present → studio, else core (SDK) app. */\nfunction detectApplicationType(projectDir: string): ApplicationType {\n return STUDIO_CONFIG_FILES.some((file) => existsSync(join(projectDir, file)))\n ? 'studio'\n : 'coreApp'\n}\n\n/**\n * Parse a config whose `app` is a branded `defineApplication(...)` result. The\n * branded `app` bypasses the legacy `app` schema (which would strip its identity\n * fields and the brand); every other field is still validated.\n *\n * Resolves `applicationType` once, here, so studio-vs-app is settled everywhere\n * downstream. The value lands on a clone, never the caller's object, so\n * re-parsing the same `app` for another directory can't inherit a stale guess.\n */\nexport function parseWorkbenchCliConfig(cliConfig: unknown, projectDir: string): CliConfig {\n const {app, ...rest} = cliConfig as Record<string, unknown> & {\n app: Record<string, unknown> & {applicationType?: string}\n }\n const {data, error, success} = cliConfigSchema.safeParse(rest)\n if (!success) {\n throw new Error(`Invalid CLI config: ${error.message}`, {cause: error})\n }\n\n // Clone via property descriptors, not spread — carries over the non-enumerable\n // brand and avoids mutating the caller's object.\n const resolvedApp = Object.defineProperties({}, Object.getOwnPropertyDescriptors(app)) as Record<\n string,\n unknown\n >\n\n // A config is not an app: it carries no `applicationType` (it targets one by\n // `appType`), so skip detection/stamping and pass its branded shape through.\n if (isWorkbenchConfig(app)) {\n return {...data, app: resolvedApp} as CliConfig\n }\n\n const explicit = app.applicationType\n if (explicit !== undefined && !applicationTypeSchema.safeParse(explicit).success) {\n throw new Error(\n `Invalid \\`applicationType\\` \"${explicit}\" in \\`defineApplication\\` — expected one of: ${APPLICATION_TYPES.join(', ')}`,\n )\n }\n resolvedApp.applicationType = explicit ?? detectApplicationType(projectDir)\n\n return {...data, app: resolvedApp} as CliConfig\n}\n"],"names":["existsSync","join","z","cliConfigSchema","WORKBENCH_APP_BRAND","Symbol","for","WORKBENCH_CONFIG_BRAND","isWorkbenchApp","app","isWorkbenchConfig","STUDIO_CONFIG_FILES","APPLICATION_TYPES","applicationTypeSchema","enum","detectApplicationType","projectDir","some","file","parseWorkbenchCliConfig","cliConfig","rest","data","error","success","safeParse","Error","message","cause","resolvedApp","Object","defineProperties","getOwnPropertyDescriptors","explicit","applicationType","undefined"],"mappings":"AAAA,SAAQA,UAAU,QAAO,UAAS;AAClC,SAAQC,IAAI,QAAO,YAAW;AAE9B,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,eAAe,QAAO,eAAc;AAG5C,+EAA+E;AAC/E,+EAA+E;AAC/E,wBAAwB;AACxB,MAAMC,sBAAsBC,OAAOC,GAAG,CAAC;AACvC,MAAMC,yBAAyBF,OAAOC,GAAG,CAAC;AAE1C;;;;CAIC,GACD,OAAO,SAASE,eAAeC,GAAY;IACzC,OAAO,OAAOA,QAAQ,YAAYA,QAAQ,QAAQL,uBAAuBK;AAC3E;AAEA;;;;CAIC,GACD,OAAO,SAASC,kBAAkBD,GAAY;IAC5C,OAAO,OAAOA,QAAQ,YAAYA,QAAQ,QAAQF,0BAA0BE;AAC9E;AAEA,MAAME,sBAAsB;IAC1B;IACA;IACA;IACA;IACA;IACA;CACD;AAED,8EAA8E;AAC9E,4EAA4E;AAC5E,wEAAwE;AACxE,MAAMC,oBAAoB;IAAC;IAAW;IAAU;IAAU;CAAY;AACtE,MAAMC,wBAAwBX,EAAEY,IAAI,CAACF;AAKrC,wFAAwF,GACxF,SAASG,sBAAsBC,UAAkB;IAC/C,OAAOL,oBAAoBM,IAAI,CAAC,CAACC,OAASlB,WAAWC,KAAKe,YAAYE,UAClE,WACA;AACN;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,wBAAwBC,SAAkB,EAAEJ,UAAkB;IAC5E,MAAM,EAACP,GAAG,EAAE,GAAGY,MAAK,GAAGD;IAGvB,MAAM,EAACE,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGrB,gBAAgBsB,SAAS,CAACJ;IACzD,IAAI,CAACG,SAAS;QACZ,MAAM,IAAIE,MAAM,CAAC,oBAAoB,EAAEH,MAAMI,OAAO,EAAE,EAAE;YAACC,OAAOL;QAAK;IACvE;IAEA,+EAA+E;IAC/E,iDAAiD;IACjD,MAAMM,cAAcC,OAAOC,gBAAgB,CAAC,CAAC,GAAGD,OAAOE,yBAAyB,CAACvB;IAKjF,6EAA6E;IAC7E,6EAA6E;IAC7E,IAAIC,kBAAkBD,MAAM;QAC1B,OAAO;YAAC,GAAGa,IAAI;YAAEb,KAAKoB;QAAW;IACnC;IAEA,MAAMI,WAAWxB,IAAIyB,eAAe;IACpC,IAAID,aAAaE,aAAa,CAACtB,sBAAsBY,SAAS,CAACQ,UAAUT,OAAO,EAAE;QAChF,MAAM,IAAIE,MACR,CAAC,6BAA6B,EAAEO,SAAS,8CAA8C,EAAErB,kBAAkBX,IAAI,CAAC,OAAO;IAE3H;IACA4B,YAAYK,eAAe,GAAGD,YAAYlB,sBAAsBC;IAEhE,OAAO;QAAC,GAAGM,IAAI;QAAEb,KAAKoB;IAAW;AACnC"}
|
|
@@ -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,8CAA6C,CAAC,2EAA2E;AACzJ,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,4BAA4B,QAAO,6BAA4B;AAEvE,IAAId,cAAc;IAChB,MA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AC7E,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;AAEA,MAAMC,WAAWC,QAAQC,GAAG,CAACC,8BAA8B;AAC3D,IAAI,CAACH,UAAU;IACb,MAAM,IAAID,MAAM;AAClB;AAEA,MAAMK,QAAQZ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,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"}
|
package/dist/manifest.js
CHANGED
|
@@ -10,9 +10,15 @@ import { z } from 'zod/mini';
|
|
|
10
10
|
* `CoreAppUserApplicationManifest` schema. Strictly validated via zod since the
|
|
11
11
|
* CLI produces the payload in full.
|
|
12
12
|
*/ export const coreAppManifestSchema = z.object({
|
|
13
|
-
|
|
13
|
+
dock: z.optional(z.object({
|
|
14
|
+
group: z.optional(z.enum([
|
|
15
|
+
'dock.system',
|
|
16
|
+
'dock.applications',
|
|
17
|
+
'dock.user'
|
|
18
|
+
])),
|
|
19
|
+
order: z.optional(z.number())
|
|
20
|
+
})),
|
|
14
21
|
icon: z.optional(z.string()),
|
|
15
|
-
priority: z.optional(z.number()),
|
|
16
22
|
slug: z.optional(z.string()),
|
|
17
23
|
title: z.optional(z.string()),
|
|
18
24
|
version: z.string()
|
package/dist/manifest.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/manifest.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\n/**\n * Studio/app manifest schemas. They live in cli-core because more than one\n * package validates manifests: the CLI extracts and writes them, and the\n * workbench dev-server registry stores and rebroadcasts them. Keeping the\n * contract here lets both validate against the same schema without depending on\n * each other.\n */\n\n/**\n * Core-app application manifest. Mirrors the workbench's\n * `CoreAppUserApplicationManifest` schema. Strictly validated via zod since the\n * CLI produces the payload in full.\n */\nexport const coreAppManifestSchema = z.object({\n group: z.optional(z.
|
|
1
|
+
{"version":3,"sources":["../src/manifest.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\n/**\n * Studio/app manifest schemas. They live in cli-core because more than one\n * package validates manifests: the CLI extracts and writes them, and the\n * workbench dev-server registry stores and rebroadcasts them. Keeping the\n * contract here lets both validate against the same schema without depending on\n * each other.\n */\n\n/**\n * Core-app application manifest. Mirrors the workbench's\n * `CoreAppUserApplicationManifest` schema. Strictly validated via zod since the\n * CLI produces the payload in full.\n */\nexport const coreAppManifestSchema = z.object({\n dock: z.optional(\n z.object({\n group: z.optional(z.enum(['dock.system', 'dock.applications', 'dock.user'])),\n order: z.optional(z.number()),\n }),\n ),\n icon: z.optional(z.string()),\n slug: z.optional(z.string()),\n title: z.optional(z.string()),\n version: z.string(),\n})\n\nexport type CoreAppManifest = z.infer<typeof coreAppManifestSchema>\n\n/**\n * Studio application manifest (serialized `create-manifest.json`). Kept loose so\n * the CLI isn't coupled to the workbench's evolving client-side schema — the\n * workbench consumer is authoritative on the inner shape. See its\n * `ClientManifest` for the fields clients expect.\n */\nexport const studioManifestSchema = z.record(z.string(), z.unknown())\n\nexport type StudioManifest = z.infer<typeof studioManifestSchema>\n"],"names":["z","coreAppManifestSchema","object","dock","optional","group","enum","order","number","icon","string","slug","title","version","studioManifestSchema","record","unknown"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B;;;;;;CAMC,GAED;;;;CAIC,GACD,OAAO,MAAMC,wBAAwBD,EAAEE,MAAM,CAAC;IAC5CC,MAAMH,EAAEI,QAAQ,CACdJ,EAAEE,MAAM,CAAC;QACPG,OAAOL,EAAEI,QAAQ,CAACJ,EAAEM,IAAI,CAAC;YAAC;YAAe;YAAqB;SAAY;QAC1EC,OAAOP,EAAEI,QAAQ,CAACJ,EAAEQ,MAAM;IAC5B;IAEFC,MAAMT,EAAEI,QAAQ,CAACJ,EAAEU,MAAM;IACzBC,MAAMX,EAAEI,QAAQ,CAACJ,EAAEU,MAAM;IACzBE,OAAOZ,EAAEI,QAAQ,CAACJ,EAAEU,MAAM;IAC1BG,SAASb,EAAEU,MAAM;AACnB,GAAE;AAIF;;;;;CAKC,GACD,OAAO,MAAMI,uBAAuBd,EAAEe,MAAM,CAACf,EAAEU,MAAM,IAAIV,EAAEgB,OAAO,IAAG"}
|
|
@@ -80,9 +80,15 @@ declare const cliConfigSchema: z.ZodMiniObject<{
|
|
|
80
80
|
* CLI produces the payload in full.
|
|
81
81
|
*/
|
|
82
82
|
declare const coreAppManifestSchema: z.ZodMiniObject<{
|
|
83
|
-
|
|
83
|
+
dock: z.ZodMiniOptional<z.ZodMiniObject<{
|
|
84
|
+
group: z.ZodMiniOptional<z.ZodMiniEnum<{
|
|
85
|
+
"dock.system": "dock.system";
|
|
86
|
+
"dock.applications": "dock.applications";
|
|
87
|
+
"dock.user": "dock.user";
|
|
88
|
+
}>>;
|
|
89
|
+
order: z.ZodMiniOptional<z.ZodMiniNumber<number>>;
|
|
90
|
+
}, z.core.$strip>>;
|
|
84
91
|
icon: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
85
|
-
priority: z.ZodMiniOptional<z.ZodMiniNumber<number>>;
|
|
86
92
|
slug: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
87
93
|
title: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
88
94
|
version: z.ZodMiniString<string>;
|
|
@@ -97,4 +103,4 @@ type CoreAppManifest = z.infer<typeof coreAppManifestSchema>;
|
|
|
97
103
|
declare const studioManifestSchema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
|
|
98
104
|
type StudioManifest = z.infer<typeof studioManifestSchema>;
|
|
99
105
|
export { cliConfigSchema as a, studioManifestSchema as i, StudioManifest as n, coreAppManifestSchema as r, CoreAppManifest as t };
|
|
100
|
-
//# sourceMappingURL=schemas-
|
|
106
|
+
//# sourceMappingURL=schemas-D1LxkXeZ.d.ts.map
|
|
@@ -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"}
|
|
@@ -1,15 +1,21 @@
|
|
|
1
1
|
import { r as CliConfig } from "./cliConfig-DUt8uaF6.js";
|
|
2
|
+
import { z } from "zod/mini";
|
|
2
3
|
/**
|
|
3
4
|
* Boolean brand check — used for config-load routing, kept exported for
|
|
4
5
|
* backward compatibility. For the typed narrowing (the app's declared fields),
|
|
5
6
|
* use `isWorkbenchApp` from `@sanity/workbench-cli`, derived from the schema.
|
|
6
7
|
*/
|
|
7
|
-
declare function isWorkbenchApp(app:
|
|
8
|
-
declare const
|
|
8
|
+
declare function isWorkbenchApp(app: unknown): boolean;
|
|
9
|
+
declare const applicationTypeSchema: z.ZodMiniEnum<{
|
|
10
|
+
coreApp: "coreApp";
|
|
11
|
+
studio: "studio";
|
|
12
|
+
canvas: "canvas";
|
|
13
|
+
dashboard: "dashboard";
|
|
14
|
+
}>;
|
|
9
15
|
/** The resolved kind of a workbench app — `studio` or one of the SDK app types. */
|
|
10
|
-
type ApplicationType =
|
|
16
|
+
type ApplicationType = z.infer<typeof applicationTypeSchema>;
|
|
11
17
|
/**
|
|
12
|
-
* Parse a config whose `app` is a branded `
|
|
18
|
+
* Parse a config whose `app` is a branded `defineApplication(...)` result. The
|
|
13
19
|
* branded `app` bypasses the legacy `app` schema (which would strip its identity
|
|
14
20
|
* fields and the brand); every other field is still validated.
|
|
15
21
|
*
|
|
@@ -19,4 +25,4 @@ type ApplicationType = (typeof APPLICATION_TYPES)[number];
|
|
|
19
25
|
*/
|
|
20
26
|
declare function parseWorkbenchCliConfig(cliConfig: unknown, projectDir: string): CliConfig;
|
|
21
27
|
export { isWorkbenchApp as n, parseWorkbenchCliConfig as r, ApplicationType as t };
|
|
22
|
-
//# sourceMappingURL=workbenchApp-
|
|
28
|
+
//# sourceMappingURL=workbenchApp-DVKwpTyU.d.ts.map
|
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"
|