@sanity/cli-core 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +7 -6
  2. package/dist/NonInteractiveError-CSLT5y93.d.ts +13 -0
  3. package/dist/ProjectRootNotFoundError-RgthN9uy.d.ts +47 -0
  4. package/dist/SanityCommand.d.ts +26 -355
  5. package/dist/SanityCommand.js +5 -0
  6. package/dist/SanityCommand.js.map +1 -1
  7. package/dist/_exports/browser.d.ts +2 -21
  8. package/dist/_exports/config.d.ts +5 -661
  9. package/dist/_exports/debug.d.ts +4 -8
  10. package/dist/_exports/debug.js +3 -3
  11. package/dist/_exports/debug.js.map +1 -1
  12. package/dist/_exports/errors.d.ts +12 -77
  13. package/dist/_exports/index.d.ts +34 -1674
  14. package/dist/_exports/package-manager.d.ts +14 -207
  15. package/dist/_exports/request.d.ts +52 -69
  16. package/dist/_exports/request.js +5 -4
  17. package/dist/_exports/request.js.map +1 -1
  18. package/dist/_exports/schemas.d.ts +2 -235
  19. package/dist/_exports/tasks.d.ts +2 -120
  20. package/dist/_exports/telemetry.d.ts +2 -156
  21. package/dist/_exports/types.d.ts +9 -475
  22. package/dist/_exports/types.js.map +1 -1
  23. package/dist/_exports/undeploy.d.ts +38 -51
  24. package/dist/_exports/util.d.ts +6 -137
  25. package/dist/_exports/ux.d.ts +31 -102
  26. package/dist/apiClient-DXlF5ZV3.d.ts +65 -0
  27. package/dist/apiClient.d.ts +2 -79
  28. package/dist/apiClient.js +69 -47
  29. package/dist/apiClient.js.map +1 -1
  30. package/dist/cliConfig-DrUV6Wp6.d.ts +197 -0
  31. package/dist/config/cli/schemas.js.map +1 -1
  32. package/dist/config/cli/types/cliConfig.js.map +1 -1
  33. package/dist/errors/NonInteractiveError.js +2 -1
  34. package/dist/errors/NonInteractiveError.js.map +1 -1
  35. package/dist/errors/ProjectRootNotFoundError.js +2 -1
  36. package/dist/errors/ProjectRootNotFoundError.js.map +1 -1
  37. package/dist/errors/enrichAuthError.js +48 -0
  38. package/dist/errors/enrichAuthError.js.map +1 -0
  39. package/dist/errors/getErrorMessage.js +3 -1
  40. package/dist/errors/getErrorMessage.js.map +1 -1
  41. package/dist/executionContext.d.ts +21 -20
  42. package/dist/executionContext.js.map +1 -1
  43. package/dist/exitCodes.d.ts +3 -3
  44. package/dist/findStudioConfigPath-DeBa0pMT.d.ts +265 -0
  45. package/dist/getWorkspace-CU32E6Uo.d.ts +54 -0
  46. package/dist/mockBrowserEnvironment-BjFQPb2W.d.ts +19 -0
  47. package/dist/noopTelemetry-BJRIvASI.d.ts +64 -0
  48. package/dist/readPackageJson-Cr_lbjVR.d.ts +67 -0
  49. package/dist/recursivelyResolveProjectRoot-BE54uEP6.d.ts +18 -0
  50. package/dist/request/createRequester.js +39 -50
  51. package/dist/request/createRequester.js.map +1 -1
  52. package/dist/request/nodeReadableFromWeb.js +64 -0
  53. package/dist/request/nodeReadableFromWeb.js.map +1 -0
  54. package/dist/resolveLocalPackage-Dr-TNTyk.d.ts +78 -0
  55. package/dist/safeStructuredClone-CWB0MXmH.d.ts +58 -0
  56. package/dist/schemas-Y-KwP413.d.ts +100 -0
  57. package/dist/timer-Dwu2TIgB.d.ts +14 -0
  58. package/dist/tsxWorkerTask-CxG3fWbU.d.ts +97 -0
  59. package/dist/types-CwJLTYDj.d.ts +23 -0
  60. package/dist/types-ZNH3prAd.d.ts +91 -0
  61. package/dist/workbenchApp-CSYpReA-.d.ts +22 -0
  62. package/package.json +16 -12
  63. package/dist/request/createIsolatedRequester.js +0 -75
  64. package/dist/request/createIsolatedRequester.js.map +0 -1
package/README.md CHANGED
@@ -101,12 +101,13 @@ Package manager detection and utilities.
101
101
 
