@sanity/cli-core 2.0.1 → 2.1.1

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.
@@ -15,6 +15,17 @@ import { WorkerOptions as WorkerOptions_2 } from "node:worker_threads";
15
15
  import { Workspace } from "sanity";
16
16
  import { z } from "zod/mini";
17
17
 
18
+ declare const APPLICATION_TYPES: readonly [
19
+ "coreApp",
20
+ "studio",
21
+ "canvas",
22
+ "dashboard",
23
+ "media-library",
24
+ ];
25
+
26
+ /** The resolved kind of a workbench app — `studio` or one of the SDK app types. */
27
+ export declare type ApplicationType = (typeof APPLICATION_TYPES)[number];
28
+
18
29
  declare type Args<T extends typeof Command> = Interfaces.InferredArgs<
19
30
  T["args"]
20
31
  >;
@@ -55,6 +66,8 @@ export declare interface CliConfig {
55
66
  app?: {
56
67
  /** The entrypoint for your custom app. By default, `src/App.tsx` */
57
68
  entry?: string;
69
+ /** Dock group the app renders in. Defaults to `dock.applications`. */
70
+ group?: "dock.applications" | "dock.system" | "dock.user";
58
71
  /**
59
72
  * Path to an icon file relative to project root.
60
73
  * The file must be an SVG.
@@ -64,6 +77,8 @@ export declare interface CliConfig {
64
77
  id?: string;
65
78
  /** The ID for the Sanity organization that manages this application */
66
79
  organizationId?: string;
80
+ /** Sort position within the dock group, ascending. Defaults to `100`. */
81
+ priority?: number;
67
82
  /** The title of the custom app, as it is seen in Dashboard UI */
68
83
  title?: string;
69
84
  };
@@ -109,7 +124,7 @@ export declare interface CliConfig {
109
124
  };
110
125
  /** Configuration options for React Compiler */
111
126
  reactCompiler?: PluginOptions;
112
- /** 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 false. */
127
+ /** 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. */
113
128
  reactStrictMode?: boolean;
114
129
  /**
115
130
  * Configuration for schema extraction (`sanity schema extract`)
@@ -214,6 +229,24 @@ export declare type ConsentInformation =
214
229
  */
215
230
  declare type ConsentStatus = "undetermined" | "unset" | "granted" | "denied";
216
231
 
232
+ export declare type CoreAppManifest = z.infer<typeof coreAppManifestSchema>;
233
+
234
+ /**
235
+ * Core-app application manifest. Mirrors the workbench's
236
+ * `CoreAppUserApplicationManifest` schema. Strictly validated via zod since the
237
+ * CLI produces the payload in full.
238
+ */
239
+ export declare const coreAppManifestSchema: z.ZodMiniObject<
240
+ {
241
+ group: z.ZodMiniOptional<z.ZodMiniString<string>>;
242
+ icon: z.ZodMiniOptional<z.ZodMiniString<string>>;
243
+ priority: z.ZodMiniOptional<z.ZodMiniNumber<number>>;
244
+ title: z.ZodMiniOptional<z.ZodMiniString<string>>;
245
+ version: z.ZodMiniString<string>;
246
+ },
247
+ z.core.$strip
248
+ >;
249
+
217
250
  /**
218
251
  * Creates a new worker for a studio worker task.
219
252
  *
@@ -395,6 +428,10 @@ declare type Flags<T extends typeof Command> = Interfaces.InferredFlags<
395
428
  *
396
429
  * If loading fails the cached promise is evicted so the next call retries.
397
430
  *
431
+ * Long-lived processes that need to observe edits to `sanity.cli.(ts|js)`
432
+ * (e.g. a dev-server watcher) should use {@link getCliConfigUncached}
433
+ * instead — it bypasses both this in-memory cache and Node's module cache.
434
+ *
398
435
  * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.
399
436
  * @returns The CLI config
400
437
  * @internal
@@ -413,6 +450,26 @@ export declare function getCliConfig(rootPath: string): Promise<CliConfig>;
413
450
  */
414
451
  export declare function getCliConfigSync(rootPath: string): CliConfig;
415
452
 
453
+ /**
454
+ * Read the CLI config for a project from disk, bypassing both the
455
+ * `getCliConfig` in-memory cache and Node's module cache. Each call locates
456
+ * `sanity.cli.(ts|js)`, drops any prior jiti compilation from `require.cache`,
457
+ * re-imports, and re-validates.
458
+ *
459
+ * Use this when the config file is expected to change during the process's
460
+ * lifetime — typically a dev-server watcher that needs the new values picked
461
+ * up after each save. One-shot CLI invocations should prefer
462
+ * {@link getCliConfig} so the prerun hook, SanityCommand helpers, and action
463
+ * files share a single load.
464
+ *
465
+ * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.
466
+ * @returns The freshly loaded CLI config
467
+ * @internal
468
+ */
469
+ export declare function getCliConfigUncached(
470
+ rootPath: string,
471
+ ): Promise<CliConfig>;
472
+
416
473
  /**
417
474
  * @public
418
475
  */
@@ -492,6 +549,30 @@ export declare function getProjectCliClient({
492
549
  ...config
493
550
  }: ProjectCliClientOptions): Promise<SanityClient_2>;
494
551
 
552
+ /**
553
+ * Returns the base Sanity configuration directory for the current user.
554
+ * For persistent user settings (auth tokens, preferences, etc.).
555
+ * Respects `SANITY_INTERNAL_ENV=staging` to isolate staging instances.
556
+ *
557
+ * Layout: `~/.config/sanity{-staging}/`
558
+ *
559
+ * @returns Absolute path to the config directory
560
+ * @internal
561
+ */
562
+ export declare function getSanityConfigDir(): string;
563
+
564
+ /**
565
+ * Returns the base Sanity data directory for the current user.
566
+ * For ephemeral runtime state (dev-server registries, caches, etc.).
567
+ * Respects `SANITY_INTERNAL_ENV=staging` to isolate staging instances.
568
+ *
569
+ * Layout: `~/.sanity{-staging}/`
570
+ *
571
+ * @returns Absolute path to the data directory
572
+ * @internal
573
+ */
574
+ export declare function getSanityDataDir(): string;
575
+
495
576
  /**
496
577
  * Gets an environment variable with the appropriate Sanity prefix based on whether it's an app or studio.
497
578
  *
@@ -693,6 +774,33 @@ export declare function isStaging(): boolean;
693
774
  */
694
775
  export declare function isStudioConfig(value: unknown): boolean;
695
776
 
777
+ /**
778
+ * Whether `app` is a branded `unstable_defineApp(...)` result — the sole
779
+ * workbench opt-in. Narrows to the shared `app` config plus the workbench-only
780
+ * fields a branded result carries: its `name`, the resolved `applicationType`
781
+ * (settled by `parseWorkbenchCliConfig` on load, so callers read it instead of
782
+ * re-deriving studio-vs-app), dock panel `views`, and background worker
783
+ * `services`. The `type` literals match the `DefineAppInput` schema so
784
+ * `views`/`services` stay assignable to `DefineAppInput['views' | 'services']`
785
+ * downstream.
786
+ */
787
+ export declare function isWorkbenchApp(
788
+ app: CliConfig["app"],
789
+ ): app is NonNullable<CliConfig["app"]> & {
790
+ applicationType?: ApplicationType;
791
+ name: string;
792
+ services?: {
793
+ name: string;
794
+ src: string;
795
+ type: "worker";
796
+ }[];
797
+ views?: {
798
+ name: string;
799
+ src: string;
800
+ type: "panel";
801
+ }[];
802
+ };
803
+
696
804
  /**
697
805
  * Mocks a browser-like environment for processes in the main thread by:
698
806
  * - Injecting browser globals (window, document, ResizeObserver, etc.)
@@ -1317,6 +1425,19 @@ export declare function setCliUserConfig(
1317
1425
  value: string | undefined,
1318
1426
  ): void;
1319
1427
 
1428
+ export declare type StudioManifest = z.infer<typeof studioManifestSchema>;
1429
+
1430
+ /**
1431
+ * Studio application manifest (serialized `create-manifest.json`). Kept loose so
1432
+ * the CLI isn't coupled to the workbench's evolving client-side schema — the
1433
+ * workbench consumer is authoritative on the inner shape. See its
1434
+ * `ClientManifest` for the fields clients expect.
1435
+ */
1436
+ export declare const studioManifestSchema: z.ZodMiniRecord<
1437
+ z.ZodMiniString<string>,
1438
+ z.ZodMiniUnknown
1439
+ >;
1440
+
1320
1441
  /**
1321
1442
  * Executes a worker file in a Sanity Studio browser context.
1322
1443
  *
@@ -1,5 +1,6 @@
1
1
  export * from '../config/cli/getCliConfig.js';
2
2
  export * from '../config/cli/getCliConfigSync.js';
3
+ export { isWorkbenchApp } from '../config/cli/workbenchApp.js';
3
4
  export * from '../config/findProjectRoot.js';
4
5
  export * from '../config/findProjectRootSync.js';
5
6
  export * from '../config/studio/getStudioConfig.js';
@@ -14,6 +15,7 @@ export * from '../errors/ProjectRootNotFoundError.js';
14
15
  export * from '../exitCodes.js';
15
16
  export * from '../loaders/studio/studioWorkerTask.js';
16
17
  export * from '../loaders/tsx/tsxWorkerTask.js';
18
+ export * from '../manifest.js';
17
19
  export * from '../SanityCommand.js';
18
20
  export * from '../services/apiClient.js';
19
21
  export * from '../services/cliUserConfig.js';
@@ -24,6 +26,7 @@ export { noopLogger } from '../telemetry/noopTelemetry.js';
24
26
  export { doImport } from '../util/doImport.js';
25
27
  export * from '../util/environment/mockBrowserEnvironment.js';
26
28
  export * from '../util/getLocalPackageVersion.js';
29
+ export * from '../util/getSanityConfigDir.js';
27
30
  export * from '../util/getSanityEnvVar.js';
28
31
  export * from '../util/getSanityUrl.js';
29
32
  export * from '../util/getWorkspace.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export * from '../config/cli/getCliConfig.js'\nexport * from '../config/cli/getCliConfigSync.js'\nexport {type CliConfig} from '../config/cli/types/cliConfig.js'\nexport {type UserViteConfig} from '../config/cli/types/userViteConfig.js'\nexport * from '../config/findProjectRoot.js'\nexport * from '../config/findProjectRootSync.js'\nexport * from '../config/studio/getStudioConfig.js'\nexport * from '../config/studio/getStudioWorkspaces.js'\nexport * from '../config/studio/isStudioConfig.js'\nexport * from '../config/util/findConfigsPaths.js'\nexport * from '../config/util/findStudioConfigPath.js'\nexport {type ProjectRootResult} from '../config/util/recursivelyResolveProjectRoot.js'\nexport * from '../debug.js'\nexport * from '../errors/NonInteractiveError.js'\nexport * from '../errors/NotFoundError.js'\nexport * from '../errors/ProjectRootNotFoundError.js'\nexport * from '../exitCodes.js'\nexport * from '../loaders/studio/studioWorkerTask.js'\nexport * from '../loaders/tsx/tsxWorkerTask.js'\nexport * from '../SanityCommand.js'\nexport * from '../services/apiClient.js'\nexport * from '../services/cliUserConfig.js'\nexport * from '../services/getCliToken.js'\nexport {\n clearCliTelemetry,\n CLI_TELEMETRY_SYMBOL,\n getCliTelemetry,\n setCliTelemetry,\n} from '../telemetry/getCliTelemetry.js'\nexport {getTelemetryBaseInfo} from '../telemetry/getTelemetryBaseInfo.js'\nexport {noopLogger} from '../telemetry/noopTelemetry.js'\nexport {\n type CLITelemetryStore,\n type ConsentInformation,\n type TelemetryUserProperties,\n} from '../telemetry/types.js'\nexport {type Output, type SanityOrgUser} from '../types.js'\nexport {doImport} from '../util/doImport.js'\nexport * from '../util/environment/mockBrowserEnvironment.js'\nexport * from '../util/getLocalPackageVersion.js'\nexport * from '../util/getSanityEnvVar.js'\nexport * from '../util/getSanityUrl.js'\nexport * from '../util/getWorkspace.js'\nexport * from '../util/importModule.js'\nexport * from '../util/isCi.js'\nexport * from '../util/isInteractive.js'\nexport * from '../util/isStaging.js'\nexport * from '../util/normalizePath.js'\nexport * from '../util/promisifyWorker.js'\nexport * from '../util/readPackageJson.js'\nexport * from '../util/resolveLocalPackage.js'\nexport * from '../util/safeStructuredClone.js'\nexport * from '../ux/colorizeJson.js'\nexport * from '../ux/timer.js'\n"],"names":["clearCliTelemetry","CLI_TELEMETRY_SYMBOL","getCliTelemetry","setCliTelemetry","getTelemetryBaseInfo","noopLogger","doImport"],"mappings":"AAAA,cAAc,gCAA+B;AAC7C,cAAc,oCAAmC;AAGjD,cAAc,+BAA8B;AAC5C,cAAc,mCAAkC;AAChD,cAAc,sCAAqC;AACnD,cAAc,0CAAyC;AACvD,cAAc,qCAAoC;AAClD,cAAc,qCAAoC;AAClD,cAAc,yCAAwC;AAEtD,cAAc,cAAa;AAC3B,cAAc,mCAAkC;AAChD,cAAc,6BAA4B;AAC1C,cAAc,wCAAuC;AACrD,cAAc,kBAAiB;AAC/B,cAAc,wCAAuC;AACrD,cAAc,kCAAiC;AAC/C,cAAc,sBAAqB;AACnC,cAAc,2BAA0B;AACxC,cAAc,+BAA8B;AAC5C,cAAc,6BAA4B;AAC1C,SACEA,iBAAiB,EACjBC,oBAAoB,EACpBC,eAAe,EACfC,eAAe,QACV,kCAAiC;AACxC,SAAQC,oBAAoB,QAAO,uCAAsC;AACzE,SAAQC,UAAU,QAAO,gCAA+B;AAOxD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,cAAc,gDAA+C;AAC7D,cAAc,oCAAmC;AACjD,cAAc,6BAA4B;AAC1C,cAAc,0BAAyB;AACvC,cAAc,0BAAyB;AACvC,cAAc,0BAAyB;AACvC,cAAc,kBAAiB;AAC/B,cAAc,2BAA0B;AACxC,cAAc,uBAAsB;AACpC,cAAc,2BAA0B;AACxC,cAAc,6BAA4B;AAC1C,cAAc,6BAA4B;AAC1C,cAAc,iCAAgC;AAC9C,cAAc,iCAAgC;AAC9C,cAAc,wBAAuB;AACrC,cAAc,iBAAgB"}
1
+ {"version":3,"sources":["../../src/_exports/index.ts"],"sourcesContent":["export * from '../config/cli/getCliConfig.js'\nexport * from '../config/cli/getCliConfigSync.js'\nexport {type CliConfig} from '../config/cli/types/cliConfig.js'\nexport {type UserViteConfig} from '../config/cli/types/userViteConfig.js'\nexport {type ApplicationType, isWorkbenchApp} from '../config/cli/workbenchApp.js'\nexport * from '../config/findProjectRoot.js'\nexport * from '../config/findProjectRootSync.js'\nexport * from '../config/studio/getStudioConfig.js'\nexport * from '../config/studio/getStudioWorkspaces.js'\nexport * from '../config/studio/isStudioConfig.js'\nexport * from '../config/util/findConfigsPaths.js'\nexport * from '../config/util/findStudioConfigPath.js'\nexport {type ProjectRootResult} from '../config/util/recursivelyResolveProjectRoot.js'\nexport * from '../debug.js'\nexport * from '../errors/NonInteractiveError.js'\nexport * from '../errors/NotFoundError.js'\nexport * from '../errors/ProjectRootNotFoundError.js'\nexport * from '../exitCodes.js'\nexport * from '../loaders/studio/studioWorkerTask.js'\nexport * from '../loaders/tsx/tsxWorkerTask.js'\nexport * from '../manifest.js'\nexport * from '../SanityCommand.js'\nexport * from '../services/apiClient.js'\nexport * from '../services/cliUserConfig.js'\nexport * from '../services/getCliToken.js'\nexport {\n clearCliTelemetry,\n CLI_TELEMETRY_SYMBOL,\n getCliTelemetry,\n setCliTelemetry,\n} from '../telemetry/getCliTelemetry.js'\nexport {getTelemetryBaseInfo} from '../telemetry/getTelemetryBaseInfo.js'\nexport {noopLogger} from '../telemetry/noopTelemetry.js'\nexport {\n type CLITelemetryStore,\n type ConsentInformation,\n type TelemetryUserProperties,\n} from '../telemetry/types.js'\nexport {type Output, type SanityOrgUser} from '../types.js'\nexport {doImport} from '../util/doImport.js'\nexport * from '../util/environment/mockBrowserEnvironment.js'\nexport * from '../util/getLocalPackageVersion.js'\nexport * from '../util/getSanityConfigDir.js'\nexport * from '../util/getSanityEnvVar.js'\nexport * from '../util/getSanityUrl.js'\nexport * from '../util/getWorkspace.js'\nexport * from '../util/importModule.js'\nexport * from '../util/isCi.js'\nexport * from '../util/isInteractive.js'\nexport * from '../util/isStaging.js'\nexport * from '../util/normalizePath.js'\nexport * from '../util/promisifyWorker.js'\nexport * from '../util/readPackageJson.js'\nexport * from '../util/resolveLocalPackage.js'\nexport * from '../util/safeStructuredClone.js'\nexport * from '../ux/colorizeJson.js'\nexport * from '../ux/timer.js'\n"],"names":["isWorkbenchApp","clearCliTelemetry","CLI_TELEMETRY_SYMBOL","getCliTelemetry","setCliTelemetry","getTelemetryBaseInfo","noopLogger","doImport"],"mappings":"AAAA,cAAc,gCAA+B;AAC7C,cAAc,oCAAmC;AAGjD,SAA8BA,cAAc,QAAO,gCAA+B;AAClF,cAAc,+BAA8B;AAC5C,cAAc,mCAAkC;AAChD,cAAc,sCAAqC;AACnD,cAAc,0CAAyC;AACvD,cAAc,qCAAoC;AAClD,cAAc,qCAAoC;AAClD,cAAc,yCAAwC;AAEtD,cAAc,cAAa;AAC3B,cAAc,mCAAkC;AAChD,cAAc,6BAA4B;AAC1C,cAAc,wCAAuC;AACrD,cAAc,kBAAiB;AAC/B,cAAc,wCAAuC;AACrD,cAAc,kCAAiC;AAC/C,cAAc,iBAAgB;AAC9B,cAAc,sBAAqB;AACnC,cAAc,2BAA0B;AACxC,cAAc,+BAA8B;AAC5C,cAAc,6BAA4B;AAC1C,SACEC,iBAAiB,EACjBC,oBAAoB,EACpBC,eAAe,EACfC,eAAe,QACV,kCAAiC;AACxC,SAAQC,oBAAoB,QAAO,uCAAsC;AACzE,SAAQC,UAAU,QAAO,gCAA+B;AAOxD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,cAAc,gDAA+C;AAC7D,cAAc,oCAAmC;AACjD,cAAc,gCAA+B;AAC7C,cAAc,6BAA4B;AAC1C,cAAc,0BAAyB;AACvC,cAAc,0BAAyB;AACvC,cAAc,0BAAyB;AACvC,cAAc,kBAAiB;AAC/B,cAAc,2BAA0B;AACxC,cAAc,uBAAsB;AACpC,cAAc,2BAA0B;AACxC,cAAc,6BAA4B;AAC1C,cAAc,6BAA4B;AAC1C,cAAc,iCAAgC;AAC9C,cAAc,iCAAgC;AAC9C,cAAc,wBAAuB;AACrC,cAAc,iBAAgB"}
@@ -1,8 +1,11 @@
1
+ import { createRequire } from 'node:module';
2
+ import { dirname } from 'node:path';
1
3
  import { debug } from '../../debug.js';
2
4
  import { NotFoundError } from '../../errors/NotFoundError.js';
3
5
  import { importModule } from '../../util/importModule.js';
4
6
  import { findPathForFiles } from '../util/findConfigsPaths.js';
5
7
  import { cliConfigSchema } from './schemas.js';
8
+ import { isWorkbenchApp, parseWorkbenchCliConfig } from './workbenchApp.js';
6
9
  const cache = new Map();
7
10
  /**
8
11
  * Get the CLI config for a project, given the root path.
@@ -15,6 +18,10 @@ const cache = new Map();
15
18
  *
16
19
  * If loading fails the cached promise is evicted so the next call retries.
17
20
  *
21
+ * Long-lived processes that need to observe edits to `sanity.cli.(ts|js)`
22
+ * (e.g. a dev-server watcher) should use {@link getCliConfigUncached}
23
+ * instead — it bypasses both this in-memory cache and Node's module cache.
24
+ *
18
25
  * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.
19
26
  * @returns The CLI config
20
27
  * @internal
@@ -23,14 +30,29 @@ const cache = new Map();
23
30
  if (cached) {
24
31
  return cached;
25
32
  }
26
- const promise = loadCliConfig(rootPath).catch((err)=>{
33
+ const promise = getCliConfigUncached(rootPath).catch((err)=>{
27
34
  cache.delete(rootPath);
28
35
  throw err;
29
36
  });
30
37
  cache.set(rootPath, promise);
31
38
  return promise;
32
39
  }
33
- async function loadCliConfig(rootPath) {
40
+ /**
41
+ * Read the CLI config for a project from disk, bypassing both the
42
+ * `getCliConfig` in-memory cache and Node's module cache. Each call locates
43
+ * `sanity.cli.(ts|js)`, drops any prior jiti compilation from `require.cache`,
44
+ * re-imports, and re-validates.
45
+ *
46
+ * Use this when the config file is expected to change during the process's
47
+ * lifetime — typically a dev-server watcher that needs the new values picked
48
+ * up after each save. One-shot CLI invocations should prefer
49
+ * {@link getCliConfig} so the prerun hook, SanityCommand helpers, and action
50
+ * files share a single load.
51
+ *
52
+ * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.
53
+ * @returns The freshly loaded CLI config
54
+ * @internal
55
+ */ export async function getCliConfigUncached(rootPath) {
34
56
  const paths = await findPathForFiles(rootPath, [
35
57
  'sanity.cli.ts',
36
58
  'sanity.cli.js'
@@ -44,6 +66,12 @@ async function loadCliConfig(rootPath) {
44
66
  }
45
67
  const configPath = configPaths[0].path;
46
68
  debug(`Loading CLI config from: ${configPath}`);
69
+ // Drop any cached compilation of this file from Node's CJS module cache
70
+ // (jiti compiles `sanity.cli.ts` to CJS and registers it via `require.cache`).
71
+ // Without this, repeated calls would receive the previously imported module
72
+ // even though the file on disk has changed. No-op on first load.
73
+ const cjsRequire = createRequire(import.meta.url);
74
+ delete cjsRequire.cache[configPath];
47
75
  let cliConfig;
48
76
  try {
49
77
  const result = await importModule(configPath);
@@ -55,6 +83,11 @@ async function loadCliConfig(rootPath) {
55
83
  cause: err
56
84
  });
57
85
  }
86
+ // Branch as early as possible: a branded `unstable_defineApp(...)` opts into
87
+ // workbench behavior, so its `app` skips the legacy `app` schema entirely.
88
+ if (isWorkbenchApp(cliConfig?.app)) {
89
+ return parseWorkbenchCliConfig(cliConfig, dirname(configPath));
90
+ }
58
91
  const { data, error, success } = cliConfigSchema.safeParse(cliConfig);
59
92
  if (!success) {
60
93
  debug(`Invalid CLI config: ${error.message}`);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/config/cli/getCliConfig.ts"],"sourcesContent":["import {debug} from '../../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'\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 * @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 = loadCliConfig(rootPath).catch((err) => {\n cache.delete(rootPath)\n throw err\n })\n\n cache.set(rootPath, promise)\n return promise\n}\n\nasync function loadCliConfig(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 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 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":["debug","NotFoundError","importModule","findPathForFiles","cliConfigSchema","cache","Map","getCliConfig","rootPath","cached","get","promise","loadCliConfig","catch","err","delete","set","paths","configPaths","filter","path","exists","length","Error","map","join","configPath","cliConfig","result","cause","data","error","success","safeParse","message"],"mappings":"AAAA,SAAQA,KAAK,QAAO,iBAAgB;AACpC,SAAQC,aAAa,QAAO,gCAA+B;AAC3D,SAAQC,YAAY,QAAO,6BAA4B;AACvD,SAAQC,gBAAgB,QAAO,8BAA6B;AAC5D,SAAQC,eAAe,QAAO,eAAc;AAG5C,MAAMC,QAAQ,IAAIC;AAElB;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,aAAaC,QAAgB;IAC3C,MAAMC,SAASJ,MAAMK,GAAG,CAACF;IACzB,IAAIC,QAAQ;QACV,OAAOA;IACT;IAEA,MAAME,UAAUC,cAAcJ,UAAUK,KAAK,CAAC,CAACC;QAC7CT,MAAMU,MAAM,CAACP;QACb,MAAMM;IACR;IAEAT,MAAMW,GAAG,CAACR,UAAUG;IACpB,OAAOA;AACT;AAEA,eAAeC,cAAcJ,QAAgB;IAC3C,MAAMS,QAAQ,MAAMd,iBAAiBK,UAAU;QAAC;QAAiB;KAAgB;IACjF,MAAMU,cAAcD,MAAME,MAAM,CAAC,CAACC,OAASA,KAAKC,MAAM;IAEtD,IAAIH,YAAYI,MAAM,KAAK,GAAG;QAC5B,MAAM,IAAIrB,cAAc,CAAC,uBAAuB,EAAEO,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;IAEtCpB,MAAM,CAAC,yBAAyB,EAAE0B,YAAY;IAE9C,IAAIC;IACJ,IAAI;QACF,MAAMC,SAAS,MAAM1B,aAAwBwB;QAE7C1B,MAAM,yBAAyB4B;QAE/BD,YAAYC;IACd,EAAE,OAAOd,KAAK;QACZd,MAAM,kDAAkDc;QAExD,MAAM,IAAIS,MAAM,+BAA+B;YAACM,OAAOf;QAAG;IAC5D;IAEA,MAAM,EAACgB,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAG5B,gBAAgB6B,SAAS,CAACN;IACzD,IAAI,CAACK,SAAS;QACZhC,MAAM,CAAC,oBAAoB,EAAE+B,MAAMG,OAAO,EAAE;QAC5C,MAAM,IAAIX,MAAM,CAAC,oBAAoB,EAAEQ,MAAMG,OAAO,EAAE,EAAE;YAACL,OAAOE;QAAK;IACvE;IAEA,OAAOD;AACT"}
1
+ {"version":3,"sources":["../../../src/config/cli/getCliConfig.ts"],"sourcesContent":["import {createRequire} from 'node:module'\nimport {dirname} from 'node:path'\n\nimport {debug} from '../../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 `unstable_defineApp(...)` opts into\n // workbench behavior, so its `app` skips the legacy `app` schema entirely.\n if (isWorkbenchApp(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","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,iBAAgB;AACpC,SAAQC,aAAa,QAAO,gCAA+B;AAC3D,SAAQC,YAAY,QAAO,6BAA4B;AACvD,SAAQC,gBAAgB,QAAO,8BAA6B;AAC5D,SAAQC,eAAe,QAAO,eAAc;AAE5C,SAAQC,cAAc,EAAEC,uBAAuB,QAAO,oBAAmB;AAEzE,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;IACp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AE;QAC5C,MAAM,IAAId,MAAM,CAAC,oBAAoB,EAAEW,MAAMG,OAAO,EAAE,EAAE;YAACN,OAAOG;QAAK;IACvE;IAEA,OAAOD;AACT"}
@@ -5,6 +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
9
  /**
9
10
  * Get the CLI config for a project synchronously, given the root path.
10
11
  *
@@ -39,6 +40,11 @@ import { cliConfigSchema } from './schemas.js';
39
40
  } finally{
40
41
  unregister();
41
42
  }
43
+ // Branch as early as possible: a branded `unstable_defineApp(...)` opts into
44
+ // workbench behavior, so its `app` skips the legacy `app` schema entirely.
45
+ if (isWorkbenchApp(cliConfig?.app)) {
46
+ return parseWorkbenchCliConfig(cliConfig, rootPath);
47
+ }
42
48
  const { data, error, success } = cliConfigSchema.safeParse(cliConfig);
43
49
  if (!success) {
44
50
  throw new Error(`Invalid CLI config: ${error.message}`);
@@ -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'\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 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","getCliConfigSync","rootPath","possiblePaths","map","file","configPaths","filter","path","length","Error","configPath","unregister","cliConfig","require","url","loaded","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;AAG5C;;;;;;;;;CASC,GACD,OAAO,SAASC,iBAAiBC,QAAgB;IAC/C,MAAMC,gBAAgB;QAAC;QAAiB;KAAgB,CAACC,GAAG,CAAC,CAACC,OAAST,KAAKM,UAAUG;IACtF,MAAMC,cAAcH,cAAcI,MAAM,CAAC,CAACC,OAASd,WAAWc;IAE9D,IAAIF,YAAYG,MAAM,KAAK,GAAG;QAC5B,MAAM,IAAIX,cAAc,CAAC,uBAAuB,EAAEI,SAAS,mBAAmB,CAAC;IACjF;IAEA,IAAII,YAAYG,MAAM,GAAG,GAAG;QAC1B,MAAM,IAAIC,MAAM,CAAC,iCAAiC,EAAEJ,YAAYV,IAAI,CAAC,MAAM,CAAC,CAAC;IAC/E;IAEA,MAAMe,aAAaL,WAAW,CAAC,EAAE;IAEjC,sCAAsC;IACtC,MAAMM,aAAaf;IAEnB,IAAIgB;IACJ,IAAI;QACF,4DAA4D;QAC5D,uCAAuC;QACvC,MAAMC,UAAUnB,cAAc,YAAYoB,GAAG;QAC7C,MAAMC,SAASF,QAAQH;QACvBE,YAAYd,oBAAoBiB;IAClC,SAAU;QACRJ;IACF;IAEA,MAAM,EAACK,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGnB,gBAAgBoB,SAAS,CAACP;IACzD,IAAI,CAACM,SAAS;QACZ,MAAM,IAAIT,MAAM,CAAC,oBAAoB,EAAEQ,MAAMG,OAAO,EAAE;IACxD;IAEA,oFAAoF;IACpF,4EAA4E;IAC5E,OAAOJ;AACT"}
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 `unstable_defineApp(...)` opts into\n // workbench behavior, so its `app` skips the legacy `app` schema entirely.\n if (isWorkbenchApp(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","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,uBAAuB,QAAO,oBAAmB;AAEzE;;;;;;;;;CASC,GACD,OAAO,SAASC,iBAAiBC,QAAgB;IAC/C,MAAMC,gBAAgB;QAAC;QAAiB;KAAgB,CAACC,GAAG,CAAC,CAACC,OAASX,KAAKQ,UAAUG;IACtF,MAAMC,cAAcH,cAAcI,MAAM,CAAC,CAACC,OAAShB,WAAWgB;IAE9D,IAAIF,YAAYG,MAAM,KAAK,GAAG;QAC5B,MAAM,IAAIb,cAAc,CAAC,uBAAuB,EAAEM,SAAS,mBAAmB,CAAC;IACjF;IAEA,IAAII,YAAYG,MAAM,GAAG,GAAG;QAC1B,MAAM,IAAIC,MAAM,CAAC,iCAAiC,EAAEJ,YAAYZ,IAAI,CAAC,MAAM,CAAC,CAAC;IAC/E;IAEA,MAAMiB,aAAaL,WAAW,CAAC,EAAE;IAEjC,sCAAsC;IACtC,MAAMM,aAAajB;IAEnB,IAAIkB;IACJ,IAAI;QACF,4DAA4D;QAC5D,uCAAuC;QACvC,MAAMC,UAAUrB,cAAc,YAAYsB,GAAG;QAC7C,MAAMC,SAASF,QAAQH;QACvBE,YAAYhB,oBAAoBmB;IAClC,SAAU;QACRJ;IACF;IAEA,6EAA6E;IAC7E,2EAA2E;IAC3E,IAAIb,eAAec,WAAWI,MAAM;QAClC,OAAOjB,wBAAwBa,WAAWX;IAC5C;IAEA,MAAM,EAACgB,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGtB,gBAAgBuB,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 +1 @@
1
- {"version":3,"sources":["../../../../src/config/cli/types/cliConfig.ts"],"sourcesContent":["import {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\n\nimport {type UserViteConfig} from './userViteConfig'\n\nexport interface TypeGenConfig {\n formatGeneratedCode: boolean\n generates: string\n overloadClientMethods: boolean\n path: string | string[]\n schema: string\n}\n\n/**\n * @public\n */\nexport interface CliConfig {\n /** The project ID and dataset the Sanity CLI should use to run its commands */\n api?: {\n dataset?: string\n projectId?: string\n }\n\n /** Configuration for custom Sanity apps built with the App SDK */\n app?: {\n /** The entrypoint for your custom app. By default, `src/App.tsx` */\n entry?: string\n /**\n * Path to an icon file relative to project root.\n * The file must be an SVG.\n */\n icon?: string\n /** @deprecated Use deployment.appId */\n id?: string\n /** The ID for the Sanity organization that manages this application */\n organizationId?: string\n /** The title of the custom app, as it is seen in Dashboard UI */\n title?: string\n }\n\n /** @deprecated Use deployment.autoUpdates */\n autoUpdates?: boolean\n\n /** Options for custom app and Studio deployments */\n deployment?: {\n /**\n * The ID for your custom app or Studio. Generated when deploying your app or Studio for the first time.\n * Get your app ID by either:\n * 1. Checking the output of `sanity deploy`, or\n * 2. Checking your project’s Studio tab at https://sanity.io/manage\n *\n * @remarks This is required for all custom app deployments, and for Studios opting in to fine grained version control.\n * {@link https://www.sanity.io/docs/studio/latest-version-of-sanity#k0896ed4574b7}\n */\n appId?: string\n /**\n * Enable automatic updates for your Studio or custom app’s Sanity dependencies.\n * {@link https://www.sanity.io/docs/studio/latest-version-of-sanity}\n */\n autoUpdates?: boolean\n }\n\n /** Define the GraphQL APIs that the CLI can deploy and interact with */\n graphql?: Array<{\n filterSuffix?: string\n generation?: 'gen1' | 'gen2' | 'gen3'\n id?: string\n nonNullDocumentFields?: boolean\n playground?: boolean\n source?: string\n tag?: string\n workspace?: string\n }>\n\n /** Configuration for the Media Library */\n mediaLibrary?: {\n /** The path to the Media Library aspects directory. When using the CLI to manage aspects, this is the directory they will be read from and written to. */\n aspectsPath?: string\n }\n\n /** Contains the property `basePath` which lets you change the top-level slug for the Studio. You typically need to set this if you embed the Studio in another application where it is one of many routes. Defaults to an empty string. */\n project?: {\n basePath?: string\n }\n\n /** Configuration options for React Compiler */\n reactCompiler?: ReactCompilerConfig\n\n /** Wraps the Studio in \\<React.StrictMode\\> root to aid in flagging potential problems related to concurrent features (startTransition, useTransition, useDeferredValue, Suspense). Can also be enabled by setting SANITY_STUDIO_REACT_STRICT_MODE=\"true\"|\"false\". It only applies to sanity dev in development mode and is ignored in sanity build and in production. Defaults to false. */\n reactStrictMode?: boolean\n\n /**\n * Configuration for schema extraction (`sanity schema extract`)\n */\n schemaExtraction?: {\n /**\n * Enable schema extraction as part of sanity dev and sanity build\n */\n enabled?: boolean\n\n /**\n * When true, schema fields marked as required will be non-optional in the output.\n * Defaults to `false`\n */\n enforceRequiredFields?: boolean\n\n /**\n * Output path for the extracted schema file.\n * Defaults to `schema.json` in the working directory.\n */\n path?: string\n\n /**\n * Additional glob patterns to watch for schema changes in watch mode.\n * These extend the default patterns:\n * - `sanity.config.{js,jsx,ts,tsx,mjs}`\n * - `schema*\\/**\\/*.{js,jsx,ts,tsx,mjs}`\n */\n watchPatterns?: string[]\n\n /**\n * The name of the workspace to generate a schema for. Required if your Sanity project has more than one\n * workspace.\n */\n workspace?: string\n }\n\n /** Defines the hostname and port that the development server should run on. hostname defaults to localhost, and port to 3333. */\n server?: {\n hostname?: string\n port?: number\n }\n\n /** @deprecated Use deployment.appId */\n studioHost?: string\n\n /**\n * Configuration for Sanity typegen\n */\n typegen?: Partial<TypeGenConfig> & {\n /**\n * Enable typegen as part of sanity dev and sanity build.\n * When enabled, types are generated on startup and when files change.\n * Defaults to `false`\n */\n enabled?: boolean\n }\n\n /** Exposes the default Vite configuration for custom apps and the Studio so it can be changed and extended. */\n vite?: UserViteConfig\n}\n"],"names":[],"mappings":"AAYA;;CAEC,GACD,WAsIC"}
1
+ {"version":3,"sources":["../../../../src/config/cli/types/cliConfig.ts"],"sourcesContent":["import {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\n\nimport {type UserViteConfig} from './userViteConfig'\n\nexport interface TypeGenConfig {\n formatGeneratedCode: boolean\n generates: string\n overloadClientMethods: boolean\n path: string | string[]\n schema: string\n}\n\n/**\n * @public\n */\nexport interface CliConfig {\n /** The project ID and dataset the Sanity CLI should use to run its commands */\n api?: {\n dataset?: string\n projectId?: string\n }\n\n /** Configuration for custom Sanity apps built with the App SDK */\n app?: {\n /** The entrypoint for your custom app. By default, `src/App.tsx` */\n entry?: string\n /** Dock group the app renders in. Defaults to `dock.applications`. */\n group?: 'dock.applications' | 'dock.system' | 'dock.user'\n /**\n * Path to an icon file relative to project root.\n * The file must be an SVG.\n */\n icon?: string\n /** @deprecated Use deployment.appId */\n id?: string\n /** The ID for the Sanity organization that manages this application */\n organizationId?: string\n /** Sort position within the dock group, ascending. Defaults to `100`. */\n priority?: number\n /** The title of the custom app, as it is seen in Dashboard UI */\n title?: string\n }\n\n /** @deprecated Use deployment.autoUpdates */\n autoUpdates?: boolean\n\n /** Options for custom app and Studio deployments */\n deployment?: {\n /**\n * The ID for your custom app or Studio. Generated when deploying your app or Studio for the first time.\n * Get your app ID by either:\n * 1. Checking the output of `sanity deploy`, or\n * 2. Checking your project’s Studio tab at https://sanity.io/manage\n *\n * @remarks This is required for all custom app deployments, and for Studios opting in to fine grained version control.\n * {@link https://www.sanity.io/docs/studio/latest-version-of-sanity#k0896ed4574b7}\n */\n appId?: string\n /**\n * Enable automatic updates for your Studio or custom app’s Sanity dependencies.\n * {@link https://www.sanity.io/docs/studio/latest-version-of-sanity}\n */\n autoUpdates?: boolean\n }\n\n /** Define the GraphQL APIs that the CLI can deploy and interact with */\n graphql?: Array<{\n filterSuffix?: string\n generation?: 'gen1' | 'gen2' | 'gen3'\n id?: string\n nonNullDocumentFields?: boolean\n playground?: boolean\n source?: string\n tag?: string\n workspace?: string\n }>\n\n /** Configuration for the Media Library */\n mediaLibrary?: {\n /** The path to the Media Library aspects directory. When using the CLI to manage aspects, this is the directory they will be read from and written to. */\n aspectsPath?: string\n }\n\n /** Contains the property `basePath` which lets you change the top-level slug for the Studio. You typically need to set this if you embed the Studio in another application where it is one of many routes. Defaults to an empty string. */\n project?: {\n basePath?: string\n }\n\n /** Configuration options for React Compiler */\n reactCompiler?: ReactCompilerConfig\n\n /** Wraps the Studio in \\<React.StrictMode\\> root to aid in flagging potential problems related to concurrent features (startTransition, useTransition, useDeferredValue, Suspense). Can also be enabled by setting SANITY_STUDIO_REACT_STRICT_MODE=\"true\"|\"false\". It only applies to sanity dev in development mode and is ignored in sanity build and in production. Defaults to true. */\n reactStrictMode?: boolean\n\n /**\n * Configuration for schema extraction (`sanity schema extract`)\n */\n schemaExtraction?: {\n /**\n * Enable schema extraction as part of sanity dev and sanity build\n */\n enabled?: boolean\n\n /**\n * When true, schema fields marked as required will be non-optional in the output.\n * Defaults to `false`\n */\n enforceRequiredFields?: boolean\n\n /**\n * Output path for the extracted schema file.\n * Defaults to `schema.json` in the working directory.\n */\n path?: string\n\n /**\n * Additional glob patterns to watch for schema changes in watch mode.\n * These extend the default patterns:\n * - `sanity.config.{js,jsx,ts,tsx,mjs}`\n * - `schema*\\/**\\/*.{js,jsx,ts,tsx,mjs}`\n */\n watchPatterns?: string[]\n\n /**\n * The name of the workspace to generate a schema for. Required if your Sanity project has more than one\n * workspace.\n */\n workspace?: string\n }\n\n /** Defines the hostname and port that the development server should run on. hostname defaults to localhost, and port to 3333. */\n server?: {\n hostname?: string\n port?: number\n }\n\n /** @deprecated Use deployment.appId */\n studioHost?: string\n\n /**\n * Configuration for Sanity typegen\n */\n typegen?: Partial<TypeGenConfig> & {\n /**\n * Enable typegen as part of sanity dev and sanity build.\n * When enabled, types are generated on startup and when files change.\n * Defaults to `false`\n */\n enabled?: boolean\n }\n\n /** Exposes the default Vite configuration for custom apps and the Studio so it can be changed and extended. */\n vite?: UserViteConfig\n}\n"],"names":[],"mappings":"AAYA;;CAEC,GACD,WA0IC"}
@@ -0,0 +1,89 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { cliConfigSchema } from './schemas.js';
4
+ /**
5
+ * The brand `unstable_defineApp` stamps on its result, registered in the global
6
+ * symbol registry. `unstable_defineApp` lives in `@sanity/cli-build`, which
7
+ * depends on cli-core — so cli-core can't import the brand without a cycle, and
8
+ * wouldn't pull the build package into startup just for this identity check
9
+ * anyway (cli-core is the hot path for every CLI command, most of which never
10
+ * touch workbench). `Symbol.for` keys the same global symbol `unstable_defineApp`
11
+ * stamps, so the check is identical; the only shared contract is the symbol
12
+ * string, which cli-core mirrors (see `APPLICATION_TYPES` below).
13
+ */ const WORKBENCH_APP_BRAND = Symbol.for('sanity.workbench.defineApp');
14
+ /**
15
+ * Whether `app` is a branded `unstable_defineApp(...)` result — the sole
16
+ * workbench opt-in. Narrows to the shared `app` config plus the workbench-only
17
+ * fields a branded result carries: its `name`, the resolved `applicationType`
18
+ * (settled by `parseWorkbenchCliConfig` on load, so callers read it instead of
19
+ * re-deriving studio-vs-app), dock panel `views`, and background worker
20
+ * `services`. The `type` literals match the `DefineAppInput` schema so
21
+ * `views`/`services` stay assignable to `DefineAppInput['views' | 'services']`
22
+ * downstream.
23
+ */ export function isWorkbenchApp(app) {
24
+ return typeof app === 'object' && app !== null && WORKBENCH_APP_BRAND in app;
25
+ }
26
+ const STUDIO_CONFIG_FILES = [
27
+ 'sanity.config.ts',
28
+ 'sanity.config.tsx',
29
+ 'sanity.config.js',
30
+ 'sanity.config.jsx',
31
+ 'sanity.config.mjs',
32
+ 'sanity.config.cjs'
33
+ ];
34
+ // Mirrors the `ApplicationType` enum in `@sanity/cli-build`'s `defineApp` schema.
35
+ // `unstable_defineApp` is a pure identity wrapper that doesn't validate its
36
+ // input, so the loader is the first place an explicit `applicationType` can be checked.
37
+ const APPLICATION_TYPES = [
38
+ 'coreApp',
39
+ 'studio',
40
+ 'canvas',
41
+ 'dashboard',
42
+ 'media-library'
43
+ ];
44
+ function isApplicationType(value) {
45
+ return typeof value === 'string' && APPLICATION_TYPES.includes(value);
46
+ }
47
+ /**
48
+ * Infer the application type for a workbench app when `unstable_defineApp`
49
+ * didn't set one: a project with a `sanity.config.*` is a studio, otherwise a
50
+ * core (SDK) app. An explicit `applicationType` always wins.
51
+ */ function detectApplicationType(projectDir) {
52
+ return STUDIO_CONFIG_FILES.some((file)=>existsSync(join(projectDir, file))) ? 'studio' : 'coreApp';
53
+ }
54
+ /**
55
+ * Parse a config whose `app` is a branded `unstable_defineApp(...)` result.
56
+ * The branded `app` bypasses the legacy `app` object schema (which would strip
57
+ * its identity fields and the brand symbol); every other field is still
58
+ * validated. The brand is preserved so downstream code relies on the
59
+ * `isWorkbenchApp` identity (above) instead of a flag.
60
+ *
61
+ * Resolves `applicationType` here — as early as possible — so studio-vs-app
62
+ * classification is settled once and read off the app everywhere else. The
63
+ * resolved value lands on a clone, never the caller's object, so re-parsing the
64
+ * same `app` for a different directory can't inherit a stale inference.
65
+ */ export function parseWorkbenchCliConfig(cliConfig, projectDir) {
66
+ const { app, ...rest } = cliConfig;
67
+ const { data, error, success } = cliConfigSchema.safeParse(rest);
68
+ if (!success) {
69
+ throw new Error(`Invalid CLI config: ${error.message}`, {
70
+ cause: error
71
+ });
72
+ }
73
+ const explicit = app.applicationType;
74
+ if (explicit !== undefined && !isApplicationType(explicit)) {
75
+ throw new Error(`Invalid \`applicationType\` "${explicit}" in \`unstable_defineApp\` — expected one of: ${APPLICATION_TYPES.join(', ')}`);
76
+ }
77
+ const applicationType = explicit ?? detectApplicationType(projectDir);
78
+ // Clone the branded app rather than mutating the caller's object. Copying own
79
+ // property descriptors carries over the non-enumerable `unstable_defineApp`
80
+ // brand, which a spread would drop.
81
+ const resolvedApp = Object.defineProperties({}, Object.getOwnPropertyDescriptors(app));
82
+ resolvedApp.applicationType = applicationType;
83
+ return {
84
+ ...data,
85
+ app: resolvedApp
86
+ };
87
+ }
88
+
89
+ //# sourceMappingURL=workbenchApp.js.map
@@ -0,0 +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/**\n * The brand `unstable_defineApp` stamps on its result, registered in the global\n * symbol registry. `unstable_defineApp` lives in `@sanity/cli-build`, which\n * depends on cli-core — so cli-core can't import the brand without a cycle, and\n * wouldn't pull the build package into startup just for this identity check\n * anyway (cli-core is the hot path for every CLI command, most of which never\n * touch workbench). `Symbol.for` keys the same global symbol `unstable_defineApp`\n * stamps, so the check is identical; the only shared contract is the symbol\n * string, which cli-core mirrors (see `APPLICATION_TYPES` below).\n */\nconst WORKBENCH_APP_BRAND = Symbol.for('sanity.workbench.defineApp')\n\n/**\n * Whether `app` is a branded `unstable_defineApp(...)` result — the sole\n * workbench opt-in. Narrows to the shared `app` config plus the workbench-only\n * fields a branded result carries: its `name`, the resolved `applicationType`\n * (settled by `parseWorkbenchCliConfig` on load, so callers read it instead of\n * re-deriving studio-vs-app), dock panel `views`, and background worker\n * `services`. The `type` literals match the `DefineAppInput` schema so\n * `views`/`services` stay assignable to `DefineAppInput['views' | 'services']`\n * downstream.\n */\nexport function isWorkbenchApp(app: CliConfig['app']): app is NonNullable<CliConfig['app']> & {\n applicationType?: ApplicationType\n name: string\n services?: {name: string; src: string; type: 'worker'}[]\n views?: {name: string; src: string; type: 'panel'}[]\n} {\n return typeof app === 'object' && app !== null && WORKBENCH_APP_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/cli-build`'s `defineApp` schema.\n// `unstable_defineApp` is a pure identity wrapper that doesn't validate its\n// input, so the loader is the first place an explicit `applicationType` can be checked.\nconst APPLICATION_TYPES = ['coreApp', 'studio', 'canvas', 'dashboard', 'media-library'] as const\n\n/** The resolved kind of a workbench app — `studio` or one of the SDK app types. */\nexport type ApplicationType = (typeof APPLICATION_TYPES)[number]\n\nfunction isApplicationType(value: unknown): value is ApplicationType {\n return typeof value === 'string' && (APPLICATION_TYPES as readonly string[]).includes(value)\n}\n\n/**\n * Infer the application type for a workbench app when `unstable_defineApp`\n * didn't set one: a project with a `sanity.config.*` is a studio, otherwise a\n * core (SDK) app. An explicit `applicationType` always wins.\n */\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 `unstable_defineApp(...)` result.\n * The branded `app` bypasses the legacy `app` object schema (which would strip\n * its identity fields and the brand symbol); every other field is still\n * validated. The brand is preserved so downstream code relies on the\n * `isWorkbenchApp` identity (above) instead of a flag.\n *\n * Resolves `applicationType` here — as early as possible — so studio-vs-app\n * classification is settled once and read off the app everywhere else. The\n * resolved value lands on a clone, never the caller's object, so re-parsing the\n * same `app` for a different directory can't inherit a stale inference.\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 const explicit = app.applicationType\n if (explicit !== undefined && !isApplicationType(explicit)) {\n throw new Error(\n `Invalid \\`applicationType\\` \"${explicit}\" in \\`unstable_defineApp\\` — expected one of: ${APPLICATION_TYPES.join(', ')}`,\n )\n }\n const applicationType = explicit ?? detectApplicationType(projectDir)\n\n // Clone the branded app rather than mutating the caller's object. Copying own\n // property descriptors carries over the non-enumerable `unstable_defineApp`\n // brand, which a spread would drop.\n const resolvedApp = Object.defineProperties({}, Object.getOwnPropertyDescriptors(app)) as Record<\n string,\n unknown\n >\n resolvedApp.applicationType = applicationType\n\n return {...data, app: resolvedApp} as CliConfig\n}\n"],"names":["existsSync","join","cliConfigSchema","WORKBENCH_APP_BRAND","Symbol","for","isWorkbenchApp","app","STUDIO_CONFIG_FILES","APPLICATION_TYPES","isApplicationType","value","includes","detectApplicationType","projectDir","some","file","parseWorkbenchCliConfig","cliConfig","rest","data","error","success","safeParse","Error","message","cause","explicit","applicationType","undefined","resolvedApp","Object","defineProperties","getOwnPropertyDescriptors"],"mappings":"AAAA,SAAQA,UAAU,QAAO,UAAS;AAClC,SAAQC,IAAI,QAAO,YAAW;AAE9B,SAAQC,eAAe,QAAO,eAAc;AAG5C;;;;;;;;;CASC,GACD,MAAMC,sBAAsBC,OAAOC,GAAG,CAAC;AAEvC;;;;;;;;;CASC,GACD,OAAO,SAASC,eAAeC,GAAqB;IAMlD,OAAO,OAAOA,QAAQ,YAAYA,QAAQ,QAAQJ,uBAAuBI;AAC3E;AAEA,MAAMC,sBAAsB;IAC1B;IACA;IACA;IACA;IACA;IACA;CACD;AAED,kFAAkF;AAClF,4EAA4E;AAC5E,wFAAwF;AACxF,MAAMC,oBAAoB;IAAC;IAAW;IAAU;IAAU;IAAa;CAAgB;AAKvF,SAASC,kBAAkBC,KAAc;IACvC,OAAO,OAAOA,UAAU,YAAY,AAACF,kBAAwCG,QAAQ,CAACD;AACxF;AAEA;;;;CAIC,GACD,SAASE,sBAAsBC,UAAkB;IAC/C,OAAON,oBAAoBO,IAAI,CAAC,CAACC,OAAShB,WAAWC,KAAKa,YAAYE,UAClE,WACA;AACN;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,wBAAwBC,SAAkB,EAAEJ,UAAkB;IAC5E,MAAM,EAACP,GAAG,EAAE,GAAGY,MAAK,GAAGD;IAGvB,MAAM,EAACE,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGpB,gBAAgBqB,SAAS,CAACJ;IACzD,IAAI,CAACG,SAAS;QACZ,MAAM,IAAIE,MAAM,CAAC,oBAAoB,EAAEH,MAAMI,OAAO,EAAE,EAAE;YAACC,OAAOL;QAAK;IACvE;IAEA,MAAMM,WAAWpB,IAAIqB,eAAe;IACpC,IAAID,aAAaE,aAAa,CAACnB,kBAAkBiB,WAAW;QAC1D,MAAM,IAAIH,MACR,CAAC,6BAA6B,EAAEG,SAAS,+CAA+C,EAAElB,kBAAkBR,IAAI,CAAC,OAAO;IAE5H;IACA,MAAM2B,kBAAkBD,YAAYd,sBAAsBC;IAE1D,8EAA8E;IAC9E,4EAA4E;IAC5E,oCAAoC;IACpC,MAAMgB,cAAcC,OAAOC,gBAAgB,CAAC,CAAC,GAAGD,OAAOE,yBAAyB,CAAC1B;IAIjFuB,YAAYF,eAAe,GAAGA;IAE9B,OAAO;QAAC,GAAGR,IAAI;QAAEb,KAAKuB;IAAW;AACnC"}
@@ -50,11 +50,12 @@ const debug = subdebug('worker:getStudioWorkspaces');
50
50
  name: config.name || 'default'
51
51
  }
52
52
  ];
53
+ const emptyAuth = {
54
+ state: of(getEmptyAuth())
55
+ };
53
56
  const unauthedWorkspaces = rawWorkspaces.map((workspace)=>({
54
57
  ...workspace,
55
- auth: {
56
- state: of(getEmptyAuth())
57
- }
58
+ auth: emptyAuth
58
59
  }));
59
60
  debug('Unauthed workspaces %o', unauthedWorkspaces);
60
61
  return firstValueFrom(resolveConfig(unauthedWorkspaces));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/config/studio/getStudioWorkspaces.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {dirname} from 'node:path'\nimport {isMainThread} from 'node:worker_threads'\n\nimport {firstValueFrom, of} from 'rxjs'\nimport {type Workspace} from 'sanity'\n\nimport {subdebug} from '../../debug.js'\nimport {doImport} from '../../util/doImport.js'\nimport {getEmptyAuth} from '../../util/getEmptyAuth.js'\nimport {resolveLocalPackage} from '../../util/resolveLocalPackage.js'\nimport {findStudioConfigPath} from '../util/findStudioConfigPath.js'\nimport {isStudioConfig} from './isStudioConfig.js'\n\nconst debug = subdebug('worker:getStudioWorkspaces')\n\n/**\n * Resolves the workspaces from the studio config.\n *\n * NOTE: This function should only be called from a worker thread.\n *\n * @param configPath - The path to the studio config\n * @returns The workspaces\n * @internal\n */\nexport async function getStudioWorkspaces(configPath: string): Promise<Workspace[]> {\n if (isMainThread) {\n throw new Error('getStudioWorkspaces should only be called from a worker thread')\n }\n const isDirectory = (await stat(configPath)).isDirectory()\n if (isDirectory) {\n configPath = await findStudioConfigPath(configPath)\n }\n debug('Finding studio config path %s', configPath)\n let config = await doImport(configPath)\n\n debug('Imported config %o', config)\n if (!isStudioConfig(config)) {\n if (!('default' in config) || !isStudioConfig(config.default)) {\n debug('Invalid studio config format in \"%s\"', configPath)\n throw new TypeError(`Invalid studio config format in \"${configPath}\"`)\n }\n\n config = config.default\n }\n\n const workDir = dirname(configPath)\n debug('Work dir %s', workDir)\n const {resolveConfig} = await resolveLocalPackage<typeof import('sanity')>('sanity', workDir)\n if (typeof resolveConfig !== 'function') {\n throw new TypeError('Expected `resolveConfig` from `sanity` to be a function')\n }\n\n // We will also want to stub out some configuration - we don't need to resolve the\n // users' logged in state, for instance - so let's disable the auth implementation.\n const rawWorkspaces = Array.isArray(config)\n ? config\n : [{...config, basePath: config.basePath || '/', name: config.name || 'default'}]\n\n const unauthedWorkspaces = rawWorkspaces.map((workspace) => ({\n ...workspace,\n auth: {state: of(getEmptyAuth())},\n }))\n\n debug('Unauthed workspaces %o', unauthedWorkspaces)\n\n return firstValueFrom(resolveConfig(unauthedWorkspaces))\n}\n"],"names":["stat","dirname","isMainThread","firstValueFrom","of","subdebug","doImport","getEmptyAuth","resolveLocalPackage","findStudioConfigPath","isStudioConfig","debug","getStudioWorkspaces","configPath","Error","isDirectory","config","default","TypeError","workDir","resolveConfig","rawWorkspaces","Array","isArray","basePath","name","unauthedWorkspaces","map","workspace","auth","state"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,OAAO,QAAO,YAAW;AACjC,SAAQC,YAAY,QAAO,sBAAqB;AAEhD,SAAQC,cAAc,EAAEC,EAAE,QAAO,OAAM;AAGvC,SAAQC,QAAQ,QAAO,iBAAgB;AACvC,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,YAAY,QAAO,6BAA4B;AAC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tC"}
1
+ {"version":3,"sources":["../../../src/config/studio/getStudioWorkspaces.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {dirname} from 'node:path'\nimport {isMainThread} from 'node:worker_threads'\n\nimport {firstValueFrom, of} from 'rxjs'\nimport {type Workspace} from 'sanity'\n\nimport {subdebug} from '../../debug.js'\nimport {doImport} from '../../util/doImport.js'\nimport {getEmptyAuth} from '../../util/getEmptyAuth.js'\nimport {resolveLocalPackage} from '../../util/resolveLocalPackage.js'\nimport {findStudioConfigPath} from '../util/findStudioConfigPath.js'\nimport {isStudioConfig} from './isStudioConfig.js'\n\nconst debug = subdebug('worker:getStudioWorkspaces')\n\n/**\n * Resolves the workspaces from the studio config.\n *\n * NOTE: This function should only be called from a worker thread.\n *\n * @param configPath - The path to the studio config\n * @returns The workspaces\n * @internal\n */\nexport async function getStudioWorkspaces(configPath: string): Promise<Workspace[]> {\n if (isMainThread) {\n throw new Error('getStudioWorkspaces should only be called from a worker thread')\n }\n const isDirectory = (await stat(configPath)).isDirectory()\n if (isDirectory) {\n configPath = await findStudioConfigPath(configPath)\n }\n debug('Finding studio config path %s', configPath)\n let config = await doImport(configPath)\n\n debug('Imported config %o', config)\n if (!isStudioConfig(config)) {\n if (!('default' in config) || !isStudioConfig(config.default)) {\n debug('Invalid studio config format in \"%s\"', configPath)\n throw new TypeError(`Invalid studio config format in \"${configPath}\"`)\n }\n\n config = config.default\n }\n\n const workDir = dirname(configPath)\n debug('Work dir %s', workDir)\n const {resolveConfig} = await resolveLocalPackage<typeof import('sanity')>('sanity', workDir)\n if (typeof resolveConfig !== 'function') {\n throw new TypeError('Expected `resolveConfig` from `sanity` to be a function')\n }\n\n // We will also want to stub out some configuration - we don't need to resolve the\n // users' logged in state, for instance - so let's disable the auth implementation.\n const rawWorkspaces = Array.isArray(config)\n ? config\n : [{...config, basePath: config.basePath || '/', name: config.name || 'default'}]\n\n const emptyAuth = {state: of(getEmptyAuth())}\n\n const unauthedWorkspaces = rawWorkspaces.map((workspace) => ({\n ...workspace,\n auth: emptyAuth,\n }))\n\n debug('Unauthed workspaces %o', unauthedWorkspaces)\n\n return firstValueFrom(resolveConfig(unauthedWorkspaces))\n}\n"],"names":["stat","dirname","isMainThread","firstValueFrom","of","subdebug","doImport","getEmptyAuth","resolveLocalPackage","findStudioConfigPath","isStudioConfig","debug","getStudioWorkspaces","configPath","Error","isDirectory","config","default","TypeError","workDir","resolveConfig","rawWorkspaces","Array","isArray","basePath","name","emptyAuth","state","unauthedWorkspaces","map","workspace","auth"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,OAAO,QAAO,YAAW;AACjC,SAAQC,YAAY,QAAO,sBAAqB;AAEhD,SAAQC,cAAc,EAAEC,EAAE,QAAO,OAAM;AAGvC,SAAQC,QAAQ,QAAO,iBAAgB;AACvC,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,YAAY,QAAO,6BAA4B;AACvD,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,oBAAoB,QAAO,kCAAiC;AACpE,SAAQC,cAAc,QAAO,sBAAqB;AAElD,MAAMC,QAAQN,SAAS;AAEvB;;;;;;;;CAQC,GACD,OAAO,eAAeO,oBAAoBC,UAAkB;IAC1D,IAAIX,cAAc;QAChB,MAAM,IAAIY,MAAM;IAClB;IACA,MAAMC,cAAc,AAAC,CAAA,MAAMf,KAAKa,WAAU,EAAGE,WAAW;IACxD,IAAIA,aAAa;QACfF,aAAa,MAAMJ,qBAAqBI;IAC1C;IACAF,MAAM,iCAAiCE;IACvC,IAAIG,SAAS,MAAMV,SAASO;IAE5BF,MAAM,sBAAsBK;IAC5B,IAAI,CAACN,eAAeM,SAAS;QAC3B,IAAI,CAAE,CAAA,aAAaA,MAAK,KAAM,CAACN,eAAeM,OAAOC,OAAO,GAAG;YAC7DN,MAAM,wCAAwCE;YAC9C,MAAM,IAAIK,UAAU,CAAC,iCAAiC,EAAEL,WAAW,CAAC,CAAC;QACvE;QAEAG,SAASA,OAAOC,OAAO;IACzB;IAEA,MAAME,UAAUlB,QAAQY;IACxBF,MAAM,eAAeQ;IACrB,MAAM,EAACC,aAAa,EAAC,GAAG,MAAMZ,oBAA6C,UAAUW;IACrF,IAAI,OAAOC,kBAAkB,YAAY;QACvC,MAAM,IAAIF,UAAU;IACtB;IAEA,kFAAkF;IAClF,mFAAmF;IACnF,MAAMG,gBAAgBC,MAAMC,OAAO,CAACP,UAChCA,SACA;QAAC;YAAC,GAAGA,MAAM;YAAEQ,UAAUR,OAAOQ,QAAQ,IAAI;YAAKC,MAAMT,OAAOS,IAAI,IAAI;QAAS;KAAE;IAEnF,MAAMC,YAAY;QAACC,OAAOvB,GAAGG;IAAe;IAE5C,MAAMqB,qBAAqBP,cAAcQ,GAAG,CAAC,CAACC,YAAe,CAAA;YAC3D,GAAGA,SAAS;YACZC,MAAML;QACR,CAAA;IAEAf,MAAM,0BAA0BiB;IAEhC,OAAOzB,eAAeiB,cAAcQ;AACtC"}
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod/mini';
2
+ /**
3
+ * Studio/app manifest schemas. They live in cli-core because more than one
4
+ * package validates manifests: the CLI extracts and writes them, and the
5
+ * workbench dev-server registry stores and rebroadcasts them. Keeping the
6
+ * contract here lets both validate against the same schema without depending on
7
+ * each other.
8
+ */ /**
9
+ * Core-app application manifest. Mirrors the workbench's
10
+ * `CoreAppUserApplicationManifest` schema. Strictly validated via zod since the
11
+ * CLI produces the payload in full.
12
+ */ export const coreAppManifestSchema = z.object({
13
+ group: z.optional(z.string()),
14
+ icon: z.optional(z.string()),
15
+ priority: z.optional(z.number()),
16
+ title: z.optional(z.string()),
17
+ version: z.string()
18
+ });
19
+ /**
20
+ * Studio application manifest (serialized `create-manifest.json`). Kept loose so
21
+ * the CLI isn't coupled to the workbench's evolving client-side schema — the
22
+ * workbench consumer is authoritative on the inner shape. See its
23
+ * `ClientManifest` for the fields clients expect.
24
+ */ export const studioManifestSchema = z.record(z.string(), z.unknown());
25
+
26
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +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.string()),\n icon: z.optional(z.string()),\n priority: z.optional(z.number()),\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","group","optional","string","icon","priority","number","title","version","studioManifestSchema","record","unknown"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B;;;;;;CAMC,GAED;;;;CAIC,GACD,OAAO,MAAMC,wBAAwBD,EAAEE,MAAM,CAAC;IAC5CC,OAAOH,EAAEI,QAAQ,CAACJ,EAAEK,MAAM;IAC1BC,MAAMN,EAAEI,QAAQ,CAACJ,EAAEK,MAAM;IACzBE,UAAUP,EAAEI,QAAQ,CAACJ,EAAEQ,MAAM;IAC7BC,OAAOT,EAAEI,QAAQ,CAACJ,EAAEK,MAAM;IAC1BK,SAASV,EAAEK,MAAM;AACnB,GAAE;AAIF;;;;;CAKC,GACD,OAAO,MAAMM,uBAAuBX,EAAEY,MAAM,CAACZ,EAAEK,MAAM,IAAIL,EAAEa,OAAO,IAAG"}
@@ -1,8 +1,8 @@
1
1
  import { mkdirSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
2
  import { dirname, join as joinPath } from 'node:path';
4
3
  import { z } from 'zod/mini';
5
4
  import { debug } from '../debug.js';
5
+ import { getSanityConfigDir } from '../util/getSanityConfigDir.js';
6
6
  import { readJsonFileSync } from '../util/readJsonFileSync.js';
7
7
  import { writeJsonFileSync } from '../util/writeJsonFileSync.js';
8
8
  import { clearCliTokenCache } from './cliTokenCache.js';
@@ -136,9 +136,7 @@ const cliUserConfigSchema = {
136
136
  * @returns The path to the CLI configuration file.
137
137
  * @internal
138
138
  */ function getCliUserConfigPath() {
139
- const sanityEnvSuffix = process.env.SANITY_INTERNAL_ENV === 'staging' ? '-staging' : '';
140
- const cliConfigPath = process.env.SANITY_CLI_CONFIG_PATH || joinPath(homedir(), '.config', `sanity${sanityEnvSuffix}`, 'config.json');
141
- return cliConfigPath;
139
+ return process.env.SANITY_CLI_CONFIG_PATH || joinPath(getSanityConfigDir(), 'config.json');
142
140
  }
143
141
 
144
142
  //# sourceMappingURL=cliUserConfig.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/services/cliUserConfig.ts"],"sourcesContent":["import {mkdirSync} from 'node:fs'\nimport {homedir} from 'node:os'\nimport {dirname, join as joinPath} from 'node:path'\n\nimport {z} from 'zod/mini'\n\nimport {debug} from '../debug.js'\nimport {readJsonFileSync} from '../util/readJsonFileSync.js'\nimport {writeJsonFileSync} from '../util/writeJsonFileSync.js'\nimport {clearCliTokenCache} from './cliTokenCache.js'\n\nconst cliUserConfigSchema = {\n authToken: z.optional(z.string()),\n}\n\n/**\n * Set the config value for the given property.\n * Validates that the passed value adheres to the defined CLI config schema.\n *\n * @param prop - The property to set the value for\n * @param value - The value to set\n * @internal\n */\nexport function setCliUserConfig(prop: 'authToken', value: string | undefined): void {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(value)\n if (!result.success) {\n const message = result.error.issues\n .map(({message, path}) => `[${path.join('.')}] ${message}`)\n .join('\\n')\n\n throw new Error(`Invalid value for config property \"${prop}\": ${message}`)\n }\n\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n\n // When value is undefined, explicitly delete the key rather than relying\n // on JSON.stringify silently dropping undefined values.\n if (value === undefined) {\n const {[prop]: _, ...rest} = config\n writeJsonFileSync(configPath, rest, {pretty: true})\n } else {\n writeJsonFileSync(configPath, {...config, [prop]: value}, {pretty: true})\n }\n\n // Invalidate the in-process token cache so subsequent getCliToken() calls\n // pick up the new value from disk.\n clearCliTokenCache()\n}\n\n/**\n * Get the config value for the given property\n *\n * @param prop - The property to get the value for\n * @returns The value of the given property\n * @internal\n */\nexport function getCliUserConfig(prop: 'authToken'): string | undefined {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(config[prop])\n if (!result.success) {\n debug('Ignoring invalid stored value for \"%s\", returning undefined', prop)\n return undefined\n }\n\n return result.data\n}\n\n/**\n * A raw key-value store for CLI user configuration.\n * Unlike the typed `getCliUserConfig`/`setCliUserConfig`, this operates on\n * arbitrary keys without schema validation.\n *\n * @public\n */\nexport interface ConfigStore {\n /** Remove a key from the config file. */\n delete: (key: string) => void\n /** Read a value by key. Returns `undefined` if the key does not exist. */\n get: (key: string) => unknown\n /** Write a value by key, merging it into the existing config. */\n set: (key: string, value: unknown) => void\n}\n\n/**\n * Get a key-value store backed by the CLI user configuration file\n * (`~/.config/sanity/config.json`).\n *\n * Each call to `get`, `set`, or `delete` performs a full synchronous\n * read-modify-write cycle. This is intentional: sync I/O prevents\n * intra-process race conditions that occurred with the previous async\n * (configstore-backed) implementation.\n *\n * Note: there is no file-level locking, so concurrent writes from\n * separate CLI processes could still conflict. In practice this is\n * unlikely since CLI config writes are rare and user-initiated.\n *\n * @returns A {@link ConfigStore} for the CLI config file\n * @public\n */\nexport function getUserConfig(): ConfigStore {\n return {\n get(key: string): unknown {\n const config = readConfig()\n return config[key]\n },\n\n set(key: string, value: unknown): void {\n const config = readConfig()\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n writeJsonFileSync(configPath, {...config, [key]: value}, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n\n // No mkdirSync needed: if readConfig() succeeded the directory already exists.\n delete(key: string): void {\n const config = readConfig()\n if (!(key in config)) return\n const {[key]: _, ...rest} = config\n writeJsonFileSync(getCliUserConfigPath(), rest, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n }\n}\n\n/**\n * Read the whole configuration from file system. If the file does not exist,\n * is corrupt, or otherwise unreadable, an empty object is returned. This is\n * intentional: the config only holds recoverable data (auth tokens, telemetry\n * consent) so silently resetting is preferable to blocking the user.\n *\n * @returns The whole CLI configuration.\n * @internal\n */\nfunction readConfig(): Record<string, unknown> {\n try {\n const config = readJsonFileSync(getCliUserConfigPath())\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error('Invalid config file - expected an object')\n }\n return config\n } catch (err: unknown) {\n debug('Failed to read CLI config file: %s', err instanceof Error ? err.message : `${err}`)\n return {}\n }\n}\n\n/**\n * Get the file system location for the CLI user configuration file.\n * Takes into account the active environment (staging vs production).\n * The file is located in the user's home directory under the `.config` directory.\n *\n * @returns The path to the CLI configuration file.\n * @internal\n */\nfunction getCliUserConfigPath() {\n const sanityEnvSuffix = process.env.SANITY_INTERNAL_ENV === 'staging' ? '-staging' : ''\n const cliConfigPath =\n process.env.SANITY_CLI_CONFIG_PATH ||\n joinPath(homedir(), '.config', `sanity${sanityEnvSuffix}`, 'config.json')\n\n return cliConfigPath\n}\n"],"names":["mkdirSync","homedir","dirname","join","joinPath","z","debug","readJsonFileSync","writeJsonFileSync","clearCliTokenCache","cliUserConfigSchema","authToken","optional","string","setCliUserConfig","prop","value","config","readConfig","result","safeParse","success","message","error","issues","map","path","Error","configPath","getCliUserConfigPath","recursive","undefined","_","rest","pretty","getCliUserConfig","data","getUserConfig","get","key","set","delete","Array","isArray","err","sanityEnvSu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KAAc;QACrBtC,MAAM,sCAAsCsC,eAAejB,QAAQiB,IAAItB,OAAO,GAAG,GAAGsB,KAAK;QACzF,OAAO,CAAC;IACV;AACF;AAEA;;;;;;;CAOC,GACD,SAASf;IACP,MAAMgB,kBAAkBC,QAAQC,GAAG,CAACC,mBAAmB,KAAK,YAAY,aAAa;IACrF,MAAMC,gBACJH,QAAQC,GAAG,CAACG,sBAAsB,IAClC9C,SAASH,WAAW,WAAW,CAAC,MAAM,EAAE4C,iBAAiB,EAAE;IAE7D,OAAOI;AACT"}
1
+ {"version":3,"sources":["../../src/services/cliUserConfig.ts"],"sourcesContent":["import {mkdirSync} from 'node:fs'\nimport {dirname, join as joinPath} from 'node:path'\n\nimport {z} from 'zod/mini'\n\nimport {debug} from '../debug.js'\nimport {getSanityConfigDir} from '../util/getSanityConfigDir.js'\nimport {readJsonFileSync} from '../util/readJsonFileSync.js'\nimport {writeJsonFileSync} from '../util/writeJsonFileSync.js'\nimport {clearCliTokenCache} from './cliTokenCache.js'\n\nconst cliUserConfigSchema = {\n authToken: z.optional(z.string()),\n}\n\n/**\n * Set the config value for the given property.\n * Validates that the passed value adheres to the defined CLI config schema.\n *\n * @param prop - The property to set the value for\n * @param value - The value to set\n * @internal\n */\nexport function setCliUserConfig(prop: 'authToken', value: string | undefined): void {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(value)\n if (!result.success) {\n const message = result.error.issues\n .map(({message, path}) => `[${path.join('.')}] ${message}`)\n .join('\\n')\n\n throw new Error(`Invalid value for config property \"${prop}\": ${message}`)\n }\n\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n\n // When value is undefined, explicitly delete the key rather than relying\n // on JSON.stringify silently dropping undefined values.\n if (value === undefined) {\n const {[prop]: _, ...rest} = config\n writeJsonFileSync(configPath, rest, {pretty: true})\n } else {\n writeJsonFileSync(configPath, {...config, [prop]: value}, {pretty: true})\n }\n\n // Invalidate the in-process token cache so subsequent getCliToken() calls\n // pick up the new value from disk.\n clearCliTokenCache()\n}\n\n/**\n * Get the config value for the given property\n *\n * @param prop - The property to get the value for\n * @returns The value of the given property\n * @internal\n */\nexport function getCliUserConfig(prop: 'authToken'): string | undefined {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(config[prop])\n if (!result.success) {\n debug('Ignoring invalid stored value for \"%s\", returning undefined', prop)\n return undefined\n }\n\n return result.data\n}\n\n/**\n * A raw key-value store for CLI user configuration.\n * Unlike the typed `getCliUserConfig`/`setCliUserConfig`, this operates on\n * arbitrary keys without schema validation.\n *\n * @public\n */\nexport interface ConfigStore {\n /** Remove a key from the config file. */\n delete: (key: string) => void\n /** Read a value by key. Returns `undefined` if the key does not exist. */\n get: (key: string) => unknown\n /** Write a value by key, merging it into the existing config. */\n set: (key: string, value: unknown) => void\n}\n\n/**\n * Get a key-value store backed by the CLI user configuration file\n * (`~/.config/sanity/config.json`).\n *\n * Each call to `get`, `set`, or `delete` performs a full synchronous\n * read-modify-write cycle. This is intentional: sync I/O prevents\n * intra-process race conditions that occurred with the previous async\n * (configstore-backed) implementation.\n *\n * Note: there is no file-level locking, so concurrent writes from\n * separate CLI processes could still conflict. In practice this is\n * unlikely since CLI config writes are rare and user-initiated.\n *\n * @returns A {@link ConfigStore} for the CLI config file\n * @public\n */\nexport function getUserConfig(): ConfigStore {\n return {\n get(key: string): unknown {\n const config = readConfig()\n return config[key]\n },\n\n set(key: string, value: unknown): void {\n const config = readConfig()\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n writeJsonFileSync(configPath, {...config, [key]: value}, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n\n // No mkdirSync needed: if readConfig() succeeded the directory already exists.\n delete(key: string): void {\n const config = readConfig()\n if (!(key in config)) return\n const {[key]: _, ...rest} = config\n writeJsonFileSync(getCliUserConfigPath(), rest, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n }\n}\n\n/**\n * Read the whole configuration from file system. If the file does not exist,\n * is corrupt, or otherwise unreadable, an empty object is returned. This is\n * intentional: the config only holds recoverable data (auth tokens, telemetry\n * consent) so silently resetting is preferable to blocking the user.\n *\n * @returns The whole CLI configuration.\n * @internal\n */\nfunction readConfig(): Record<string, unknown> {\n try {\n const config = readJsonFileSync(getCliUserConfigPath())\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error('Invalid config file - expected an object')\n }\n return config\n } catch (err: unknown) {\n debug('Failed to read CLI config file: %s', err instanceof Error ? err.message : `${err}`)\n return {}\n }\n}\n\n/**\n * Get the file system location for the CLI user configuration file.\n * Takes into account the active environment (staging vs production).\n * The file is located in the user's home directory under the `.config` directory.\n *\n * @returns The path to the CLI configuration file.\n * @internal\n */\nfunction getCliUserConfigPath() {\n return process.env.SANITY_CLI_CONFIG_PATH || joinPath(getSanityConfigDir(), 'config.json')\n}\n"],"names":["mkdirSync","dirname","join","joinPath","z","debug","getSanityConfigDir","readJsonFileSync","writeJsonFileSync","clearCliTokenCache","cliUserConfigSchema","authToken","optional","string","setCliUserConfig","prop","value","config","readConfig","result","safeParse","success","message","error","issues","map","path","Error","configPath","getCliUserConfigPath","recursive","undefined","_","rest","pretty","getCliUserConfig","data","getUserConfig","get","key","set","delete","Array","isArray","err","process","env","SANITY_CLI_CONFIG_PATH"],"mappings":"AAAA,SAAQA,SAAS,QAAO,UAAS;AACjC,SAAQC,OAAO,EAAEC,QAAQC,QAAQ,QAAO,YAAW;AAEnD,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,kBAAkB,QAAO,gCAA+B;AAChE,SAAQC,gBAAgB,QAAO,8BAA6B;AAC5D,SAAQC,iBAAiB,QAAO,+BAA8B;AAC9D,SAAQC,kBAAkB,QAAO,qBAAoB;AAErD,MAAMC,sBAAsB;IAC1BC,WAAWP,EAAEQ,QAAQ,CAACR,EAAES,MAAM;AAChC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,iBAA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AC,KAAID,GAAW,EAAEvB,KAAc;YAC7B,MAAMC,SAASC;YACf,MAAMU,aAAaC;YACnB7B,UAAUC,QAAQ2B,aAAa;gBAACE,WAAW;YAAI;YAC/CtB,kBAAkBoB,YAAY;gBAAC,GAAGX,MAAM;gBAAE,CAACsB,IAAI,EAAEvB;YAAK,GAAG;gBAACkB,QAAQ;YAAI;YACtE,IAAIK,QAAQ,aAAa9B;QAC3B;QAEA,+EAA+E;QAC/EgC,QAAOF,GAAW;YAChB,MAAMtB,SAASC;YACf,IAAI,CAAEqB,CAAAA,OAAOtB,MAAK,GAAI;YACtB,MAAM,EAAC,CAACsB,IAAI,EAAEP,CAAC,EAAE,GAAGC,MAAK,GAAGhB;YAC5BT,kBAAkBqB,wBAAwBI,MAAM;gBAACC,QAAQ;YAAI;YAC7D,IAAIK,QAAQ,aAAa9B;QAC3B;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,SAASS;IACP,IAAI;QACF,MAAMD,SAASV,iBAAiBsB;QAChC,IAAI,CAACZ,UAAU,OAAOA,WAAW,YAAYyB,MAAMC,OAAO,CAAC1B,SAAS;YAClE,MAAM,IAAIU,MAAM;QAClB;QACA,OAAOV;IACT,EAAE,OAAO2B,KAAc;QACrBvC,MAAM,sCAAsCuC,eAAejB,QAAQiB,IAAItB,OAAO,GAAG,GAAGsB,KAAK;QACzF,OAAO,CAAC;IACV;AACF;AAEA;;;;;;;CAOC,GACD,SAASf;IACP,OAAOgB,QAAQC,GAAG,CAACC,sBAAsB,IAAI5C,SAASG,sBAAsB;AAC9E"}
@@ -13,13 +13,31 @@ import { getBrowserStubs } from './stubs.js';
13
13
  return ()=>{
14
14
  /* intentional noop - already mocked */ };
15
15
  }
16
- // Inject browser stubs into global scope
16
+ // Inject browser stubs into global scope. `getBrowserStubs()` has already
17
+ // decided what to inject — including a small set of keys (e.g.
18
+ // `localStorage`/`sessionStorage`/`Storage`) that we want to take from JSDOM
19
+ // even if Node provides them, so realm identity stays consistent.
17
20
  const stubs = getBrowserStubs();
18
21
  const mockedGlobalThis = globalThis;
19
22
  const stubbedKeys = [];
23
+ const originalDescriptors = new Map();
20
24
  for (const key of Object.keys(stubs)){
21
- if (key in mockedGlobalThis) continue;
22
- mockedGlobalThis[key] = stubs[key];
25
+ // Snapshot via descriptor to avoid triggering getters (e.g. Node 26's
26
+ // `localStorage` getter logs an ExperimentalWarning on read).
27
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
28
+ if (descriptor) {
29
+ originalDescriptors.set(key, descriptor);
30
+ // Assignment would throw for getter-only accessors (e.g. Node 26's
31
+ // `localStorage`/`sessionStorage`), so replace the property outright.
32
+ Object.defineProperty(globalThis, key, {
33
+ configurable: true,
34
+ enumerable: descriptor.enumerable,
35
+ value: stubs[key],
36
+ writable: true
37
+ });
38
+ } else {
39
+ mockedGlobalThis[key] = stubs[key];
40
+ }
23
41
  stubbedKeys.push(key);
24
42
  }
25
43
  // Add marker to window to detect double-mocking
@@ -34,7 +52,12 @@ import { getBrowserStubs } from './stubs.js';
34
52
  delete globalThis.window.__mockedBySanity;
35
53
  }
36
54
  for (const key of stubbedKeys){
37
- delete mockedGlobalThis[key];
55
+ const descriptor = originalDescriptors.get(key);
56
+ if (descriptor) {
57
+ Object.defineProperty(globalThis, key, descriptor);
58
+ } else {
59
+ delete mockedGlobalThis[key];
60
+ }
38
61
  }
39
62
  };
40
63
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/util/environment/setupBrowserStubs.ts"],"sourcesContent":["import {getBrowserStubs} from './stubs.js'\n\n/**\n * Sets up browser globals (window, document, etc.) in the global scope.\n *\n * This is used by both mockBrowserEnvironment (for child processes) and\n * studioWorkerLoader (for worker threads) to provide a browser-like environment.\n *\n * @returns A cleanup function that removes the injected globals\n * @internal\n */\nexport async function setupBrowserStubs(): Promise<() => void> {\n // Guard against double-registering\n if (globalThis.window && '__mockedBySanity' in globalThis.window) {\n return () => {\n /* intentional noop - already mocked */\n }\n }\n\n // Inject browser stubs into global scope\n const stubs = getBrowserStubs()\n const mockedGlobalThis: Record<string, unknown> = globalThis\n const stubbedKeys: string[] = []\n\n for (const key of Object.keys(stubs)) {\n if (key in mockedGlobalThis) continue\n mockedGlobalThis[key] = stubs[key]\n stubbedKeys.push(key)\n }\n\n // Add marker to window to detect double-mocking\n if (globalThis.window) {\n ;(globalThis.window as unknown as Record<string, unknown>).__mockedBySanity = true\n }\n\n // Return cleanup function\n return () => {\n // Remove marker before deleting window\n if (globalThis.window) {\n delete (globalThis.window as unknown as Record<string, unknown>).__mockedBySanity\n }\n\n for (const key of stubbedKeys) {\n delete mockedGlobalThis[key]\n }\n }\n}\n"],"names":["getBrowserStubs","setupBrowserStubs","globalThis","window","stubs","mockedGlobalThis","stubbedKeys","key","Object","keys","push","__mockedBySanity"],"mappings":"AAAA,SAAQA,eAAe,QAAO,aAAY;AAE1C;;;;;;;;CAQC,GACD,OAAO,eAAeC;IACpB,mCAAmC;IACnC,IAAIC,WAAWC,MAAM,IAAI,sBAAsBD,WAAWC,MAAM,EAAE;QAChE,OAAO;QACL,qCAAqC,GACvC;IACF;IAEA,yCAAyC;IACzC,MAAMC,QAAQJ;IACd,MAAMK,mBAA4CH;IAClD,MAAMI,cAAwB,EAAE;IAEhC,KAAK,MAAMC,OAAOC,OAAOC,IAAI,CAACL,OAAQ;QACpC,IAAIG,OAAOF,kBAAkB;QAC7BA,gBAAgB,CAACE,IAAI,GAAGH,KAAK,CAACG,IAAI;QAClCD,YAAYI,IAAI,CAACH;IACnB;IAEA,gDAAgD;IAChD,IAAIL,WAAWC,MAAM,EAAE;;QACnBD,WAAWC,MAAM,CAAwCQ,gBAAgB,GAAG;IAChF;IAEA,0BAA0B;IAC1B,OAAO;QACL,uCAAuC;QACvC,IAAIT,WAAWC,MAAM,EAAE;YACrB,OAAO,AAACD,WAAWC,MAAM,CAAwCQ,gBAAgB;QACnF;QAEA,KAAK,MAAMJ,OAAOD,YAAa;YAC7B,OAAOD,gBAAgB,CAACE,IAAI;QAC9B;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/util/environment/setupBrowserStubs.ts"],"sourcesContent":["import {getBrowserStubs} from './stubs.js'\n\n/**\n * Sets up browser globals (window, document, etc.) in the global scope.\n *\n * This is used by both mockBrowserEnvironment (for child processes) and\n * studioWorkerLoader (for worker threads) to provide a browser-like environment.\n *\n * @returns A cleanup function that removes the injected globals\n * @internal\n */\nexport async function setupBrowserStubs(): Promise<() => void> {\n // Guard against double-registering\n if (globalThis.window && '__mockedBySanity' in globalThis.window) {\n return () => {\n /* intentional noop - already mocked */\n }\n }\n\n // Inject browser stubs into global scope. `getBrowserStubs()` has already\n // decided what to inject — including a small set of keys (e.g.\n // `localStorage`/`sessionStorage`/`Storage`) that we want to take from JSDOM\n // even if Node provides them, so realm identity stays consistent.\n const stubs = getBrowserStubs()\n const mockedGlobalThis: Record<string, unknown> = globalThis\n const stubbedKeys: string[] = []\n const originalDescriptors = new Map<string, PropertyDescriptor>()\n\n for (const key of Object.keys(stubs)) {\n // Snapshot via descriptor to avoid triggering getters (e.g. Node 26's\n // `localStorage` getter logs an ExperimentalWarning on read).\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, key)\n if (descriptor) {\n originalDescriptors.set(key, descriptor)\n // Assignment would throw for getter-only accessors (e.g. Node 26's\n // `localStorage`/`sessionStorage`), so replace the property outright.\n Object.defineProperty(globalThis, key, {\n configurable: true,\n enumerable: descriptor.enumerable,\n value: stubs[key],\n writable: true,\n })\n } else {\n mockedGlobalThis[key] = stubs[key]\n }\n stubbedKeys.push(key)\n }\n\n // Add marker to window to detect double-mocking\n if (globalThis.window) {\n ;(globalThis.window as unknown as Record<string, unknown>).__mockedBySanity = true\n }\n\n // Return cleanup function\n return () => {\n // Remove marker before deleting window\n if (globalThis.window) {\n delete (globalThis.window as unknown as Record<string, unknown>).__mockedBySanity\n }\n\n for (const key of stubbedKeys) {\n const descriptor = originalDescriptors.get(key)\n if (descriptor) {\n Object.defineProperty(globalThis, key, descriptor)\n } else {\n delete mockedGlobalThis[key]\n }\n }\n }\n}\n"],"names":["getBrowserStubs","setupBrowserStubs","globalThis","window","stubs","mockedGlobalThis","stubbedKeys","originalDescriptors","Map","key","Object","keys","descriptor","getOwnPropertyDescriptor","set","defineProperty","configurable","enumerable","value","writable","push","__mockedBySanity","get"],"mappings":"AAAA,SAAQA,eAAe,QAAO,aAAY;AAE1C;;;;;;;;CAQC,GACD,OAAO,eAAeC;IACpB,mCAAmC;IACnC,IAAIC,WAAWC,MAAM,IAAI,sBAAsBD,WAAWC,MAAM,EAAE;QAChE,OAAO;QACL,qCAAqC,GACvC;IACF;IAEA,0EAA0E;IAC1E,+DAA+D;IAC/D,6EAA6E;IAC7E,kEAAkE;IAClE,MAAMC,QAAQJ;IACd,MAAMK,mBAA4CH;IAClD,MAAMI,cAAwB,EAAE;IAChC,MAAMC,sBAAsB,IAAIC;IAEhC,KAAK,MAAMC,OAAOC,OAAOC,IAAI,CAACP,OAAQ;QACpC,sEAAsE;QACtE,8DAA8D;QAC9D,MAAMQ,aAAaF,OAAOG,wBAAwB,CAACX,YAAYO;QAC/D,IAAIG,YAAY;YACdL,oBAAoBO,GAAG,CAACL,KAAKG;YAC7B,mEAAmE;YACnE,sEAAsE;YACtEF,OAAOK,cAAc,CAACb,YAAYO,KAAK;gBACrCO,cAAc;gBACdC,YAAYL,WAAWK,UAAU;gBACjCC,OAAOd,KAAK,CAACK,IAAI;gBACjBU,UAAU;YACZ;QACF,OAAO;YACLd,gBAAgB,CAACI,IAAI,GAAGL,KAAK,CAACK,IAAI;QACpC;QACAH,YAAYc,IAAI,CAACX;IACnB;IAEA,gDAAgD;IAChD,IAAIP,WAAWC,MAAM,EAAE;;QACnBD,WAAWC,MAAM,CAAwCkB,gBAAgB,GAAG;IAChF;IAEA,0BAA0B;IAC1B,OAAO;QACL,uCAAuC;QACvC,IAAInB,WAAWC,MAAM,EAAE;YACrB,OAAO,AAACD,WAAWC,MAAM,CAAwCkB,gBAAgB;QACnF;QAEA,KAAK,MAAMZ,OAAOH,YAAa;YAC7B,MAAMM,aAAaL,oBAAoBe,GAAG,CAACb;YAC3C,IAAIG,YAAY;gBACdF,OAAOK,cAAc,CAACb,YAAYO,KAAKG;YACzC,OAAO;gBACL,OAAOP,gBAAgB,CAACI,IAAI;YAC9B;QACF;IACF;AACF"}
@@ -105,6 +105,20 @@ function isAbortSignalLike(value) {
105
105
  }
106
106
  return dom;
107
107
  }
108
+ /**
109
+ * Web globals that Node.js may provide but whose JSDOM implementations we
110
+ * always prefer, so that behavior is consistent across Node versions.
111
+ *
112
+ * Node 26+ exposes `localStorage`/`sessionStorage`/`Storage` as built-in globals,
113
+ * but `localStorage` is `undefined` unless started with `--localstorage-file`, and
114
+ * the `Storage` constructor identity differs from JSDOM's. Mixing realms would
115
+ * break code that does `localStorage instanceof Storage`, so we override all
116
+ * three together.
117
+ */ const ALWAYS_INCLUDE_FROM_JSDOM = new Set([
118
+ 'localStorage',
119
+ 'sessionStorage',
120
+ 'Storage'
121
+ ]);
108
122
  /**
109
123
  * Collects all browser globals from the JSDOM window that should be injected
110
124
  * into the Node.js global scope to emulate a browser environment.
@@ -125,8 +139,9 @@ function isAbortSignalLike(value) {
125
139
  if (key.startsWith('_')) continue;
126
140
  // Skip numeric indices (e.g. '0' for window[0])
127
141
  if (/^\d+$/.test(key)) continue;
128
- // Skip properties that Node.js already provides to avoid conflicts
129
- if (nodeGlobals.has(key)) continue;
142
+ // Skip properties that Node.js already provides to avoid conflicts, unless
143
+ // we explicitly want to override Node's version with JSDOM's
144
+ if (nodeGlobals.has(key) && !ALWAYS_INCLUDE_FROM_JSDOM.has(key)) continue;
130
145
  stubs[key] = dom.window[key];
131
146
  }
132
147
  return stubs;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/util/environment/stubs.ts"],"sourcesContent":["import {JSDOM} from 'jsdom'\n\nconst html = `<!doctype html>\n<html>\n <head><meta charset=\"utf-8\"></head>\n <body></body>\n</html>`\n\ninterface AbortSignalLike {\n aborted: boolean\n addEventListener(type: 'abort', listener: () => void, options?: {once?: boolean}): void\n removeEventListener(type: 'abort', listener: () => void): void\n}\n\ntype EventListenerOptionsWithSignal = AddEventListenerOptions & {signal?: unknown}\n\nfunction isAbortSignalLike(value: unknown): value is AbortSignalLike {\n return (\n !!value &&\n typeof value === 'object' &&\n 'aborted' in value &&\n typeof (value as AbortSignalLike).aborted === 'boolean' &&\n 'addEventListener' in value &&\n typeof (value as AbortSignalLike).addEventListener === 'function' &&\n 'removeEventListener' in value &&\n typeof (value as AbortSignalLike).removeEventListener === 'function'\n )\n}\n\n/**\n * Make JSDOM's `addEventListener({signal})` accept native Node.js AbortSignals.\n *\n * JSDOM validates `signal` using its own realm's `AbortSignal` constructor, which rejects\n * Node's native signal. Instead of replacing the global Abort APIs, intercept those calls\n * and emulate the abortable-listener behavior for cross-realm signals.\n */\nfunction patchEventTargetSignalSupport(dom: JSDOM): void {\n const eventTarget = dom.window.EventTarget\n const addEventListener = eventTarget.prototype.addEventListener\n\n eventTarget.prototype.addEventListener = function addEventListenerPatched(\n type: string,\n listener: EventListenerOrEventListenerObject | null,\n options?: AddEventListenerOptions | boolean,\n ) {\n if (typeof options === 'boolean' || !options?.signal) {\n return addEventListener.call(this, type, listener, options)\n }\n\n const rawSignal = (options as EventListenerOptionsWithSignal).signal\n const isJSDOMSignal = rawSignal instanceof (dom.window.AbortSignal as typeof AbortSignal)\n if (!rawSignal || isJSDOMSignal || !isAbortSignalLike(rawSignal)) {\n return addEventListener.call(this, type, listener, options)\n }\n\n const signal: AbortSignalLike = rawSignal\n if (signal.aborted) {\n return\n }\n\n const {signal: _signal, ...optionsWithoutSignal} = options as EventListenerOptionsWithSignal\n addEventListener.call(this, type, listener, optionsWithoutSignal)\n\n const removeOnAbort = () => {\n this.removeEventListener(type, listener, options)\n }\n\n signal.addEventListener('abort', removeOnAbort, {once: true})\n }\n}\n\n/**\n * Creates a JSDOM instance and applies polyfills for missing browser globals.\n */\nfunction createBrowserDom(): JSDOM {\n const dom = new JSDOM(html, {\n pretendToBeVisual: true,\n url: 'http://localhost:3333/',\n })\n\n patchEventTargetSignalSupport(dom)\n\n // Special handling of certain globals\n if (typeof dom.window.document.execCommand !== 'function') {\n // Crashes ace editor without this :/\n dom.window.document.execCommand = function execCommand(\n // Provide the right arity for the function, even if unused\n _commandName: string,\n _showDefaultUI: boolean,\n _valueArgument: unknown,\n ) {\n // Return false to indicate \"unsupported\"\n return false\n }\n }\n\n if (dom.window.requestIdleCallback === undefined) {\n dom.window.requestIdleCallback = (cb: IdleRequestCallback) => setTimeout(cb, 10)\n }\n\n if (dom.window.cancelIdleCallback === undefined) {\n dom.window.cancelIdleCallback = (id: number) => clearTimeout(id)\n }\n\n if (dom.window.ResizeObserver === undefined) {\n dom.window.ResizeObserver = class ResizeObserver {\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(_callback: unknown) {}\n disconnect() {}\n observe(_target: unknown, _options: unknown) {}\n unobserve(_target: unknown) {}\n }\n }\n\n if (dom.window.IntersectionObserver === undefined) {\n dom.window.IntersectionObserver = class IntersectionObserver {\n options: {root?: unknown; rootMargin?: string; threshold?: number}\n constructor(\n _callback: unknown,\n options?: {root?: unknown; rootMargin?: string; threshold?: number},\n ) {\n this.options = options || {}\n }\n get root() {\n return this.options.root || null\n }\n get rootMargin() {\n return this.options.rootMargin || ''\n }\n get thresholds() {\n return Array.isArray(this.options.threshold)\n ? this.options.threshold\n : [this.options.threshold || 0]\n }\n\n disconnect() {}\n observe(_el: unknown) {}\n takeRecords() {\n return []\n }\n unobserve(_el: unknown) {}\n }\n }\n\n if (dom.window.matchMedia === undefined) {\n dom.window.matchMedia = (_qs: unknown) =>\n ({\n matches: false,\n media: '',\n onchange: null,\n }) as MediaQueryList\n }\n\n return dom\n}\n\n/**\n * Collects all browser globals from the JSDOM window that should be injected\n * into the Node.js global scope to emulate a browser environment.\n *\n * This dynamically iterates over all own properties of the JSDOM window,\n * skipping internal JSDOM properties (prefixed with `_`) and properties that\n * already exist in Node.js globals to avoid conflicts.\n *\n * This approach ensures that any new properties added by JSDOM upgrades are\n * automatically included, preventing \"missing global\" bugs (e.g. `Element`,\n * `HTMLElement`, `SVGElement` needed by libraries like styled-components).\n */\nfunction collectBrowserStubs(): Record<string, unknown> {\n const dom = createBrowserDom()\n const stubs: Record<string, unknown> = Object.create(null)\n const nodeGlobals = new Set(Object.getOwnPropertyNames(globalThis))\n\n for (const key of Object.getOwnPropertyNames(dom.window)) {\n // Skip internal JSDOM properties\n if (key.startsWith('_')) continue\n\n // Skip numeric indices (e.g. '0' for window[0])\n if (/^\\d+$/.test(key)) continue\n\n // Skip properties that Node.js already provides to avoid conflicts\n if (nodeGlobals.has(key)) continue\n\n stubs[key] = (dom.window as Record<string, unknown>)[key]\n }\n\n return stubs\n}\n\nlet browserStubs: Record<string, unknown> | undefined\n\nexport function getBrowserStubs(): Record<string, unknown> {\n if (!browserStubs) {\n browserStubs = collectBrowserStubs()\n }\n return browserStubs\n}\n"],"names":["JSDOM","html","isAbortSignalLike","value","aborted","addEventListener","removeEventListener","patchEventTargetSignalSupport","dom","eventTarget","window","EventTarget","prototype","addEventListenerPatched","type","listener","options","signal","call","rawSignal","isJSDOMSignal","AbortSignal","_signal","optionsWithoutSignal","removeOnAbort","once","createBrowserDom","pretendToBeVisual","url","document","execCommand","_commandName","_showDefaultUI","_valueArgument","requestIdleCallback","undefined","cb","setTimeout","cancelIdleCallback","id","clearTimeout","ResizeObserver","_callback","disconnect","observe","_target","_options","unobserve","IntersectionObserver","root","rootMargin","thresholds","Array","isArray","threshold","_el","takeRecords","matchMedia","_qs","matches","media","onchange","collectBrowserStubs","stubs","Object","create","nodeGlobals","Set","getOwnPropertyNames","globalThis","key","startsWith","test","has","browserStubs","getBrowserStubs"],"mappings":"AAAA,SAAQA,KAAK,QAAO,QAAO;AAE3B,MAAMC,OAAO,CAAC;;;;OAIP,CAAC;AAUR,SAASC,kBAAkBC,KAAc;IACvC,OACE,CAAC,CAACA,SAC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vC,IAAI,CAACtC,OAAO,CAACsC,SAAS,GACtB;oBAAC,IAAI,CAACtC,OAAO,CAACsC,SAAS,IAAI;iBAAE;YACnC;YAEAX,aAAa,CAAC;YACdC,QAAQW,GAAY,EAAE,CAAC;YACvBC,cAAc;gBACZ,OAAO,EAAE;YACX;YACAT,UAAUQ,GAAY,EAAE,CAAC;QAC3B;IACF;IAEA,IAAI/C,IAAIE,MAAM,CAAC+C,UAAU,KAAKtB,WAAW;QACvC3B,IAAIE,MAAM,CAAC+C,UAAU,GAAG,CAACC,MACtB,CAAA;gBACCC,SAAS;gBACTC,OAAO;gBACPC,UAAU;YACZ,CAAA;IACJ;IAEA,OAAOrD;AACT;AAEA;;;;;;;;;;;CAWC,GACD,SAASsD;IACP,MAAMtD,MAAMkB;IACZ,MAAMqC,QAAiCC,OAAOC,MAAM,CAAC;IACrD,MAAMC,cAAc,IAAIC,IAAIH,OAAOI,mBAAmB,CAACC;IAEvD,KAAK,MAAMC,OAAON,OAAOI,mBAAmB,CAAC5D,IAAIE,MAAM,EAAG;QACxD,iCAAiC;QACjC,IAAI4D,IAAIC,UAAU,CAAC,MAAM;QAEzB,gDAAgD;QAChD,IAAI,QAAQC,IAAI,CAACF,MAAM;QAEvB,mEAAmE;QACnE,IAAIJ,YAAYO,GAAG,CAACH,MAAM;QAE1BP,KAAK,CAACO,IAAI,GAAG,AAAC9D,IAAIE,MAAM,AAA4B,CAAC4D,IAAI;IAC3D;IAEA,OAAOP;AACT;AAEA,IAAIW;AAEJ,OAAO,SAASC;IACd,IAAI,CAACD,cAAc;QACjBA,eAAeZ;IACjB;IACA,OAAOY;AACT"}
1
+ {"version":3,"sources":["../../../src/util/environment/stubs.ts"],"sourcesContent":["import {JSDOM} from 'jsdom'\n\nconst html = `<!doctype html>\n<html>\n <head><meta charset=\"utf-8\"></head>\n <body></body>\n</html>`\n\ninterface AbortSignalLike {\n aborted: boolean\n addEventListener(type: 'abort', listener: () => void, options?: {once?: boolean}): void\n removeEventListener(type: 'abort', listener: () => void): void\n}\n\ntype EventListenerOptionsWithSignal = AddEventListenerOptions & {signal?: unknown}\n\nfunction isAbortSignalLike(value: unknown): value is AbortSignalLike {\n return (\n !!value &&\n typeof value === 'object' &&\n 'aborted' in value &&\n typeof (value as AbortSignalLike).aborted === 'boolean' &&\n 'addEventListener' in value &&\n typeof (value as AbortSignalLike).addEventListener === 'function' &&\n 'removeEventListener' in value &&\n typeof (value as AbortSignalLike).removeEventListener === 'function'\n )\n}\n\n/**\n * Make JSDOM's `addEventListener({signal})` accept native Node.js AbortSignals.\n *\n * JSDOM validates `signal` using its own realm's `AbortSignal` constructor, which rejects\n * Node's native signal. Instead of replacing the global Abort APIs, intercept those calls\n * and emulate the abortable-listener behavior for cross-realm signals.\n */\nfunction patchEventTargetSignalSupport(dom: JSDOM): void {\n const eventTarget = dom.window.EventTarget\n const addEventListener = eventTarget.prototype.addEventListener\n\n eventTarget.prototype.addEventListener = function addEventListenerPatched(\n type: string,\n listener: EventListenerOrEventListenerObject | null,\n options?: AddEventListenerOptions | boolean,\n ) {\n if (typeof options === 'boolean' || !options?.signal) {\n return addEventListener.call(this, type, listener, options)\n }\n\n const rawSignal = (options as EventListenerOptionsWithSignal).signal\n const isJSDOMSignal = rawSignal instanceof (dom.window.AbortSignal as typeof AbortSignal)\n if (!rawSignal || isJSDOMSignal || !isAbortSignalLike(rawSignal)) {\n return addEventListener.call(this, type, listener, options)\n }\n\n const signal: AbortSignalLike = rawSignal\n if (signal.aborted) {\n return\n }\n\n const {signal: _signal, ...optionsWithoutSignal} = options as EventListenerOptionsWithSignal\n addEventListener.call(this, type, listener, optionsWithoutSignal)\n\n const removeOnAbort = () => {\n this.removeEventListener(type, listener, options)\n }\n\n signal.addEventListener('abort', removeOnAbort, {once: true})\n }\n}\n\n/**\n * Creates a JSDOM instance and applies polyfills for missing browser globals.\n */\nfunction createBrowserDom(): JSDOM {\n const dom = new JSDOM(html, {\n pretendToBeVisual: true,\n url: 'http://localhost:3333/',\n })\n\n patchEventTargetSignalSupport(dom)\n\n // Special handling of certain globals\n if (typeof dom.window.document.execCommand !== 'function') {\n // Crashes ace editor without this :/\n dom.window.document.execCommand = function execCommand(\n // Provide the right arity for the function, even if unused\n _commandName: string,\n _showDefaultUI: boolean,\n _valueArgument: unknown,\n ) {\n // Return false to indicate \"unsupported\"\n return false\n }\n }\n\n if (dom.window.requestIdleCallback === undefined) {\n dom.window.requestIdleCallback = (cb: IdleRequestCallback) => setTimeout(cb, 10)\n }\n\n if (dom.window.cancelIdleCallback === undefined) {\n dom.window.cancelIdleCallback = (id: number) => clearTimeout(id)\n }\n\n if (dom.window.ResizeObserver === undefined) {\n dom.window.ResizeObserver = class ResizeObserver {\n // eslint-disable-next-line @typescript-eslint/no-useless-constructor\n constructor(_callback: unknown) {}\n disconnect() {}\n observe(_target: unknown, _options: unknown) {}\n unobserve(_target: unknown) {}\n }\n }\n\n if (dom.window.IntersectionObserver === undefined) {\n dom.window.IntersectionObserver = class IntersectionObserver {\n options: {root?: unknown; rootMargin?: string; threshold?: number}\n constructor(\n _callback: unknown,\n options?: {root?: unknown; rootMargin?: string; threshold?: number},\n ) {\n this.options = options || {}\n }\n get root() {\n return this.options.root || null\n }\n get rootMargin() {\n return this.options.rootMargin || ''\n }\n get thresholds() {\n return Array.isArray(this.options.threshold)\n ? this.options.threshold\n : [this.options.threshold || 0]\n }\n\n disconnect() {}\n observe(_el: unknown) {}\n takeRecords() {\n return []\n }\n unobserve(_el: unknown) {}\n }\n }\n\n if (dom.window.matchMedia === undefined) {\n dom.window.matchMedia = (_qs: unknown) =>\n ({\n matches: false,\n media: '',\n onchange: null,\n }) as MediaQueryList\n }\n\n return dom\n}\n\n/**\n * Web globals that Node.js may provide but whose JSDOM implementations we\n * always prefer, so that behavior is consistent across Node versions.\n *\n * Node 26+ exposes `localStorage`/`sessionStorage`/`Storage` as built-in globals,\n * but `localStorage` is `undefined` unless started with `--localstorage-file`, and\n * the `Storage` constructor identity differs from JSDOM's. Mixing realms would\n * break code that does `localStorage instanceof Storage`, so we override all\n * three together.\n */\nconst ALWAYS_INCLUDE_FROM_JSDOM = new Set(['localStorage', 'sessionStorage', 'Storage'])\n\n/**\n * Collects all browser globals from the JSDOM window that should be injected\n * into the Node.js global scope to emulate a browser environment.\n *\n * This dynamically iterates over all own properties of the JSDOM window,\n * skipping internal JSDOM properties (prefixed with `_`) and properties that\n * already exist in Node.js globals to avoid conflicts.\n *\n * This approach ensures that any new properties added by JSDOM upgrades are\n * automatically included, preventing \"missing global\" bugs (e.g. `Element`,\n * `HTMLElement`, `SVGElement` needed by libraries like styled-components).\n */\nfunction collectBrowserStubs(): Record<string, unknown> {\n const dom = createBrowserDom()\n const stubs: Record<string, unknown> = Object.create(null)\n const nodeGlobals = new Set(Object.getOwnPropertyNames(globalThis))\n\n for (const key of Object.getOwnPropertyNames(dom.window)) {\n // Skip internal JSDOM properties\n if (key.startsWith('_')) continue\n\n // Skip numeric indices (e.g. '0' for window[0])\n if (/^\\d+$/.test(key)) continue\n\n // Skip properties that Node.js already provides to avoid conflicts, unless\n // we explicitly want to override Node's version with JSDOM's\n if (nodeGlobals.has(key) && !ALWAYS_INCLUDE_FROM_JSDOM.has(key)) continue\n\n stubs[key] = (dom.window as Record<string, unknown>)[key]\n }\n\n return stubs\n}\n\nlet browserStubs: Record<string, unknown> | undefined\n\nexport function getBrowserStubs(): Record<string, unknown> {\n if (!browserStubs) {\n browserStubs = collectBrowserStubs()\n }\n return browserStubs\n}\n"],"names":["JSDOM","html","isAbortSignalLike","value","aborted","addEventListener","removeEventListener","patchEventTargetSignalSupport","dom","eventTarget","window","EventTarget","prototype","addEventListenerPatched","type","listener","options","signal","call","rawSignal","isJSDOMSignal","AbortSignal","_signal","optionsWithoutSignal","removeOnAbort","once","createBrowserDom","pretendToBeVisual","url","document","execCommand","_commandName","_showDefaultUI","_valueArgument","requestIdleCallback","undefined","cb","setTimeout","cancelIdleCallback","id","clearTimeout","ResizeObserver","_callback","disconnect","observe","_target","_options","unobserve","IntersectionObserver","root","rootMargin","thresholds","Array","isArray","threshold","_el","takeRecords","matchMedia","_qs","matches","media","onchange","ALWAYS_INCLUDE_FROM_JSDOM","Set","collectBrowserStubs","stubs","Object","create","nodeGlobals","getOwnPropertyNames","globalThis","key","startsWith","test","has","browserStubs","getBrowserStubs"],"mappings":"AAAA,SAAQA,KAAK,QAAO,QAAO;AAE3B,MAAMC,OAAO,CAAC;;;;OAIP,CAAC;AAUR,SAASC,kBAAkBC,KAAc;IACvC,OACE,CAAC,CAACA,SACF,OAAOA,UAAU,YACjB,aAAaA,SACb,OAAO,AAACA,MAA0BC,OAAO,KAAK,aAC9C,sBAAsBD,SACtB,OAAO,AAACA,MAA0BE,gBAAgB,KAAK,cACvD,yBAAyBF,SACzB,OAAO,AAACA,MAA0BG,mBAAmB,KAAK;AAE9D;AAEA;;;;;;CAMC,GACD,SAASC,8BAA8BC,GAAU;IAC/C,MAAMC,cAAcD,IAAIE,MAAM,CAACC,WAAW;IAC1C,MAAMN,mBAAmBI,YAAYG,SAAS,CAACP,gBAAgB;IAE/DI,YAAYG,SAAS,CAACP,gBAAgB,GAAG,SAASQ,wBAChDC,IAAY,EACZC,QAAmD,EACnDC,OAA2C;QAE3C,IAAI,OAAOA,YAAY,aAAa,CAACA,SAASC,QAAQ;YACpD,OAAOZ,iBAAiBa,IAAI,CAAC,IAAI,EAAEJ,MAAMC,UAAUC;QACrD;QAEA,MAAMG,YAAY,AAACH,QAA2CC,MAAM;QACpE,MAAMG,gBAAgBD,qBAAsBX,IAAIE,MAAM,CAACW,WAAW;QAClE,IAAI,CAACF,aAAaC,iBAAiB,CAAClB,kBAAkBiB,YAAY;YAChE,OAAOd,iBAAiBa,IAAI,CAAC,IAAI,EAAEJ,MAAMC,UAAUC;QACrD;QAEA,MAAMC,SAA0BE;QAChC,IAAIF,OAAOb,OAAO,EAAE;YAClB;QACF;QAEA,MAAM,EAACa,QAAQK,OAAO,EAAE,GAAGC,sBAAqB,GAAGP;QACnDX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CAACH,QAAQ,CAACT,0BAA0BY,GAAG,CAACH,MAAM;QAEjEN,KAAK,CAACM,IAAI,GAAG,AAAC/D,IAAIE,MAAM,AAA4B,CAAC6D,IAAI;IAC3D;IAEA,OAAON;AACT;AAEA,IAAIU;AAEJ,OAAO,SAASC;IACd,IAAI,CAACD,cAAc;QACjBA,eAAeX;IACjB;IACA,OAAOW;AACT"}
@@ -0,0 +1,32 @@
1
+ import { homedir } from 'node:os';
2
+ import { join as joinPath } from 'node:path';
3
+ import { isStaging } from './isStaging.js';
4
+ function envSuffix() {
5
+ return isStaging() ? '-staging' : '';
6
+ }
7
+ /**
8
+ * Returns the base Sanity configuration directory for the current user.
9
+ * For persistent user settings (auth tokens, preferences, etc.).
10
+ * Respects `SANITY_INTERNAL_ENV=staging` to isolate staging instances.
11
+ *
12
+ * Layout: `~/.config/sanity{-staging}/`
13
+ *
14
+ * @returns Absolute path to the config directory
15
+ * @internal
16
+ */ export function getSanityConfigDir() {
17
+ return joinPath(homedir(), '.config', `sanity${envSuffix()}`);
18
+ }
19
+ /**
20
+ * Returns the base Sanity data directory for the current user.
21
+ * For ephemeral runtime state (dev-server registries, caches, etc.).
22
+ * Respects `SANITY_INTERNAL_ENV=staging` to isolate staging instances.
23
+ *
24
+ * Layout: `~/.sanity{-staging}/`
25
+ *
26
+ * @returns Absolute path to the data directory
27
+ * @internal
28
+ */ export function getSanityDataDir() {
29
+ return joinPath(homedir(), `.sanity${envSuffix()}`);
30
+ }
31
+
32
+ //# sourceMappingURL=getSanityConfigDir.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/getSanityConfigDir.ts"],"sourcesContent":["import {homedir} from 'node:os'\nimport {join as joinPath} from 'node:path'\n\nimport {isStaging} from './isStaging.js'\n\nfunction envSuffix(): string {\n return isStaging() ? '-staging' : ''\n}\n\n/**\n * Returns the base Sanity configuration directory for the current user.\n * For persistent user settings (auth tokens, preferences, etc.).\n * Respects `SANITY_INTERNAL_ENV=staging` to isolate staging instances.\n *\n * Layout: `~/.config/sanity{-staging}/`\n *\n * @returns Absolute path to the config directory\n * @internal\n */\nexport function getSanityConfigDir(): string {\n return joinPath(homedir(), '.config', `sanity${envSuffix()}`)\n}\n\n/**\n * Returns the base Sanity data directory for the current user.\n * For ephemeral runtime state (dev-server registries, caches, etc.).\n * Respects `SANITY_INTERNAL_ENV=staging` to isolate staging instances.\n *\n * Layout: `~/.sanity{-staging}/`\n *\n * @returns Absolute path to the data directory\n * @internal\n */\nexport function getSanityDataDir(): string {\n return joinPath(homedir(), `.sanity${envSuffix()}`)\n}\n"],"names":["homedir","join","joinPath","isStaging","envSuffix","getSanityConfigDir","getSanityDataDir"],"mappings":"AAAA,SAAQA,OAAO,QAAO,UAAS;AAC/B,SAAQC,QAAQC,QAAQ,QAAO,YAAW;AAE1C,SAAQC,SAAS,QAAO,iBAAgB;AAExC,SAASC;IACP,OAAOD,cAAc,aAAa;AACpC;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASE;IACd,OAAOH,SAASF,WAAW,WAAW,CAAC,MAAM,EAAEI,aAAa;AAC9D;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASE;IACd,OAAOJ,SAASF,WAAW,CAAC,OAAO,EAAEI,aAAa;AACpD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli-core",
3
- "version": "2.0.1",
3
+ "version": "2.1.1",
4
4
  "description": "Sanity CLI core package",
5
5
  "keywords": [
6
6
  "cli",
@@ -27,7 +27,7 @@
27
27
  "type": "module",
28
28
  "sideEffects": false,
29
29
  "main": "./dist/_exports/index.js",
30
- "types": "dist/_exports/index.d.ts",
30
+ "types": "./dist/_exports/index.d.ts",
31
31
  "exports": {
32
32
  ".": {
33
33
  "source": "./src/_exports/index.ts",
@@ -52,11 +52,11 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@inquirer/prompts": "^8.5.2",
55
- "@oclif/core": "^4.11.4",
56
- "@sanity/client": "^7.22.1",
55
+ "@oclif/core": "^4.11.7",
56
+ "@sanity/client": "^7.23.0",
57
57
  "boxen": "^8.0.1",
58
58
  "debug": "^4.4.3",
59
- "get-it": "^8.7.2",
59
+ "get-it": "^8.8.0",
60
60
  "get-tsconfig": "^4.14.0",
61
61
  "import-meta-resolve": "^4.2.0",
62
62
  "jiti": "^2.7.0",
@@ -67,25 +67,25 @@
67
67
  "read-package-up": "^12.0.0",
68
68
  "rxjs": "^7.8.2",
69
69
  "tsx": "^4.22.4",
70
- "vite": "^8.0.16",
70
+ "vite": "^8.1.0",
71
71
  "vite-node": "^6.0.0",
72
- "zod": "^4.3.6"
72
+ "zod": "^4.4.3"
73
73
  },
74
74
  "devDependencies": {
75
75
  "@eslint/compat": "^2.1.0",
76
- "@sanity/pkg-utils": "^10.5.2",
76
+ "@sanity/pkg-utils": "^10.5.8",
77
77
  "@sanity/telemetry": "^1.1.0",
78
78
  "@swc/cli": "^0.8.1",
79
- "@swc/core": "^1.15.40",
79
+ "@swc/core": "^1.15.41",
80
80
  "@types/debug": "^4.1.13",
81
81
  "@types/jsdom": "^28.0.3",
82
- "@types/node": "^20.19.41",
82
+ "@types/node": "^22.20.0",
83
83
  "babel-plugin-react-compiler": "^1.0.0",
84
84
  "eslint": "^10.4.1",
85
85
  "publint": "^0.3.21",
86
- "sanity": "^5.30.0",
86
+ "sanity": "^6.1.0",
87
87
  "typescript": "^5.9.3",
88
- "vitest": "^4.1.8",
88
+ "vitest": "^4.1.9",
89
89
  "@repo/package.config": "0.0.1",
90
90
  "@repo/tsconfig": "3.70.0",
91
91
  "@sanity/eslint-config-cli": "1.1.2"
@@ -99,7 +99,7 @@
99
99
  }
100
100
  },
101
101
  "engines": {
102
- "node": ">=20.19.1 <22 || >=22.12"
102
+ "node": ">=22.12"
103
103
  },
104
104
  "scripts": {
105
105
  "build": "swc --delete-dir-on-start --strip-leading-paths --out-dir dist/ src --ignore '**/*.test.ts' --ignore '**/__tests__/**'",