102
102
  HTTP request utilities built on [`get-it`](https://github.com/sanity-io/get-it).
103
103
 
104
- | Export | Description |
105
- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
106
- | `createRequester(middleware?)` | Create a configured `get-it` requester instance. |
107
- | `Requester` | `get-it` `Requester` type. |
108
- | `MiddlewareOptions` | Options type for `createRequester`. |
109
- | `agent`, `base`, `injectResponse`, `jsonRequest`, `jsonResponse`, `keepAlive`, `observable`, `progress`, `proxy`, `retry`, `urlEncoded` | Optional `get-it` middleware for use alongside `createRequester`. |
104
+ | Export | Description |
105
+ | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
106
+ | `createRequester(options?)` | Create a configured get-it v9 requester with CLI defaults (User-Agent, debug). |
107
+ | `CreateRequesterOptions` | Options type for `createRequester`. |
108
+ | `nodeReadableFromWeb(stream)` | Convert a Web `ReadableStream` to a Node.js `Readable`. |
109
+ | `HttpError`, `RequestFunction`, `RequestOptions`, `BufferedResponse`, `JsonResponse`, `TextResponse`, `StreamResponse`, … | Re-exported get-it types/helpers. |
110
+ | `retry`, `debug` | get-it middleware for use alongside `createRequester`. |
110
111
 
111
112
  ## `@sanity/cli-core/schemas`
112
113
 
@@ -0,0 +1,13 @@
1
+ import { CLIError } from "@oclif/core/errors";
2
+ /**
3
+ * Error thrown when a prompt is attempted in a non-interactive environment
4
+ * (e.g., CI, non-TTY, piped stdin). Callers can catch this specific error
5
+ * to provide appropriate fallback behavior.
6
+ *
7
+ * Extends `CLIError` to suppress stack traces in user-facing output.
8
+ */
9
+ declare class NonInteractiveError extends CLIError {
10
+ constructor(promptName: string);
11
+ }
12
+ export { NonInteractiveError as t };
13
+ //# sourceMappingURL=NonInteractiveError-CSLT5y93.d.ts.map
@@ -0,0 +1,47 @@
1
+ import { CLIError } from "@oclif/core/errors";
2
+ /**
3
+ * Error thrown when a file or directory is not found
4
+ *
5
+ * `code` is always `ENOENT` to mirror Node.js behavior when a file is not found
6
+ *
7
+ * @internal
8
+ */
9
+ declare class NotFoundError extends Error {
10
+ code: string;
11
+ path?: string;
12
+ constructor(message: string, path?: string);
13
+ }
14
+ /**
15
+ * Returns whether or not the given error is a `NotFoundError`
16
+ *
17
+ * @param err - The error to check
18
+ * @returns `true` if the error is a `NotFoundError`, `false` otherwise
19
+ * @internal
20
+ */
21
+ declare function isNotFoundError(err: unknown): err is NotFoundError;
22
+ /**
23
+ * Error thrown when a project root directory cannot be found.
24
+ *
25
+ * This occurs when the CLI is run outside a Sanity project directory
26
+ * (one containing `sanity.config.(ts|js)` or `sanity.cli.(ts|js)`).
27
+ *
28
+ * Extends `CLIError` to suppress stack traces in user-facing output.
29
+ *
30
+ * @internal
31
+ */
32
+ declare class ProjectRootNotFoundError extends CLIError {
33
+ constructor(message: string, options?: {
34
+ cause?: Error;
35
+ suggestions?: string[];
36
+ });
37
+ }
38
+ /**
39
+ * Returns whether or not the given error is a `ProjectRootNotFoundError`
40
+ *
41
+ * @param err - The error to check
42
+ * @returns `true` if the error is a `ProjectRootNotFoundError`, `false` otherwise
43
+ * @internal
44
+ */
45
+ declare function isProjectRootNotFoundError(err: unknown): err is ProjectRootNotFoundError;
46
+ export { isNotFoundError as i, isProjectRootNotFoundError as n, NotFoundError as r, ProjectRootNotFoundError as t };
47
+ //# sourceMappingURL=ProjectRootNotFoundError-RgthN9uy.d.ts.map
@@ -1,282 +1,29 @@
1
- import { ClientConfig } from "@sanity/client";
2
- import { Command } from "@oclif/core";
1
+ import { n as ProjectCliClientOptions, t as GlobalCliClientOptions } from "./apiClient-DXlF5ZV3.js";
2
+ import { r as CliConfig } from "./cliConfig-DrUV6Wp6.js";
3
+ import { t as ProjectRootResult } from "./recursivelyResolveProjectRoot-BE54uEP6.js";
4
+ import { t as CLITelemetryStore } from "./types-ZNH3prAd.js";
5
+ import { t as Output } from "./types-CwJLTYDj.js";
6
+ import { Command, Interfaces } from "@oclif/core";
3
7
  import { CommandError } from "@oclif/core/interfaces";
4
- import { ConfigEnv } from "vite";
5
- import { InlineConfig } from "vite";
6
- import { Interfaces } from "@oclif/core";
7
- import { PluginOptions } from "babel-plugin-react-compiler";
8
- import { SanityClient } from "sanity";
9
-
8
+ type Flags<T extends typeof Command> = Interfaces.InferredFlags<(typeof SanityCommand)['baseFlags'] & T['flags']>;
9
+ type Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>;
10
10
  /**
11
- * Dashboard visibility an application can declare. Mirrors Brett's canonical
12
- * `VISIBILITIES` — the source of truth lives in the application service.
13
- * @public
14
- */
15
- declare const APP_VISIBILITIES: readonly ["default", "unlisted", "disabled"];
16
-
17
- /** @public */
18
- declare type AppVisibility = (typeof APP_VISIBILITIES)[number];
19
-
20
- declare type Args<T extends typeof Command> = Interfaces.InferredArgs<
21
- T["args"]
22
- >;
23
-
24
- /**
25
- * @public
26
- */
27
- declare interface CliConfig {
28
- /** The project ID and dataset the Sanity CLI should use to run its commands */
29
- api?: {
30
- dataset?: string;
31
- projectId?: string;
32
- };
33
- /** Configuration for custom Sanity apps built with the App SDK */
34
- app?: {
35
- /** The entrypoint for your custom app. By default, `src/App.tsx` */
36
- entry?: string;
37
- /**
38
- * Path to an icon file relative to project root.
39
- * The file must be an SVG.
40
- */
41
- icon?: string;
42
- /** @deprecated Use deployment.appId */
43
- id?: string;
44
- /** The ID for the Sanity organization that manages this application */
45
- organizationId?: string;
46
- /** The title of the custom app, as it is seen in Dashboard UI */
47
- title?: string;
48
- /** Dashboard visibility of the application. Defaults to `default`. */
49
- visibility?: AppVisibility;
50
- };
51
- /** @deprecated Use deployment.autoUpdates */
52
- autoUpdates?: boolean;
53
- /** Options for custom app and Studio deployments */
54
- deployment?: {
55
- /**
56
- * The ID for your custom app or Studio. Generated when deploying your app or Studio for the first time.
57
- * Get your app ID by either:
58
- * 1. Checking the output of `sanity deploy`, or
59
- * 2. Checking your project’s Studio tab at https://sanity.io/manage
60
- *
61
- * @remarks This is required for all custom app deployments, and for Studios opting in to fine grained version control.
62
- * {@link https://www.sanity.io/docs/studio/latest-version-of-sanity#k0896ed4574b7}
63
- */
64
- appId?: string;
65
- /**
66
- * Enable automatic updates for your Studio or custom app’s Sanity dependencies.
67
- * {@link https://www.sanity.io/docs/studio/latest-version-of-sanity}
68
- */
69
- autoUpdates?: boolean;
70
- };
71
- /** Define the GraphQL APIs that the CLI can deploy and interact with */
72
- graphql?: Array<{
73
- filterSuffix?: string;
74
- generation?: "gen1" | "gen2" | "gen3";
75
- id?: string;
76
- nonNullDocumentFields?: boolean;
77
- playground?: boolean;
78
- source?: string;
79
- tag?: string;
80
- workspace?: string;
81
- }>;
82
- /** Configuration for the Media Library */
83
- mediaLibrary?: {
84
- /** The path to the Media Library aspects directory. When using the CLI to manage aspects, this is the directory they will be read from and written to. */
85
- aspectsPath?: string;
86
- };
87
- /** Contains the property `basePath` which lets you change the top-level slug for the Studio. You typically need to set this if you embed the Studio in another application where it is one of many routes. Defaults to an empty string. */
88
- project?: {
89
- basePath?: string;
90
- };
91
- /** Configuration options for React Compiler */
92
- reactCompiler?: boolean | PluginOptions;
93
- /** Wraps the Studio in \<React.StrictMode\> root to aid in flagging potential problems related to concurrent features (startTransition, useTransition, useDeferredValue, Suspense). Can also be enabled by setting SANITY_STUDIO_REACT_STRICT_MODE="true"|"false". It only applies to sanity dev in development mode and is ignored in sanity build and in production. Defaults to true. */
94
- reactStrictMode?: boolean;
95
- /**
96
- * Configuration for schema extraction (`sanity schema extract`)
97
- */
98
- schemaExtraction?: {
99
- /**
100
- * Enable schema extraction as part of sanity dev and sanity build
101
- */
102
- enabled?: boolean;
103
- /**
104
- * When true, schema fields marked as required will be non-optional in the output.
105
- * Defaults to `false`
106
- */
107
- enforceRequiredFields?: boolean;
108
- /**
109
- * Output path for the extracted schema file.
110
- * Defaults to `schema.json` in the working directory.
111
- */
112
- path?: string;
113
- /**
114
- * Additional glob patterns to watch for schema changes in watch mode.
115
- * These extend the default patterns:
116
- * - `sanity.config.{js,jsx,ts,tsx,mjs}`
117
- * - `schema*\/**\/*.{js,jsx,ts,tsx,mjs}`
118
- */
119
- watchPatterns?: string[];
120
- /**
121
- * The name of the workspace to generate a schema for. Required if your Sanity project has more than one
122
- * workspace.
123
- */
124
- workspace?: string;
125
- };
126
- /** Defines the hostname and port that the development server should run on. hostname defaults to localhost, and port to 3333. */
127
- server?: {
128
- hostname?: string;
129
- port?: number;
130
- };
131
- /** @deprecated Use deployment.appId */
132
- studioHost?: string;
133
- /**
134
- * Configuration for Sanity typegen
135
- */
136
- typegen?: Partial<TypeGenConfig> & {
137
- /**
138
- * Enable typegen as part of sanity dev and sanity build.
139
- * When enabled, types are generated on startup and when files change.
140
- * Defaults to `false`
141
- */
142
- enabled?: boolean;
143
- };
144
- /**
145
- * Enable Vite's experimental bundled dev mode for `sanity dev`. This serves bundled
146
- * files during development, which can speed up startup and reloads for large projects.
147
- * Defaults to `false`.
148
- *
149
- * Unstable: may change or be removed without notice while the underlying Vite
150
- * feature (`experimental.bundledDev`) is experimental.
151
- * {@link https://vite.dev/guide/rolldown#full-bundle-mode}
152
- */
153
- unstable_bundledDev?: boolean;
154
- /** Exposes the default Vite configuration for custom apps and the Studio so it can be changed and extended. */
155
- vite?: UserViteConfig;
156
- }
157
-
158
- /**
159
- * @public
160
- */
161
- declare type CLITelemetryStore = TelemetryLogger<TelemetryUserProperties>;
162
-
163
- declare interface DeferredEvent<
164
- Data = unknown,
165
- Event extends DefinedTelemetryLog<Data> = DefinedTelemetryLog<Data>,
166
- > {
167
- createdAt: string;
168
- event: Event;
169
- data: Data;
170
- }
171
-
172
- declare interface DefinedTelemetryLog<Schema> {
173
- type: "log";
174
- /** Unique name of the event */
175
- name: string;
176
- /** Event version. Increment this by 1 whenever the shape of the data changes in a non-backwards compatible way */
177
- version: number;
178
- /** Description of log event */
179
- description?: string;
180
- /**
181
- * Max sample rate of this event.
182
- * Calling telemetry.log(EventDefinition, data) repeatedly will submit at most one event every specified time interval (in milliseconds)
183
- * */
184
- maxSampleRate?: number;
185
- /** Data schema. Will not be accessible at runtime */
186
- schema: Schema;
187
- }
188
-
189
- declare interface DefinedTelemetryTrace<Data = void, Context = void> {
190
- type: "trace";
191
- /** Unique name of the trace */
192
- name: string;
193
- /** Trace version. Increment this by 1 whenever the shape of the data changes in a non-backwards compatible way */
194
- version: number;
195
- /** Description of trace */
196
- description?: string;
197
- /** Data schema. Will not be accessible at runtime */
198
- schema: Data;
199
- /** Contextual data schema. Will not be accessible at runtime */
200
- context: Context;
201
- }
202
-
203
- declare type Flags<T extends typeof Command> = Interfaces.InferredFlags<
204
- (typeof SanityCommand)["baseFlags"] & T["flags"]
205
- >;
206
-
207
- /**
208
- * @public
209
- */
210
- declare interface GlobalCliClientOptions extends ClientConfig {
211
- /**
212
- * The API version to use for this client.
213
- */
214
- apiVersion: string;
215
- /**
216
- * Whether to require a user to be authenticated to use this client.
217
- * Default: `false`.
218
- * Throws an error if `true` and user is not authenticated.
219
- */
220
- requireUser?: boolean;
221
- /**
222
- * Whether to skip reading the stored CLI token. When `true`, the client will
223
- * have no token unless one is explicitly provided.
224
- * Default: `false`.
225
- */
226
- unauthenticated?: boolean;
227
- }
228
-
229
- declare interface Output {
230
- error: Command["error"];
231
- log: Command["log"];
232
- warn: Command["warn"];
233
- }
234
-
235
- /**
236
- * @public
237
- */
238
- declare interface ProjectCliClientOptions extends ClientConfig {
239
- /**
240
- * The API version to use for this client.
241
- */
242
- apiVersion: string;
243
- /**
244
- * The project ID to use for this client.
245
- */
246
- projectId: string;
247
- /**
248
- * The dataset to use for this client.
249
- */
250
- dataset?: string;
251
- /**
252
- * Whether to require a user to be authenticated to use this client.
253
- * Default: `false`.
254
- * Throws an error if `true` and user is not authenticated.
255
- */
256
- requireUser?: boolean;
257
- }
258
-
259
- /**
260
- * Result of finding a project configuration
261
- *
262
- * @public
11
+ * Interface for `SanityCommand`, a wrapper around OCLIF's Command class.
12
+ * Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.
13
+ * @see https://oclif.io/docs/base_class/
263
14
  */
264
- declare interface ProjectRootResult {
265
- directory: string;
266
- /**
267
- * Path to the project configuration file, if found.
268
- */
269
- path: string;
270
- /**
271
- * Type of project root.
272
- */
273
- type: "app" | "studio";
15
+ interface SanityCommandInterface {
16
+ getCliConfig: () => Promise<CliConfig>;
17
+ getProjectId: (options?: {
18
+ deprecatedFlagName?: string;
19
+ fallback?: () => Promise<string>;
20
+ }) => Promise<string>;
21
+ getProjectRoot: () => Promise<ProjectRootResult>;
22
+ isUnattended: () => boolean;
23
+ output: Output;
24
+ resolveIsInteractive: () => boolean;
274
25
  }
275
-
276
- export declare abstract class SanityCommand<T extends typeof Command>
277
- extends Command
278
- implements SanityCommandInterface
279
- {
26
+ declare abstract class SanityCommand<T extends typeof Command> extends Command implements SanityCommandInterface {
280
27
  protected args: Args<T>;
281
28
  protected flags: Flags<T>;
282
29
  /**
@@ -287,9 +34,7 @@ export declare abstract class SanityCommand<T extends typeof Command>
287
34
  *
288
35
  * @deprecated use `getGlobalCliClient` function directly instead.
289
36
  */
290
- protected getGlobalApiClient: (
291
- args: GlobalCliClientOptions,
292
- ) => Promise<SanityClient>;
37
+ protected getGlobalApiClient: (args: GlobalCliClientOptions) => Promise<import("@sanity/client").SanityClient>;
293
38
  /**
294
39
  * Get the project API client.
295
40
  *
@@ -298,9 +43,7 @@ export declare abstract class SanityCommand<T extends typeof Command>
298
43
  *
299
44
  * @deprecated use `getProjectCliClient` function directly instead.
300
45
  */
301
- protected getProjectApiClient: (
302
- args: ProjectCliClientOptions,
303
- ) => Promise<SanityClient>;
46
+ protected getProjectApiClient: (args: ProjectCliClientOptions) => Promise<import("@sanity/client").SanityClient>;
304
47
  /**
305
48
  * Helper for outputting to the console.
306
49
  *
@@ -414,77 +157,5 @@ export declare abstract class SanityCommand<T extends typeof Command>
414
157
  */
415
158
  warn(input: Error | string): Error | string;
416
159
  }
417
-
418
- /**
419
- * Interface for `SanityCommand`, a wrapper around OCLIF's Command class.
420
- * Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.
421
- * @see https://oclif.io/docs/base_class/
422
- */
423
- export declare interface SanityCommandInterface {
424
- getCliConfig: () => Promise<CliConfig>;
425
- getProjectId: (options?: {
426
- deprecatedFlagName?: string;
427
- fallback?: () => Promise<string>;
428
- }) => Promise<string>;
429
- getProjectRoot: () => Promise<ProjectRootResult>;
430
- isUnattended: () => boolean;
431
- output: Output;
432
- resolveIsInteractive: () => boolean;
433
- }
434
-
435
- /**
436
- * Note that `sessionId` is removed from the signature of these functions
437
- */
438
- declare interface TelemetryLogger<UserProperties> {
439
- updateUserProperties(properties: UserProperties): void;
440
- resume(events: DeferredEvent[]): void;
441
- log<Data>(event: DefinedTelemetryLog<Data>, data: Data): void;
442
- log<Data extends void>(event: DefinedTelemetryLog<Data>): void;
443
- trace<Data>(
444
- event: DefinedTelemetryTrace<Data>,
445
- context?: unknown,
446
- ): TelemetryTrace<UserProperties, Data>;
447
- }
448
-
449
- declare interface TelemetryTrace<UserProperties, Data> {
450
- start(): void;
451
- log(data: Data): void;
452
- error(error: Error): void;
453
- complete(): void;
454
- newContext(name: string): TelemetryLogger<UserProperties>;
455
- await<P extends Promise<Data>>(promise: P): P;
456
- await<P extends Promise<unknown>>(promise: P, finalData: Data): P;
457
- }
458
-
459
- /**
460
- * @public
461
- */
462
- declare interface TelemetryUserProperties {
463
- cliVersion: string;
464
- cpuArchitecture: string;
465
- machinePlatform: string;
466
- runtime: string;
467
- runtimeVersion: string;
468
- dataset?: string;
469
- projectId?: string;
470
- }
471
-
472
- declare interface TypeGenConfig {
473
- formatGeneratedCode: boolean;
474
- generates: string;
475
- overloadClientMethods: boolean;
476
- path: string | string[];
477
- schema: string;
478
- }
479
-
480
- /**
481
- * @public
482
- */
483
- declare type UserViteConfig =
484
- | ((
485
- config: InlineConfig,
486
- env: ConfigEnv,
487
- ) => InlineConfig | Promise<InlineConfig>)
488
- | InlineConfig;
489
-
490
- export {};
160
+ export { SanityCommand, SanityCommandInterface };
161
+ //# sourceMappingURL=SanityCommand.d.ts.map
@@ -4,6 +4,7 @@ import { subdebug } from './_exports/debug.js';
4
4
  import { getGlobalCliClient, getProjectCliClient } from './apiClient.js';
5
5
  import { getCliConfig } from './config/cli/getCliConfig.js';
6
6
  import { findProjectRoot } from './config/findProjectRoot.js';
7
+ import { enrichAuthError } from './errors/enrichAuthError.js';
7
8
  import { NonInteractiveError } from './errors/NonInteractiveError.js';
8
9
  import { ProjectRootNotFoundError } from './errors/ProjectRootNotFoundError.js';
9
10
  import { getCliExecutionContext } from './executionContext.js';
@@ -60,6 +61,10 @@ export class SanityCommand extends Command {
60
61
  this.logToStderr(styleText('yellow', '\u{203A}') + ' Aborted by user');
61
62
  return this.exit(exitCodes.SIGINT);
62
63
  }
64
+ // 401s carry login/membership guidance in their message. Applied here
65
+ // rather than in transport middleware since client v8 dropped custom
66
+ // requesters.
67
+ enrichAuthError(err);
63
68
  // In other cases, we _do_ want to report the error
64
69
  reportCliTraceError(err);
65
70
  // oclif's base `catch` sets `process.exitCode` as a side effect
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/SanityCommand.ts"],"sourcesContent":["import {format, styleText} from 'node:util'\n\nimport {Command, Interfaces} from '@oclif/core'\nimport {type CommandError} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {\n getGlobalCliClient,\n getProjectCliClient,\n type GlobalCliClientOptions,\n type ProjectCliClientOptions,\n} from './apiClient.js'\nimport {getCliConfig} from './config/cli/getCliConfig.js'\nimport {type CliConfig} from './config/cli/types/cliConfig.js'\nimport {findProjectRoot} from './config/findProjectRoot.js'\nimport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nimport {NonInteractiveError} from './errors/NonInteractiveError.js'\nimport {ProjectRootNotFoundError} from './errors/ProjectRootNotFoundError.js'\nimport {getCliExecutionContext} from './executionContext.js'\nimport {exitCodes} from './exitCodes.js'\nimport {getCliTelemetry, reportCliTraceError} from './telemetry/getCliTelemetry.js'\nimport {type CLITelemetryStore} from './telemetry/types.js'\nimport {type Output} from './types.js'\nimport {isInteractive} from './util/isInteractive.js'\n\ntype Flags<T extends typeof Command> = Interfaces.InferredFlags<\n (typeof SanityCommand)['baseFlags'] & T['flags']\n>\n\ntype Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>\n\nconst debug = subdebug('sanityCommand')\n\n/**\n * Interface for `SanityCommand`, a wrapper around OCLIF's Command class.\n * Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.\n * @see https://oclif.io/docs/base_class/\n */\nexport interface SanityCommandInterface {\n getCliConfig: () => Promise<CliConfig>\n getProjectId: (options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }) => Promise<string>\n getProjectRoot: () => Promise<ProjectRootResult>\n isUnattended: () => boolean\n output: Output\n resolveIsInteractive: () => boolean\n}\n\nexport abstract class SanityCommand<T extends typeof Command>\n extends Command\n implements SanityCommandInterface\n{\n protected args!: Args<T>\n protected flags!: Flags<T>\n\n /**\n * Get the global API client.\n *\n * @param args - The global API client options.\n * @returns The global API client.\n *\n * @deprecated use `getGlobalCliClient` function directly instead.\n */\n protected getGlobalApiClient = (args: GlobalCliClientOptions) => getGlobalCliClient(args)\n\n /**\n * Get the project API client.\n *\n * @param args - The project API client options.\n * @returns The project API client.\n *\n * @deprecated use `getProjectCliClient` function directly instead.\n */\n protected getProjectApiClient = (args: ProjectCliClientOptions) => getProjectCliClient(args)\n\n /**\n * Helper for outputting to the console.\n *\n * @example\n * ```ts\n * this.output.log('Hello')\n * this.output.warn('Warning')\n * this.output.error('Error')\n * ```\n */\n public output: Output = {\n error: this.error.bind(this),\n log: this.log.bind(this),\n warn: this.warn.bind(this),\n }\n\n /**\n * The telemetry store.\n *\n * @returns The telemetry store.\n */\n protected telemetry!: CLITelemetryStore\n\n /**\n * Report real command errors to the CLI command trace.\n * User aborts (SIGINT, ExitPromptError) are not reported — the trace is left\n * incomplete, which accurately represents that the command was interrupted.\n */\n protected override async catch(err: CommandError): Promise<void> {\n // ExitPromptError is thrown by `@inquirer/prompts` when the user cancels a prompt\n // The `message === 'SIGINT'` check matches oclif's own convention (see handle.js in @oclif/core)\n if (err.name === 'ExitPromptError' || err.message === 'SIGINT') {\n this.logToStderr(styleText('yellow', '\\u{203A}') + ' Aborted by user')\n return this.exit(exitCodes.SIGINT)\n }\n\n // In other cases, we _do_ want to report the error\n reportCliTraceError(err)\n\n // oclif's base `catch` sets `process.exitCode` as a side effect\n // we do not want to write to the host's own exit status.\n if (getCliExecutionContext()) {\n if (this.jsonEnabled()) {\n this.logJson(this.toErrorJson(err))\n return\n }\n throw err\n }\n\n return super.catch(err)\n }\n\n /**\n * Get the CLI config.\n *\n * @returns The CLI config.\n */\n public async getCliConfig(): Promise<CliConfig> {\n const root = await this.getProjectRoot()\n\n debug(`Using project root`, root)\n return getCliConfig(root.directory)\n }\n\n /**\n * Get the project ID from passed flags or (if not provided) the CLI config.\n *\n * Optionally accepts a `fallback` function that is called when no project ID\n * can be determined from flags or config. This allows commands to provide\n * interactive project selection while keeping the prompt logic in the CLI package.\n *\n * If the fallback throws a `NonInteractiveError` (e.g. because the terminal is\n * not interactive), it falls through to the standard error with suggestions.\n *\n * Optionally accepts a `deprecatedFlagName` for commands that have a deprecated\n * flag (e.g. `--project`) that should be checked after `--project-id` but before\n * the CLI config.\n *\n * @returns The project ID.\n */\n public async getProjectId(options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }): Promise<string> {\n const hasProjectFlag = this.ctor.flags != null && 'project-id' in this.ctor.flags\n\n // Check --project-id flag first\n if (hasProjectFlag) {\n const flagProjectId =\n 'project-id' in this.flags && typeof this.flags['project-id'] === 'string'\n ? this.flags['project-id']\n : undefined\n\n if (flagProjectId) return flagProjectId\n }\n\n // Check deprecated flag (e.g. --project) before CLI config\n if (options?.deprecatedFlagName) {\n const deprecatedValue =\n options.deprecatedFlagName in this.flags &&\n typeof this.flags[options.deprecatedFlagName] === 'string'\n ? (this.flags[options.deprecatedFlagName] as string)\n : undefined\n\n if (deprecatedValue) return deprecatedValue\n }\n\n // Fall back to CLI config\n try {\n const config = await this.getCliConfig()\n const configProjectId = config.api?.projectId\n if (configProjectId) return configProjectId\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n // No project root — fall through to fallback/error\n }\n\n // Offer interactive selection if a fallback was provided\n if (options?.fallback) {\n try {\n return await options.fallback()\n } catch (err) {\n if (!(err instanceof NonInteractiveError)) throw err\n // Non-interactive: throw with actionable suggestions\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n cause: err,\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n 'Running in an interactive terminal to get a project selection prompt',\n ],\n })\n }\n }\n\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n ],\n })\n }\n\n /**\n * Get the project's root directory by resolving the config\n *\n * @returns The project root result.\n */\n public getProjectRoot(): Promise<ProjectRootResult> {\n if (getCliExecutionContext()) {\n throw new ProjectRootNotFoundError(\n 'Project root resolution from the filesystem is disabled for programmatic invocations',\n )\n }\n return findProjectRoot(process.cwd())\n }\n\n public async init(): Promise<void> {\n const {args, flags} = await this.parse({\n args: this.ctor.args,\n baseFlags: (super.ctor as typeof SanityCommand).baseFlags,\n enableJsonFlag: this.ctor.enableJsonFlag,\n flags: this.ctor.flags,\n strict: this.ctor.strict,\n })\n\n this.args = args as Args<T>\n this.flags = flags as Flags<T>\n this.telemetry = getCliTelemetry()\n\n await super.init()\n }\n\n /**\n * Check if the command is running in unattended mode.\n *\n * This means the command should not ask for user input, instead using defaults where\n * possible, and if that does not make sense (eg there's missing information), then we\n * should error out (remember to exit with a non-zero code).\n *\n * Most commands should take an explicit `--yes` flag to enable unattended mode, but\n * some commands may also be run in unattended mode if `process.stdin` is not a TTY\n * (eg when running in a CI environment), or when `--json` asks for machine-readable\n * output (a caller parsing JSON can't answer a prompt).\n */\n public isUnattended(): boolean {\n return this.flags.yes || this.flags.json || !this.resolveIsInteractive()\n }\n\n /**\n * Write to stdout — or, when running under an execution context (e.g. from\n * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`\n * semantics: suppressed when `--json` is enabled, printf-style formatting.\n */\n public override log(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.log(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stdout(format(message, ...args))\n }\n\n /**\n * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the\n * execution context's `stdout` sink, so programmatic callers don't have to\n * strip ANSI codes.\n */\n public override logJson(json: unknown): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.logJson(json)\n return\n }\n context.stdout(JSON.stringify(json, null, 2))\n }\n\n /**\n * Like `log`, but for stderr / the context's `stderr` sink.\n */\n public override logToStderr(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stderr) {\n super.logToStderr(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stderr(format(message, ...args))\n }\n\n /**\n * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.\n *\n * @returns Whether the terminal is interactive.\n */\n public resolveIsInteractive(): boolean {\n return isInteractive()\n }\n\n /**\n * Execute an already-constructed command without oclif's static runner:\n * `Command.run()` performs a full `Config.load()` — filesystem reads, env\n * consultation, and a process-global config cache write — on every call,\n * which programmatic invocations must not repeat per request.\n */\n public runInExecutionContext<TResult>(): Promise<TResult> {\n if (!getCliExecutionContext()) {\n throw new Error('runInExecutionContext requires a CLI execution context')\n }\n return this._run<TResult>()\n }\n\n /**\n * Get the CLI config, returning an empty config if no project root is found.\n *\n * Use this instead of `getCliConfig()` in commands that can operate without a\n * project directory (e.g. when `--project-id` and `--dataset` flags are provided).\n *\n * @returns The CLI config, or an empty config object if no project root is found.\n */\n protected async tryGetCliConfig(): Promise<CliConfig> {\n try {\n return await this.getCliConfig()\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n return {}\n }\n }\n\n /**\n * Emit a warning — routed to the execution context's `stderr` sink when one\n * is active, otherwise through oclif's standard warning printer.\n */\n public override warn(input: Error | string): Error | string {\n const context = getCliExecutionContext()\n if (!context?.stderr) return super.warn(input)\n\n if (!this.jsonEnabled()) {\n context.stderr(`Warning: ${input instanceof Error ? input.message : input}`)\n }\n return input\n }\n}\n"],"names":["format","styleText","Command","subdebug","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","NonInteractiveError","ProjectRootNotFoundError","getCliExecutionContext","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","debug","SanityCommand","args","flags","getGlobalApiClient","getProjectApiClient","output","error","bind","log","warn","telemetry","catch","err","name","message","logToStderr","exit","SIGINT","jsonEnabled","logJson","toErrorJson","root","getProjectRoot","directory","getProjectId","options","hasProjectFlag","ctor","flagProjectId","undefined","deprecatedFlagName","deprecatedValue","config","configProjectId","api","projectId","fallback","cause","suggestions","process","cwd","init","parse","baseFlags","enableJsonFlag","strict","isUnattended","yes","json","resolveIsInteractive","context","stdout","JSON","stringify","stderr","runInExecutionContext","Error","_run","tryGetCliConfig","input"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO,QAAmB,cAAa;AAG/C,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SACEC,kBAAkB,EAClBC,mBAAmB,QAGd,iBAAgB;AACvB,SAAQC,YAAY,QAAO,+BAA8B;AAEzD,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,SAAQC,mBAAmB,QAAO,kCAAiC;AACnE,SAAQC,wBAAwB,QAAO,uCAAsC;AAC7E,SAAQC,sBAAsB,QAAO,wBAAuB;AAC5D,SAAQC,SAAS,QAAO,iBAAgB;AACxC,SAAQC,eAAe,EAAEC,mBAAmB,QAAO,iCAAgC;AAGnF,SAAQC,aAAa,QAAO,0BAAyB;AAQrD,MAAMC,QAAQZ,SAAS;AAmBvB,OAAO,MAAea,sBACZd;IAGEe,KAAc;IACdC,MAAgB;IAE1B;;;;;;;GAOC,GACD,AAAUC,qBAAqB,CA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AE,EAAE,GAAGb,IAAe,EAAQ;QAClE,MAAMiD,UAAUxD;QAChB,IAAI,CAACwD,SAASI,QAAQ;YACpB,KAAK,CAACvC,YAAYD,YAAYb;YAC9B;QACF;QACA,IAAI,CAAC,IAAI,CAACiB,WAAW,IAAIgC,QAAQI,MAAM,CAACtE,OAAO8B,YAAYb;IAC7D;IAEA;;;;GAIC,GACD,AAAOgD,uBAAgC;QACrC,OAAOnD;IACT;IAEA;;;;;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,CAACpE,YAAY;QAChC,EAAE,OAAOsB,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} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {\n getGlobalCliClient,\n getProjectCliClient,\n type GlobalCliClientOptions,\n type ProjectCliClientOptions,\n} from './apiClient.js'\nimport {getCliConfig} from './config/cli/getCliConfig.js'\nimport {type CliConfig} from './config/cli/types/cliConfig.js'\nimport {findProjectRoot} from './config/findProjectRoot.js'\nimport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nimport {enrichAuthError} from './errors/enrichAuthError.js'\nimport {NonInteractiveError} from './errors/NonInteractiveError.js'\nimport {ProjectRootNotFoundError} from './errors/ProjectRootNotFoundError.js'\nimport {getCliExecutionContext} from './executionContext.js'\nimport {exitCodes} from './exitCodes.js'\nimport {getCliTelemetry, reportCliTraceError} from './telemetry/getCliTelemetry.js'\nimport {type CLITelemetryStore} from './telemetry/types.js'\nimport {type Output} from './types.js'\nimport {isInteractive} from './util/isInteractive.js'\n\ntype Flags<T extends typeof Command> = Interfaces.InferredFlags<\n (typeof SanityCommand)['baseFlags'] & T['flags']\n>\n\ntype Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>\n\nconst debug = subdebug('sanityCommand')\n\n/**\n * Interface for `SanityCommand`, a wrapper around OCLIF's Command class.\n * Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.\n * @see https://oclif.io/docs/base_class/\n */\nexport interface SanityCommandInterface {\n getCliConfig: () => Promise<CliConfig>\n getProjectId: (options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }) => Promise<string>\n getProjectRoot: () => Promise<ProjectRootResult>\n isUnattended: () => boolean\n output: Output\n resolveIsInteractive: () => boolean\n}\n\nexport abstract class SanityCommand<T extends typeof Command>\n extends Command\n implements SanityCommandInterface\n{\n protected args!: Args<T>\n protected flags!: Flags<T>\n\n /**\n * Get the global API client.\n *\n * @param args - The global API client options.\n * @returns The global API client.\n *\n * @deprecated use `getGlobalCliClient` function directly instead.\n */\n protected getGlobalApiClient = (args: GlobalCliClientOptions) => getGlobalCliClient(args)\n\n /**\n * Get the project API client.\n *\n * @param args - The project API client options.\n * @returns The project API client.\n *\n * @deprecated use `getProjectCliClient` function directly instead.\n */\n protected getProjectApiClient = (args: ProjectCliClientOptions) => getProjectCliClient(args)\n\n /**\n * Helper for outputting to the console.\n *\n * @example\n * ```ts\n * this.output.log('Hello')\n * this.output.warn('Warning')\n * this.output.error('Error')\n * ```\n */\n public output: Output = {\n error: this.error.bind(this),\n log: this.log.bind(this),\n warn: this.warn.bind(this),\n }\n\n /**\n * The telemetry store.\n *\n * @returns The telemetry store.\n */\n protected telemetry!: CLITelemetryStore\n\n /**\n * Report real command errors to the CLI command trace.\n * User aborts (SIGINT, ExitPromptError) are not reported — the trace is left\n * incomplete, which accurately represents that the command was interrupted.\n */\n protected override async catch(err: CommandError): Promise<void> {\n // ExitPromptError is thrown by `@inquirer/prompts` when the user cancels a prompt\n // The `message === 'SIGINT'` check matches oclif's own convention (see handle.js in @oclif/core)\n if (err.name === 'ExitPromptError' || err.message === 'SIGINT') {\n this.logToStderr(styleText('yellow', '\\u{203A}') + ' Aborted by user')\n return this.exit(exitCodes.SIGINT)\n }\n\n // 401s carry login/membership guidance in their message. Applied here\n // rather than in transport middleware since client v8 dropped custom\n // requesters.\n enrichAuthError(err)\n\n // In other cases, we _do_ want to report the error\n reportCliTraceError(err)\n\n // oclif's base `catch` sets `process.exitCode` as a side effect\n // we do not want to write to the host's own exit status.\n if (getCliExecutionContext()) {\n if (this.jsonEnabled()) {\n this.logJson(this.toErrorJson(err))\n return\n }\n throw err\n }\n\n return super.catch(err)\n }\n\n /**\n * Get the CLI config.\n *\n * @returns The CLI config.\n */\n public async getCliConfig(): Promise<CliConfig> {\n const root = await this.getProjectRoot()\n\n debug(`Using project root`, root)\n return getCliConfig(root.directory)\n }\n\n /**\n * Get the project ID from passed flags or (if not provided) the CLI config.\n *\n * Optionally accepts a `fallback` function that is called when no project ID\n * can be determined from flags or config. This allows commands to provide\n * interactive project selection while keeping the prompt logic in the CLI package.\n *\n * If the fallback throws a `NonInteractiveError` (e.g. because the terminal is\n * not interactive), it falls through to the standard error with suggestions.\n *\n * Optionally accepts a `deprecatedFlagName` for commands that have a deprecated\n * flag (e.g. `--project`) that should be checked after `--project-id` but before\n * the CLI config.\n *\n * @returns The project ID.\n */\n public async getProjectId(options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }): Promise<string> {\n const hasProjectFlag = this.ctor.flags != null && 'project-id' in this.ctor.flags\n\n // Check --project-id flag first\n if (hasProjectFlag) {\n const flagProjectId =\n 'project-id' in this.flags && typeof this.flags['project-id'] === 'string'\n ? this.flags['project-id']\n : undefined\n\n if (flagProjectId) return flagProjectId\n }\n\n // Check deprecated flag (e.g. --project) before CLI config\n if (options?.deprecatedFlagName) {\n const deprecatedValue =\n options.deprecatedFlagName in this.flags &&\n typeof this.flags[options.deprecatedFlagName] === 'string'\n ? (this.flags[options.deprecatedFlagName] as string)\n : undefined\n\n if (deprecatedValue) return deprecatedValue\n }\n\n // Fall back to CLI config\n try {\n const config = await this.getCliConfig()\n const configProjectId = config.api?.projectId\n if (configProjectId) return configProjectId\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n // No project root — fall through to fallback/error\n }\n\n // Offer interactive selection if a fallback was provided\n if (options?.fallback) {\n try {\n return await options.fallback()\n } catch (err) {\n if (!(err instanceof NonInteractiveError)) throw err\n // Non-interactive: throw with actionable suggestions\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n cause: err,\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n 'Running in an interactive terminal to get a project selection prompt',\n ],\n })\n }\n }\n\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n ],\n })\n }\n\n /**\n * Get the project's root directory by resolving the config\n *\n * @returns The project root result.\n */\n public getProjectRoot(): Promise<ProjectRootResult> {\n if (getCliExecutionContext()) {\n throw new ProjectRootNotFoundError(\n 'Project root resolution from the filesystem is disabled for programmatic invocations',\n )\n }\n return findProjectRoot(process.cwd())\n }\n\n public async init(): Promise<void> {\n const {args, flags} = await this.parse({\n args: this.ctor.args,\n baseFlags: (super.ctor as typeof SanityCommand).baseFlags,\n enableJsonFlag: this.ctor.enableJsonFlag,\n flags: this.ctor.flags,\n strict: this.ctor.strict,\n })\n\n this.args = args as Args<T>\n this.flags = flags as Flags<T>\n this.telemetry = getCliTelemetry()\n\n await super.init()\n }\n\n /**\n * Check if the command is running in unattended mode.\n *\n * This means the command should not ask for user input, instead using defaults where\n * possible, and if that does not make sense (eg there's missing information), then we\n * should error out (remember to exit with a non-zero code).\n *\n * Most commands should take an explicit `--yes` flag to enable unattended mode, but\n * some commands may also be run in unattended mode if `process.stdin` is not a TTY\n * (eg when running in a CI environment), or when `--json` asks for machine-readable\n * output (a caller parsing JSON can't answer a prompt).\n */\n public isUnattended(): boolean {\n return this.flags.yes || this.flags.json || !this.resolveIsInteractive()\n }\n\n /**\n * Write to stdout — or, when running under an execution context (e.g. from\n * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`\n * semantics: suppressed when `--json` is enabled, printf-style formatting.\n */\n public override log(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.log(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stdout(format(message, ...args))\n }\n\n /**\n * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the\n * execution context's `stdout` sink, so programmatic callers don't have to\n * strip ANSI codes.\n */\n public override logJson(json: unknown): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.logJson(json)\n return\n }\n context.stdout(JSON.stringify(json, null, 2))\n }\n\n /**\n * Like `log`, but for stderr / the context's `stderr` sink.\n */\n public override logToStderr(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stderr) {\n super.logToStderr(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stderr(format(message, ...args))\n }\n\n /**\n * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.\n *\n * @returns Whether the terminal is interactive.\n */\n public resolveIsInteractive(): boolean {\n return isInteractive()\n }\n\n /**\n * Execute an already-constructed command without oclif's static runner:\n * `Command.run()` performs a full `Config.load()` — filesystem reads, env\n * consultation, and a process-global config cache write — on every call,\n * which programmatic invocations must not repeat per request.\n */\n public runInExecutionContext<TResult>(): Promise<TResult> {\n if (!getCliExecutionContext()) {\n throw new Error('runInExecutionContext requires a CLI execution context')\n }\n return this._run<TResult>()\n }\n\n /**\n * Get the CLI config, returning an empty config if no project root is found.\n *\n * Use this instead of `getCliConfig()` in commands that can operate without a\n * project directory (e.g. when `--project-id` and `--dataset` flags are provided).\n *\n * @returns The CLI config, or an empty config object if no project root is found.\n */\n protected async tryGetCliConfig(): Promise<CliConfig> {\n try {\n return await this.getCliConfig()\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n return {}\n }\n }\n\n /**\n * Emit a warning — routed to the execution context's `stderr` sink when one\n * is active, otherwise through oclif's standard warning printer.\n */\n public override warn(input: Error | string): Error | string {\n const context = getCliExecutionContext()\n if (!context?.stderr) return super.warn(input)\n\n if (!this.jsonEnabled()) {\n context.stderr(`Warning: ${input instanceof Error ? input.message : input}`)\n }\n return input\n }\n}\n"],"names":["format","styleText","Command","subdebug","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","enrichAuthError","NonInteractiveError","ProjectRootNotFoundError","getCliExecutionContext","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","debug","SanityCommand","args","flags","getGlobalApiClient","getProjectApiClient","output","error","bind","log","warn","telemetry","catch","err","name","message","logToStderr","exit","SIGINT","jsonEnabled","logJson","toErrorJson","root","getProjectRoot","directory","getProjectId","options","hasProjectFlag","ctor","flagProjectId","undefined","deprecatedFlagName","deprecatedValue","config","configProjectId","api","projectId","fallback","cause","suggestions","process","cwd","init","parse","baseFlags","enableJsonFlag","strict","isUnattended","yes","json","resolveIsInteractive","context","stdout","JSON","stringify","stderr","runInExecutionContext","Error","_run","tryGetCliConfig","input"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO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A;;;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,21 +1,2 @@
1
- /**
2
- * Mocks a browser-like environment for processes in the main thread by:
3
- * - Injecting browser globals (window, document, ResizeObserver, etc.)
4
- * - Loading studio environment variables from the project's sanity installation into process.env
5
- *
6
- * This is useful for commands like `sanity exec` that have to run user scripts
7
- * in the main thread of the process (but in a child process).
8
- *
9
- * Be cautious when using this, since it will pollute the global namespace with browser globals.
10
- *
11
- * If your code can run in a worker thread, you should use the `studioWorkerTask` function instead.
12
- *
13
- * @param basePath - The root path of the Sanity Studio project
14
- * @returns A cleanup function that removes the injected globals and environment variables
15
- * @internal
16
- */
17
- export declare function mockBrowserEnvironment(
18
- basePath: string,
19
- ): Promise<() => void>;
20
-
21
- export {};
1
+ import { t as mockBrowserEnvironment } from "../mockBrowserEnvironment-BjFQPb2W.js";
2
+ export { mockBrowserEnvironment };