@sanity/cli 6.0.0-alpha.18 → 6.0.0-alpha.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions/build/getViteConfig.js +47 -4
- package/dist/actions/build/getViteConfig.js.map +1 -1
- package/dist/actions/build/renderDocumentWorker/components/GlobalErrorHandler.js +1 -0
- package/dist/actions/build/renderDocumentWorker/components/GlobalErrorHandler.js.map +1 -1
- package/dist/actions/build/writeSanityRuntime.js +4 -3
- package/dist/actions/build/writeSanityRuntime.js.map +1 -1
- package/dist/actions/dev/getDashboardAppUrl.js +48 -0
- package/dist/actions/dev/getDashboardAppUrl.js.map +1 -0
- package/dist/actions/dev/getDevServerConfig.js +2 -1
- package/dist/actions/dev/getDevServerConfig.js.map +1 -1
- package/dist/actions/dev/startAppDevServer.js +3 -3
- package/dist/actions/dev/startAppDevServer.js.map +1 -1
- package/dist/actions/dev/startStudioDevServer.js +5 -10
- package/dist/actions/dev/startStudioDevServer.js.map +1 -1
- package/dist/actions/schema/extractSchemaWatcher.js +8 -6
- package/dist/actions/schema/extractSchemaWatcher.js.map +1 -1
- package/dist/actions/schema/matchSchemaPattern.js +22 -0
- package/dist/actions/schema/matchSchemaPattern.js.map +1 -0
- package/dist/actions/schema/runSchemaExtraction.js.map +1 -1
- package/dist/commands/backup/disable.js +0 -6
- package/dist/commands/backup/disable.js.map +1 -1
- package/dist/commands/backup/download.js +0 -6
- package/dist/commands/backup/download.js.map +1 -1
- package/dist/commands/backup/enable.js +0 -6
- package/dist/commands/backup/enable.js.map +1 -1
- package/dist/commands/backup/list.js +0 -6
- package/dist/commands/backup/list.js.map +1 -1
- package/dist/commands/cors/add.js +0 -6
- package/dist/commands/cors/add.js.map +1 -1
- package/dist/commands/cors/delete.js +0 -6
- package/dist/commands/cors/delete.js.map +1 -1
- package/dist/commands/cors/list.js +0 -6
- package/dist/commands/cors/list.js.map +1 -1
- package/dist/commands/dataset/alias/create.js +23 -7
- package/dist/commands/dataset/alias/create.js.map +1 -1
- package/dist/commands/dataset/alias/delete.js +17 -7
- package/dist/commands/dataset/alias/delete.js.map +1 -1
- package/dist/commands/dataset/alias/link.js +17 -7
- package/dist/commands/dataset/alias/link.js.map +1 -1
- package/dist/commands/dataset/alias/unlink.js +17 -7
- package/dist/commands/dataset/alias/unlink.js.map +1 -1
- package/dist/commands/dataset/copy.js +39 -29
- package/dist/commands/dataset/copy.js.map +1 -1
- package/dist/commands/dataset/create.js +17 -7
- package/dist/commands/dataset/create.js.map +1 -1
- package/dist/commands/dataset/delete.js +13 -7
- package/dist/commands/dataset/delete.js.map +1 -1
- package/dist/commands/dataset/embeddings/disable.js +19 -7
- package/dist/commands/dataset/embeddings/disable.js.map +1 -1
- package/dist/commands/dataset/embeddings/enable.js +17 -7
- package/dist/commands/dataset/embeddings/enable.js.map +1 -1
- package/dist/commands/dataset/embeddings/status.js +15 -7
- package/dist/commands/dataset/embeddings/status.js.map +1 -1
- package/dist/commands/dataset/export.js +30 -18
- package/dist/commands/dataset/export.js.map +1 -1
- package/dist/commands/dataset/list.js +19 -7
- package/dist/commands/dataset/list.js.map +1 -1
- package/dist/commands/dataset/visibility/get.js +15 -7
- package/dist/commands/dataset/visibility/get.js.map +1 -1
- package/dist/commands/dataset/visibility/set.js +19 -7
- package/dist/commands/dataset/visibility/set.js.map +1 -1
- package/dist/commands/documents/create.js +0 -6
- package/dist/commands/documents/create.js.map +1 -1
- package/dist/commands/documents/delete.js +0 -6
- package/dist/commands/documents/delete.js.map +1 -1
- package/dist/commands/documents/get.js +0 -6
- package/dist/commands/documents/get.js.map +1 -1
- package/dist/commands/documents/query.js +0 -6
- package/dist/commands/documents/query.js.map +1 -1
- package/dist/commands/graphql/list.js +0 -6
- package/dist/commands/graphql/list.js.map +1 -1
- package/dist/commands/graphql/undeploy.js +0 -6
- package/dist/commands/graphql/undeploy.js.map +1 -1
- package/dist/commands/hook/attempt.js +0 -6
- package/dist/commands/hook/attempt.js.map +1 -1
- package/dist/commands/hook/create.js +0 -6
- package/dist/commands/hook/create.js.map +1 -1
- package/dist/commands/hook/delete.js +0 -6
- package/dist/commands/hook/delete.js.map +1 -1
- package/dist/commands/hook/list.js +0 -6
- package/dist/commands/hook/list.js.map +1 -1
- package/dist/commands/hook/logs.js +0 -6
- package/dist/commands/hook/logs.js.map +1 -1
- package/dist/commands/media/delete-aspect.js +0 -6
- package/dist/commands/media/delete-aspect.js.map +1 -1
- package/dist/commands/media/deploy-aspect.js +1 -6
- package/dist/commands/media/deploy-aspect.js.map +1 -1
- package/dist/commands/media/export.js +0 -6
- package/dist/commands/media/export.js.map +1 -1
- package/dist/commands/media/import.js +0 -6
- package/dist/commands/media/import.js.map +1 -1
- package/dist/commands/schema/delete.js +0 -6
- package/dist/commands/schema/delete.js.map +1 -1
- package/dist/commands/tokens/add.js +0 -6
- package/dist/commands/tokens/add.js.map +1 -1
- package/dist/commands/tokens/delete.js +0 -6
- package/dist/commands/tokens/delete.js.map +1 -1
- package/dist/commands/tokens/list.js +0 -6
- package/dist/commands/tokens/list.js.map +1 -1
- package/dist/commands/users/invite.js +0 -6
- package/dist/commands/users/invite.js.map +1 -1
- package/dist/commands/users/list.js +0 -6
- package/dist/commands/users/list.js.map +1 -1
- package/dist/prompts/promptForProject.js +64 -0
- package/dist/prompts/promptForProject.js.map +1 -0
- package/dist/server/devServer.js +4 -2
- package/dist/server/devServer.js.map +1 -1
- package/dist/server/vite/plugin-schema-extraction.js +201 -0
- package/dist/server/vite/plugin-schema-extraction.js.map +1 -0
- package/dist/server/vite/plugin-typegen.js +217 -0
- package/dist/server/vite/plugin-typegen.js.map +1 -0
- package/dist/services/grants.js +13 -0
- package/dist/services/grants.js.map +1 -0
- package/dist/types/grants.js +3 -0
- package/dist/types/grants.js.map +1 -0
- package/dist/util/checkProjectPermissions.js +21 -0
- package/dist/util/checkProjectPermissions.js.map +1 -0
- package/dist/util/getSharedServerConfig.js +1 -0
- package/dist/util/getSharedServerConfig.js.map +1 -1
- package/dist/util/sharedFlags.js +19 -0
- package/dist/util/sharedFlags.js.map +1 -0
- package/dist/util/toForwardSlashes.js +8 -0
- package/dist/util/toForwardSlashes.js.map +1 -0
- package/oclif.manifest.json +412 -286
- package/package.json +18 -16
- package/dist/actions/dev/getCoreAppUrl.js +0 -10
- package/dist/actions/dev/getCoreAppUrl.js.map +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
|
+
import { findProjectRoot, getCliTelemetry } from '@sanity/cli-core';
|
|
2
3
|
import viteReact from '@vitejs/plugin-react';
|
|
3
4
|
import debug from 'debug';
|
|
4
5
|
import { readPackageUp } from 'read-package-up';
|
|
@@ -6,6 +7,8 @@ import { mergeConfig } from 'vite';
|
|
|
6
7
|
import { sanityBuildEntries } from '../../server/vite/plugin-sanity-build-entries.js';
|
|
7
8
|
import { sanityFaviconsPlugin } from '../../server/vite/plugin-sanity-favicons.js';
|
|
8
9
|
import { sanityRuntimeRewritePlugin } from '../../server/vite/plugin-sanity-runtime-rewrite.js';
|
|
10
|
+
import { sanitySchemaExtractionPlugin } from '../../server/vite/plugin-schema-extraction.js';
|
|
11
|
+
import { sanityTypegenPlugin } from '../../server/vite/plugin-typegen.js';
|
|
9
12
|
import { createExternalFromImportMap } from './createExternalFromImportMap.js';
|
|
10
13
|
import { getAppEnvironmentVariables, getStudioEnvironmentVariables } from './getStudioEnvironmentVariables.js';
|
|
11
14
|
import { normalizeBasePath } from './normalizeBasePath.js';
|
|
@@ -14,8 +17,8 @@ import { normalizeBasePath } from './normalizeBasePath.js';
|
|
|
14
17
|
*
|
|
15
18
|
* @internal Only meant for consumption inside of Sanity modules, do not depend on this externally
|
|
16
19
|
*/ export async function getViteConfig(options) {
|
|
17
|
-
const { basePath: rawBasePath = '/', cwd, importMap, isApp, minify, mode, outputDir, reactCompiler, server, // default to `true` when `mode=development`
|
|
18
|
-
sourceMap = options.mode === 'development' } = options;
|
|
20
|
+
const { basePath: rawBasePath = '/', cwd, importMap, isApp, minify, mode, outputDir, reactCompiler, schemaExtraction, server, // default to `true` when `mode=development`
|
|
21
|
+
sourceMap = options.mode === 'development', typegen } = options;
|
|
19
22
|
const basePath = normalizeBasePath(rawBasePath);
|
|
20
23
|
const sanityCliPkgPath = (await readPackageUp({
|
|
21
24
|
cwd: import.meta.dirname
|
|
@@ -23,6 +26,7 @@ import { normalizeBasePath } from './normalizeBasePath.js';
|
|
|
23
26
|
if (!sanityCliPkgPath) {
|
|
24
27
|
throw new Error('Unable to resolve `@sanity/cli` module root');
|
|
25
28
|
}
|
|
29
|
+
const configPath = (await findProjectRoot(cwd)).path;
|
|
26
30
|
const customFaviconsPath = path.join(cwd, 'static');
|
|
27
31
|
const defaultFaviconsPath = path.join(path.dirname(sanityCliPkgPath), 'static', 'favicons');
|
|
28
32
|
const staticPath = `${basePath}static`;
|
|
@@ -44,8 +48,10 @@ import { normalizeBasePath } from './normalizeBasePath.js';
|
|
|
44
48
|
cacheDir: 'node_modules/.sanity/vite',
|
|
45
49
|
configFile: false,
|
|
46
50
|
define: {
|
|
51
|
+
__SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),
|
|
47
52
|
__SANITY_STAGING__: process.env.SANITY_INTERNAL_ENV === 'staging',
|
|
48
53
|
'process.env.MODE': JSON.stringify(mode),
|
|
54
|
+
'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),
|
|
49
55
|
/**
|
|
50
56
|
* Yes, double negatives are confusing.
|
|
51
57
|
* The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34
|
|
@@ -63,6 +69,9 @@ import { normalizeBasePath } from './normalizeBasePath.js';
|
|
|
63
69
|
plugins: [
|
|
64
70
|
viteReact(reactCompiler ? {
|
|
65
71
|
babel: {
|
|
72
|
+
generatorOpts: {
|
|
73
|
+
compact: true
|
|
74
|
+
},
|
|
66
75
|
plugins: [
|
|
67
76
|
[
|
|
68
77
|
'babel-plugin-react-compiler',
|
|
@@ -82,10 +91,33 @@ import { normalizeBasePath } from './normalizeBasePath.js';
|
|
|
82
91
|
cwd,
|
|
83
92
|
importMap,
|
|
84
93
|
isApp
|
|
85
|
-
})
|
|
94
|
+
}),
|
|
95
|
+
// Add schema extraction when enabled
|
|
96
|
+
...schemaExtraction?.enabled ? [
|
|
97
|
+
sanitySchemaExtractionPlugin({
|
|
98
|
+
additionalPatterns: schemaExtraction.watchPatterns,
|
|
99
|
+
configPath,
|
|
100
|
+
enforceRequiredFields: schemaExtraction.enforceRequiredFields,
|
|
101
|
+
outputPath: schemaExtraction.path,
|
|
102
|
+
telemetryLogger: getCliTelemetry(),
|
|
103
|
+
workDir: cwd,
|
|
104
|
+
workspaceName: schemaExtraction.workspace
|
|
105
|
+
})
|
|
106
|
+
] : [],
|
|
107
|
+
// Add typegen when enabled
|
|
108
|
+
...typegen?.enabled ? [
|
|
109
|
+
sanityTypegenPlugin({
|
|
110
|
+
config: typegen,
|
|
111
|
+
telemetryLogger: getCliTelemetry(),
|
|
112
|
+
workDir: cwd
|
|
113
|
+
})
|
|
114
|
+
] : []
|
|
86
115
|
],
|
|
87
116
|
resolve: {
|
|
88
117
|
dedupe: [
|
|
118
|
+
'react',
|
|
119
|
+
'react-dom',
|
|
120
|
+
'sanity',
|
|
89
121
|
'styled-components'
|
|
90
122
|
]
|
|
91
123
|
},
|
|
@@ -95,7 +127,18 @@ import { normalizeBasePath } from './normalizeBasePath.js';
|
|
|
95
127
|
port: server?.port || 3333,
|
|
96
128
|
// Only enable strict port for studio,
|
|
97
129
|
// since apps can run on any port
|
|
98
|
-
strictPort: isApp ? false : true
|
|
130
|
+
strictPort: isApp ? false : true,
|
|
131
|
+
/**
|
|
132
|
+
* Significantly speed up startup time,
|
|
133
|
+
* and most importantly eliminates the `new dependencies optimized: foobar. optimized dependencies changed. reloading`
|
|
134
|
+
* types of initial reload loops that otherwise happen as vite discovers deps that need to be optimized.
|
|
135
|
+
* This option starts the traversal up front, and warms up the dep tree required to render the userland sanity.config.ts file,
|
|
136
|
+
* and thus avoids frustrating reload loops.
|
|
137
|
+
*/ warmup: {
|
|
138
|
+
clientFiles: [
|
|
139
|
+
'./.sanity/runtime/app.js'
|
|
140
|
+
]
|
|
141
|
+
}
|
|
99
142
|
}
|
|
100
143
|
};
|
|
101
144
|
if (mode === 'production') {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/build/getViteConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type UserViteConfig} from '@sanity/cli-core'\nimport viteReact from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport debug from 'debug'\nimport {readPackageUp} from 'read-package-up'\nimport {type ConfigEnv, type InlineConfig, mergeConfig, type Rollup} from 'vite'\n\nimport {sanityBuildEntries} from '../../server/vite/plugin-sanity-build-entries.js'\nimport {sanityFaviconsPlugin} from '../../server/vite/plugin-sanity-favicons.js'\nimport {sanityRuntimeRewritePlugin} from '../../server/vite/plugin-sanity-runtime-rewrite.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {\n getAppEnvironmentVariables,\n getStudioEnvironmentVariables,\n} from './getStudioEnvironmentVariables.js'\nimport {normalizeBasePath} from './normalizeBasePath.js'\n\ninterface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: string\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n reactCompiler: ReactCompilerConfig | undefined\n\n /**\n * Base path (eg under where to serve the app - `/studio` or similar)\n * Will be normalized to ensure it starts and ends with a `/`\n */\n basePath?: string\n\n importMap?: {imports?: Record<string, string>}\n\n isApp?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n}\n\n/**\n * Get a configuration object for Vite based on the passed options\n *\n * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally\n */\nexport async function getViteConfig(options: ViteOptions): Promise<InlineConfig> {\n const {\n basePath: rawBasePath = '/',\n cwd,\n importMap,\n isApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n server,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n } = options\n\n const basePath = normalizeBasePath(rawBasePath)\n\n const sanityCliPkgPath = (await readPackageUp({cwd: import.meta.dirname}))?.path\n if (!sanityCliPkgPath) {\n throw new Error('Unable to resolve `@sanity/cli` module root')\n }\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = path.join(path.dirname(sanityCliPkgPath), 'static', 'favicons')\n const staticPath = `${basePath}static`\n\n const envVars = isApp\n ? getAppEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n : getStudioEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n\n const viteConfig: InlineConfig = {\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: 'node_modules/.sanity/vite',\n configFile: false,\n define: {\n __SANITY_STAGING__: process.env.SANITY_INTERNAL_ENV === 'staging',\n 'process.env.MODE': JSON.stringify(mode),\n /**\n * Yes, double negatives are confusing.\n * The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34\n * Which means that in production, use the much faster way of inserting CSS rules, based on the CSSStyleSheet API (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule)\n * while in dev mode, use the slower way of inserting CSS rules, which appends text nodes to the `<style>` tag: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/sheet/Tag.ts#L74-L76\n * There are historical reasons for this, primarily that browsers initially did not support editing CSS rules in the DevTools inspector if `CSSStyleSheet.insetRule` were used.\n * However, that's no longer the case (since Chrome 81 back in April 2020: https://developer.chrome.com/docs/css-ui/css-in-js), the latest version of FireFox also supports it,\n * and there is no longer any reason to use the much slower method in dev mode.\n */\n 'process.env.SC_DISABLE_SPEEDY': JSON.stringify('false'),\n ...envVars,\n },\n envPrefix: isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n mode,\n plugins: [\n viteReact(\n reactCompiler ? {babel: {plugins: [['babel-plugin-react-compiler', reactCompiler]]}} : {},\n ),\n sanityFaviconsPlugin({customFaviconsPath, defaultFaviconsPath, staticUrlPath: staticPath}),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({basePath, cwd, importMap, isApp}),\n ],\n resolve: {\n dedupe: ['styled-components'],\n },\n root: cwd,\n server: {\n host: server?.host,\n port: server?.port || 3333,\n // Only enable strict port for studio,\n // since apps can run on any port\n strictPort: isApp ? false : true,\n },\n }\n\n if (mode === 'production') {\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n emptyOutDir: false, // Rely on CLI to do this\n minify: minify ? 'esbuild' : false,\n\n rollupOptions: {\n external: createExternalFromImportMap(importMap),\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n },\n onwarn: onRollupWarn,\n },\n }\n }\n\n return viteConfig\n}\n\nfunction onRollupWarn(warning: Rollup.RollupLog, warn: Rollup.LoggingFunction) {\n if (suppressUnusedImport(warning)) {\n return\n }\n\n warn(warning)\n}\n\nfunction suppressUnusedImport(warning: Rollup.RollupLog & {ids?: string[]}): boolean {\n if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') return false\n\n // Suppress:\n // ```\n // \"useDebugValue\" is imported from external module \"react\"…\n // ```\n if (warning.names?.includes('useDebugValue')) {\n warning.names = warning.names.filter((n) => n !== 'useDebugValue')\n if (warning.names.length === 0) return true\n }\n\n // If some library does something unexpected, we suppress since it isn't actionable\n if (warning.ids?.every((id) => id.includes('/node_modules/') || id.includes('\\\\node_modules\\\\')))\n return true\n\n return false\n}\n\n/**\n * Ensure Sanity entry chunk is always loaded\n *\n * @param config - User-modified configuration\n * @returns Merged configuration\n * @internal\n */\nexport async function finalizeViteConfig(config: InlineConfig): Promise<InlineConfig> {\n if (typeof config.build?.rollupOptions?.input !== 'object') {\n throw new TypeError(\n 'Vite config must contain `build.rollupOptions.input`, and it must be an object',\n )\n }\n\n if (!config.root) {\n throw new Error(\n 'Vite config must contain `root` property, and must point to the Sanity root directory',\n )\n }\n\n return mergeConfig(config, {\n build: {\n rollupOptions: {\n input: {\n sanity: path.join(config.root, '.sanity', 'runtime', 'app.js'),\n },\n },\n },\n })\n}\n\n/**\n * Merge user-provided Vite configuration object or function\n *\n * @param defaultConfig - Default configuration object\n * @param userConfig - User-provided configuration object or function\n * @returns Merged configuration\n * @internal\n */\nexport async function extendViteConfigWithUserConfig(\n env: ConfigEnv,\n defaultConfig: InlineConfig,\n userConfig: UserViteConfig,\n): Promise<InlineConfig> {\n let config = defaultConfig\n\n if (typeof userConfig === 'function') {\n debug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n debug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","viteReact","debug","readPackageUp","mergeConfig","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","createExternalFromImportMap","getAppEnvironmentVariables","getStudioEnvironmentVariables","normalizeBasePath","getViteConfig","options","basePath","rawBasePath","cwd","importMap","isApp","minify","mode","outputDir","reactCompiler","server","sourceMap","sanityCliPkgPath","dirname","Error","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","jsonEncode","prefix","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_STAGING__","process","env","SANITY_INTERNAL_ENV","JSON","stringify","envPrefix","logLevel","plugins","babel","staticUrlPath","dedupe","root","host","port","strictPort","assetsDir","emptyOutDir","rollupOptions","external","input","sanity","onwarn","onRollupWarn","warning","warn","suppressUnusedImport","code","names","includes","filter","n","length","ids","every","id","finalizeViteConfig","config","TypeError","extendViteConfigWithUserConfig","defaultConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAG5B,OAAOC,eAAe,uBAAsB;AAE5C,OAAOC,WAAW,QAAO;AACzB,SAAQC,aAAa,QAAO,kBAAiB;AAC7C,SAA2CC,WAAW,QAAoB,OAAM;AAEhF,SAAQC,kBAAkB,QAAO,mDAAkD;AACnF,SAAQC,oBAAoB,QAAO,8CAA6C;AAChF,SAAQC,0BAA0B,QAAO,qDAAoD;AAC7F,SAAQC,2BAA2B,QAAO,mCAAkC;AAC5E,SACEC,0BAA0B,EAC1BC,6BAA6B,QACxB,qCAAoC;AAC3C,SAAQC,iBAAiB,QAAO,yBAAwB;AA4CxD;;;;CAIC,GACD,OAAO,eAAeC,cAAcC,OAAoB;IACtD,MAAM,EACJC,UAAUC,cAAc,GAAG,EAC3BC,GAAG,EACHC,SAAS,EACTC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,SAAS,EACTC,aAAa,EACbC,MAAM,EACN,4CAA4C;IAC5CC,YAAYX,QAAQO,IAAI,KAAK,aAAa,EAC3C,GAAGP;IAEJ,MAAMC,WAAWH,kBAAkBI;IAEnC,MAAMU,mBAAoB,CAAA,MAAMtB,cAAc;QAACa,KAAK,YAAYU,OAAO;IAAA,EAAC,GAAI1B;IAC5E,IAAI,CAACyB,kBAAkB;QACrB,MAAM,IAAIE,MAAM;IAClB;IAEA,MAAMC,qBAAqB5B,KAAK6B,IAAI,CAACb,KAAK;IAC1C,MAAMc,sBAAsB9B,KAAK6B,IAAI,CAAC7B,KAAK0B,OAAO,CAACD,mBAAmB,UAAU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MAAM;QACN+E,SAAS,MAAMI,WAAWJ,QAAQnC;IACpC,OAAO,IAAI,OAAOuC,eAAe,UAAU;QACzCnF,MAAM;QACN+E,SAAS7E,YAAY6E,QAAQI;IAC/B;IAEA,OAAOJ;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/getViteConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {\n type CliConfig,\n findProjectRoot,\n getCliTelemetry,\n type UserViteConfig,\n} from '@sanity/cli-core'\nimport viteReact from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport debug from 'debug'\nimport {readPackageUp} from 'read-package-up'\nimport {type ConfigEnv, type InlineConfig, mergeConfig, type Rollup} from 'vite'\n\nimport {sanityBuildEntries} from '../../server/vite/plugin-sanity-build-entries.js'\nimport {sanityFaviconsPlugin} from '../../server/vite/plugin-sanity-favicons.js'\nimport {sanityRuntimeRewritePlugin} from '../../server/vite/plugin-sanity-runtime-rewrite.js'\nimport {sanitySchemaExtractionPlugin} from '../../server/vite/plugin-schema-extraction.js'\nimport {sanityTypegenPlugin} from '../../server/vite/plugin-typegen.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {\n getAppEnvironmentVariables,\n getStudioEnvironmentVariables,\n} from './getStudioEnvironmentVariables.js'\nimport {normalizeBasePath} from './normalizeBasePath.js'\n\ninterface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: string\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n reactCompiler: ReactCompilerConfig | undefined\n\n /**\n * Base path (eg under where to serve the app - `/studio` or similar)\n * Will be normalized to ensure it starts and ends with a `/`\n */\n basePath?: string\n\n importMap?: {imports?: Record<string, string>}\n\n isApp?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n /**\n * Schema extraction configuration\n */\n schemaExtraction?: CliConfig['schemaExtraction']\n /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n /**\n * Typegen configuration\n */\n typegen?: CliConfig['typegen']\n}\n\n/**\n * Get a configuration object for Vite based on the passed options\n *\n * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally\n */\nexport async function getViteConfig(options: ViteOptions): Promise<InlineConfig> {\n const {\n basePath: rawBasePath = '/',\n cwd,\n importMap,\n isApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n server,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n typegen,\n } = options\n\n const basePath = normalizeBasePath(rawBasePath)\n\n const sanityCliPkgPath = (await readPackageUp({cwd: import.meta.dirname}))?.path\n if (!sanityCliPkgPath) {\n throw new Error('Unable to resolve `@sanity/cli` module root')\n }\n\n const configPath = (await findProjectRoot(cwd)).path\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = path.join(path.dirname(sanityCliPkgPath), 'static', 'favicons')\n const staticPath = `${basePath}static`\n\n const envVars = isApp\n ? getAppEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n : getStudioEnvironmentVariables({jsonEncode: true, prefix: 'process.env.'})\n\n const viteConfig: InlineConfig = {\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: 'node_modules/.sanity/vite',\n configFile: false,\n define: {\n __SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),\n __SANITY_STAGING__: process.env.SANITY_INTERNAL_ENV === 'staging',\n 'process.env.MODE': JSON.stringify(mode),\n 'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),\n /**\n * Yes, double negatives are confusing.\n * The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34\n * Which means that in production, use the much faster way of inserting CSS rules, based on the CSSStyleSheet API (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule)\n * while in dev mode, use the slower way of inserting CSS rules, which appends text nodes to the `<style>` tag: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/sheet/Tag.ts#L74-L76\n * There are historical reasons for this, primarily that browsers initially did not support editing CSS rules in the DevTools inspector if `CSSStyleSheet.insetRule` were used.\n * However, that's no longer the case (since Chrome 81 back in April 2020: https://developer.chrome.com/docs/css-ui/css-in-js), the latest version of FireFox also supports it,\n * and there is no longer any reason to use the much slower method in dev mode.\n */\n 'process.env.SC_DISABLE_SPEEDY': JSON.stringify('false'),\n ...envVars,\n },\n envPrefix: isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n mode,\n plugins: [\n viteReact(\n reactCompiler\n ? {\n babel: {\n generatorOpts: {compact: true},\n plugins: [['babel-plugin-react-compiler', reactCompiler]],\n },\n }\n : {},\n ),\n sanityFaviconsPlugin({customFaviconsPath, defaultFaviconsPath, staticUrlPath: staticPath}),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({basePath, cwd, importMap, isApp}),\n // Add schema extraction when enabled\n ...(schemaExtraction?.enabled\n ? [\n sanitySchemaExtractionPlugin({\n additionalPatterns: schemaExtraction.watchPatterns,\n configPath,\n enforceRequiredFields: schemaExtraction.enforceRequiredFields,\n outputPath: schemaExtraction.path,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n workspaceName: schemaExtraction.workspace,\n }),\n ]\n : []),\n // Add typegen when enabled\n ...(typegen?.enabled\n ? [\n sanityTypegenPlugin({\n config: typegen,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n }),\n ]\n : []),\n ],\n resolve: {\n dedupe: ['react', 'react-dom', 'sanity', 'styled-components'],\n },\n root: cwd,\n server: {\n host: server?.host,\n port: server?.port || 3333,\n // Only enable strict port for studio,\n // since apps can run on any port\n strictPort: isApp ? false : true,\n\n /**\n * Significantly speed up startup time,\n * and most importantly eliminates the `new dependencies optimized: foobar. optimized dependencies changed. reloading`\n * types of initial reload loops that otherwise happen as vite discovers deps that need to be optimized.\n * This option starts the traversal up front, and warms up the dep tree required to render the userland sanity.config.ts file,\n * and thus avoids frustrating reload loops.\n */\n warmup: {\n clientFiles: ['./.sanity/runtime/app.js'],\n },\n },\n }\n\n if (mode === 'production') {\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n emptyOutDir: false, // Rely on CLI to do this\n minify: minify ? 'esbuild' : false,\n\n rollupOptions: {\n external: createExternalFromImportMap(importMap),\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n },\n onwarn: onRollupWarn,\n },\n }\n }\n\n return viteConfig\n}\n\nfunction onRollupWarn(warning: Rollup.RollupLog, warn: Rollup.LoggingFunction) {\n if (suppressUnusedImport(warning)) {\n return\n }\n\n warn(warning)\n}\n\nfunction suppressUnusedImport(warning: Rollup.RollupLog & {ids?: string[]}): boolean {\n if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') return false\n\n // Suppress:\n // ```\n // \"useDebugValue\" is imported from external module \"react\"…\n // ```\n if (warning.names?.includes('useDebugValue')) {\n warning.names = warning.names.filter((n) => n !== 'useDebugValue')\n if (warning.names.length === 0) return true\n }\n\n // If some library does something unexpected, we suppress since it isn't actionable\n if (warning.ids?.every((id) => id.includes('/node_modules/') || id.includes('\\\\node_modules\\\\')))\n return true\n\n return false\n}\n\n/**\n * Ensure Sanity entry chunk is always loaded\n *\n * @param config - User-modified configuration\n * @returns Merged configuration\n * @internal\n */\nexport async function finalizeViteConfig(config: InlineConfig): Promise<InlineConfig> {\n if (typeof config.build?.rollupOptions?.input !== 'object') {\n throw new TypeError(\n 'Vite config must contain `build.rollupOptions.input`, and it must be an object',\n )\n }\n\n if (!config.root) {\n throw new Error(\n 'Vite config must contain `root` property, and must point to the Sanity root directory',\n )\n }\n\n return mergeConfig(config, {\n build: {\n rollupOptions: {\n input: {\n sanity: path.join(config.root, '.sanity', 'runtime', 'app.js'),\n },\n },\n },\n })\n}\n\n/**\n * Merge user-provided Vite configuration object or function\n *\n * @param defaultConfig - Default configuration object\n * @param userConfig - User-provided configuration object or function\n * @returns Merged configuration\n * @internal\n */\nexport async function extendViteConfigWithUserConfig(\n env: ConfigEnv,\n defaultConfig: InlineConfig,\n userConfig: UserViteConfig,\n): Promise<InlineConfig> {\n let config = defaultConfig\n\n if (typeof userConfig === 'function') {\n debug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n debug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","findProjectRoot","getCliTelemetry","viteReact","debug","readPackageUp","mergeConfig","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","sanitySchemaExtractionPlugin","sanityTypegenPlugin","createExternalFromImportMap","getAppEnvironmentVariables","getStudioEnvironmentVariables","normalizeBasePath","getViteConfig","options","basePath","rawBasePath","cwd","importMap","isApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","sourceMap","typegen","sanityCliPkgPath","dirname","Error","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","jsonEncode","prefix","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_BUILD_TIMESTAMP__","JSON","stringify","Date","now","__SANITY_STAGING__","process","env","SANITY_INTERNAL_ENV","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","babel","generatorOpts","compact","staticUrlPath","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","config","dedupe","root","host","port","strictPort","warmup","clientFiles","assetsDir","emptyOutDir","rollupOptions","external","input","sanity","onwarn","onRollupWarn","warning","warn","suppressUnusedImport","code","names","includes","filter","n","length","ids","every","id","finalizeViteConfig","TypeError","extendViteConfigWithUserConfig","defaultConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAEEC,eAAe,EACfC,eAAe,QAEV,mBAAkB;AACzB,OAAOC,eAAe,uBAAsB;AAE5C,OAAOC,WAAW,QAAO;AACzB,SAAQC,aAAa,QAAO,kBAAiB;AAC7C,SAA2CC,WAAW,QAAoB,OAAM;AAEhF,SAAQC,kBAAkB,QAAO,mDAAkD;AACnF,SAAQC,oBAAoB,QAAO,8CAA6C;AAChF,SAAQC,0BAA0B,QAAO,qDAAoD;AAC7F,SAAQC,4BAA4B,QAAO,gDAA+C;AAC1F,SAAQC,mBAAmB,QAAO,sCAAqC;AACvE,SAAQC,2BAA2B,QAAO,mCAAkC;AAC5E,SACEC,0BAA0B,EAC1BC,6BAA6B,QACxB,qCAAoC;AAC3C,SAAQC,iBAAiB,QAAO,yBAAwB;AAoDxD;;;;CAIC,GACD,OAAO,eAAeC,cAAcC,OAAoB;IACtD,MAAM,EACJC,UAAUC,cAAc,GAAG,EAC3BC,GAAG,EACHC,SAAS,EACTC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,SAAS,EACTC,aAAa,EACbC,gBAAgB,EAChBC,MAAM,EACN,4CAA4C;IAC5CC,YAAYZ,QAAQO,IAAI,KAAK,aAAa,EAC1CM,OAAO,EACR,GAAGb;IAEJ,MAAMC,WAAWH,kBAAkBI;IAEnC,MAAMY,mBAAoB,CAAA,MAAM1B,cAAc;QAACe,KAAK,YAAYY,OAAO;IAAA,EAAC,GAAIhC;IAC5E,IAAI,CAAC+B,kBAAkB;QACrB,MAAM,IAAIE,MAAM;IAClB;IAEA,MAAMC,aAAa,AAAC,CAAA,MAAMjC,gBAAgBmB,IAAG,EAAGpB,IAAI;IAEpD,MAAMmC,qBAAqBnC,KAAKoC,IAAI,CAAChB,KAAK;IAC1C,MAAMiB,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,KAAK,GAAG,OAAO;IACzC;IAEA,mFAAmF;IACnF,IAAIR,QAAQS,GAAG,EAAEC,MAAM,CAACC,KAAOA,GAAGN,QAAQ,CAAC,qBAAqBM,GAAGN,QAAQ,CAAC,sBAC1E,OAAO;IAET,OAAO;AACT;AAEA;;;;;;CAMC,GACD,OAAO,eAAeO,mBAAmB5B,MAAoB;IAC3D,IAAI,OAAOA,OAAOjC,KAAK,EAAE2C,eAAeE,UAAU,UAAU;QAC1D,MAAM,IAAIiB,UACR;IAEJ;IAEA,IAAI,CAAC7B,OAAOE,IAAI,EAAE;QAChB,MAAM,IAAI9C,MACR;IAEJ;IAEA,OAAO3B,YAAYuE,QAAQ;QACzBjC,OAAO;YACL2C,eAAe;gBACbE,OAAO;oBACLC,QAAQ1F,KAAKoC,IAAI,CAACyC,OAAOE,IAAI,EAAE,WAAW,WAAW;gBACvD;YACF;QACF;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAe4B,+BACpBjD,GAAc,EACdkD,aAA2B,EAC3BC,UAA0B;IAE1B,IAAIhC,SAAS+B;IAEb,IAAI,OAAOC,eAAe,YAAY;QACpCzG,MAAM;QACNyE,SAAS,MAAMgC,WAAWhC,QAAQnB;IACpC,OAAO,IAAI,OAAOmD,eAAe,UAAU;QACzCzG,MAAM;QACNyE,SAASvE,YAAYuE,QAAQgC;IAC/B;IAEA,OAAOhC;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/actions/build/renderDocumentWorker/components/GlobalErrorHandler.tsx"],"sourcesContent":["import {type JSX} from 'react'\n\nconst errorHandlerScript = `\n;(function () {\n var _caughtErrors = []\n\n var errorChannel = (function () {\n var subscribers = []\n\n function publish(msg) {\n for (var i = 0; i < subscribers.length; i += 1) {\n subscribers[i](msg)\n }\n }\n\n function subscribe(subscriber) {\n subscribers.push(subscriber)\n\n return function () {\n var idx = subscribers.indexOf(subscriber)\n\n if (idx > -1) {\n subscribers.splice(idx, 1)\n }\n }\n }\n\n return {publish, subscribe, subscribers}\n })()\n\n // NOTE: Store the error channel instance in the global scope so that the application can\n // access it and subscribe to errors.\n window.__sanityErrorChannel = {\n subscribe: errorChannel.subscribe,\n }\n\n function _nextTick(callback) {\n setTimeout(callback, 0)\n }\n\n function _handleError(error, params) {\n _nextTick(function () {\n // - If there are error channel subscribers, then we notify them (no console error).\n // - If there are no subscribers, then we log the error to the console and render the error overlay.\n if (errorChannel.subscribers.length) {\n errorChannel.publish({error, params})\n } else {\n console.error(error)\n\n _renderErrorOverlay(error, params)\n }\n })\n }\n\n var ERROR_BOX_STYLE = [\n 'background: #fff',\n 'border-radius: 6px',\n 'box-sizing: border-box',\n 'color: #121923',\n 'flex: 1',\n \"font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue','Liberation Sans',Helvetica,Arial,system-ui,sans-serif\",\n 'font-size: 16px',\n 'line-height: 21px',\n 'margin: 0 auto',\n 'max-width: 960px',\n 'overflow: auto',\n 'padding: 20px',\n 'width: 100%',\n ].join(';')\n\n var ERROR_CODE_STYLE = [\n 'color: #972E2A',\n \"font-family: -apple-system-ui-monospace, 'SF Mono', Menlo, Monaco, Consolas, monospace\",\n 'font-size: 13px',\n 'line-height: 17px',\n 'margin: 0',\n ].join(';')\n\n function _renderErrorOverlay(error, params) {\n var errorElement = document.querySelector('#__sanityError') || document.createElement('div')\n var colno = params.event.colno\n var lineno = params.event.lineno\n var filename = params.event.filename\n\n errorElement.id = '__sanityError'\n errorElement.innerHTML = [\n '<div style=\"' + ERROR_BOX_STYLE + '\">',\n '<div style=\"font-weight: 700;\">Uncaught error: ' + error.message + '</div>',\n '<div style=\"color: #515E72; font-size: 13px; line-height: 17px; margin: 10px 0;\">' +\n filename +\n ':' +\n lineno +\n ':' +\n colno +\n '</div>',\n '<pre style=\"' + ERROR_CODE_STYLE + '\">' + error.stack + '</pre>',\n '</div>',\n ].join('')\n\n errorElement.style.position = 'fixed'\n errorElement.style.zIndex = 1000000\n errorElement.style.top = 0\n errorElement.style.left = 0\n errorElement.style.right = 0\n errorElement.style.bottom = 0\n errorElement.style.padding = '20px'\n errorElement.style.background = 'rgba(16,17,18,0.66)'\n errorElement.style.display = 'flex'\n errorElement.style.alignItems = 'center'\n errorElement.style.justifyContent = 'center'\n\n document.body.appendChild(errorElement)\n }\n\n // NOTE:\n // Yes – we're attaching 2 error listeners below 👀\n // This is because React makes the same error throw twice (in development mode).\n // See: https://github.com/facebook/react/issues/10384\n\n // Error listener #1\n window.onerror = function (event, source, lineno, colno, error) {\n _nextTick(function () {\n if (_caughtErrors.indexOf(error) !== -1) return\n\n _caughtErrors.push(error)\n\n _handleError(error, {\n event,\n lineno,\n colno,\n source,\n })\n\n _nextTick(function () {\n var idx = _caughtErrors.indexOf(error)\n\n if (idx > -1) _caughtErrors.splice(idx, 1)\n })\n })\n\n // IMPORTANT: this callback must return \\`true\\` to prevent the error from being rendered in\n // the browser’s console.\n return true\n }\n\n // Error listener #2\n window.addEventListener('error', function (event) {\n if (_caughtErrors.indexOf(event.error) !== -1) return true\n\n _caughtErrors.push(event.error)\n\n _handleError(event.error, {\n event,\n lineno: event.lineno,\n colno: event.colno,\n })\n\n _nextTick(function () {\n _nextTick(function () {\n var idx = _caughtErrors.indexOf(event.error)\n\n if (idx > -1) _caughtErrors.splice(idx, 1)\n })\n })\n\n return true\n })\n})()\n`\n\n/** @internal */\nexport function GlobalErrorHandler(): JSX.Element {\n return <script dangerouslySetInnerHTML={{__html: errorHandlerScript}} />\n}\n"],"names":["errorHandlerScript","GlobalErrorHandler","script","dangerouslySetInnerHTML","__html"],"mappings":";AAEA,MAAMA,qBAAqB,CAAC
|
|
1
|
+
{"version":3,"sources":["../../../../../src/actions/build/renderDocumentWorker/components/GlobalErrorHandler.tsx"],"sourcesContent":["import {type JSX} from 'react'\n\nconst errorHandlerScript = `\n;(function () {\n var _caughtErrors = []\n\n var errorChannel = (function () {\n var subscribers = []\n\n function publish(msg) {\n for (var i = 0; i < subscribers.length; i += 1) {\n subscribers[i](msg)\n }\n }\n\n function subscribe(subscriber) {\n subscribers.push(subscriber)\n\n return function () {\n var idx = subscribers.indexOf(subscriber)\n\n if (idx > -1) {\n subscribers.splice(idx, 1)\n }\n }\n }\n\n return {publish, subscribe, subscribers}\n })()\n\n // NOTE: Store the error channel instance in the global scope so that the application can\n // access it and subscribe to errors.\n window.__sanityErrorChannel = {\n subscribe: errorChannel.subscribe,\n }\n\n function _nextTick(callback) {\n setTimeout(callback, 0)\n }\n\n function _handleError(error, params) {\n _nextTick(function () {\n // - If there are error channel subscribers, then we notify them (no console error).\n // - If there are no subscribers, then we log the error to the console and render the error overlay.\n if (errorChannel.subscribers.length) {\n errorChannel.publish({error, params})\n } else {\n console.error(error)\n\n _renderErrorOverlay(error, params)\n }\n })\n }\n\n var ERROR_BOX_STYLE = [\n 'background: #fff',\n 'border-radius: 6px',\n 'box-sizing: border-box',\n 'color: #121923',\n 'flex: 1',\n \"font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue','Liberation Sans',Helvetica,Arial,system-ui,sans-serif\",\n 'font-size: 16px',\n 'line-height: 21px',\n 'margin: 0 auto',\n 'max-width: 960px',\n 'max-height: 90dvh',\n 'overflow: auto',\n 'padding: 20px',\n 'width: 100%',\n ].join(';')\n\n var ERROR_CODE_STYLE = [\n 'color: #972E2A',\n \"font-family: -apple-system-ui-monospace, 'SF Mono', Menlo, Monaco, Consolas, monospace\",\n 'font-size: 13px',\n 'line-height: 17px',\n 'margin: 0',\n ].join(';')\n\n function _renderErrorOverlay(error, params) {\n var errorElement = document.querySelector('#__sanityError') || document.createElement('div')\n var colno = params.event.colno\n var lineno = params.event.lineno\n var filename = params.event.filename\n\n errorElement.id = '__sanityError'\n errorElement.innerHTML = [\n '<div style=\"' + ERROR_BOX_STYLE + '\">',\n '<div style=\"font-weight: 700;\">Uncaught error: ' + error.message + '</div>',\n '<div style=\"color: #515E72; font-size: 13px; line-height: 17px; margin: 10px 0;\">' +\n filename +\n ':' +\n lineno +\n ':' +\n colno +\n '</div>',\n '<pre style=\"' + ERROR_CODE_STYLE + '\">' + error.stack + '</pre>',\n '</div>',\n ].join('')\n\n errorElement.style.position = 'fixed'\n errorElement.style.zIndex = 1000000\n errorElement.style.top = 0\n errorElement.style.left = 0\n errorElement.style.right = 0\n errorElement.style.bottom = 0\n errorElement.style.padding = '20px'\n errorElement.style.background = 'rgba(16,17,18,0.66)'\n errorElement.style.display = 'flex'\n errorElement.style.alignItems = 'center'\n errorElement.style.justifyContent = 'center'\n\n document.body.appendChild(errorElement)\n }\n\n // NOTE:\n // Yes – we're attaching 2 error listeners below 👀\n // This is because React makes the same error throw twice (in development mode).\n // See: https://github.com/facebook/react/issues/10384\n\n // Error listener #1\n window.onerror = function (event, source, lineno, colno, error) {\n _nextTick(function () {\n if (_caughtErrors.indexOf(error) !== -1) return\n\n _caughtErrors.push(error)\n\n _handleError(error, {\n event,\n lineno,\n colno,\n source,\n })\n\n _nextTick(function () {\n var idx = _caughtErrors.indexOf(error)\n\n if (idx > -1) _caughtErrors.splice(idx, 1)\n })\n })\n\n // IMPORTANT: this callback must return \\`true\\` to prevent the error from being rendered in\n // the browser’s console.\n return true\n }\n\n // Error listener #2\n window.addEventListener('error', function (event) {\n if (_caughtErrors.indexOf(event.error) !== -1) return true\n\n _caughtErrors.push(event.error)\n\n _handleError(event.error, {\n event,\n lineno: event.lineno,\n colno: event.colno,\n })\n\n _nextTick(function () {\n _nextTick(function () {\n var idx = _caughtErrors.indexOf(event.error)\n\n if (idx > -1) _caughtErrors.splice(idx, 1)\n })\n })\n\n return true\n })\n})()\n`\n\n/** @internal */\nexport function GlobalErrorHandler(): JSX.Element {\n return <script dangerouslySetInnerHTML={{__html: errorHandlerScript}} />\n}\n"],"names":["errorHandlerScript","GlobalErrorHandler","script","dangerouslySetInnerHTML","__html"],"mappings":";AAEA,MAAMA,qBAAqB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuK5B,CAAC;AAED,cAAc,GACd,OAAO,SAASC;IACd,qBAAO,KAACC;QAAOC,yBAAyB;YAACC,QAAQJ;QAAkB;;AACrE"}
|
|
@@ -2,6 +2,7 @@ import fs from 'node:fs/promises';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { tryFindStudioConfigPath } from '@sanity/cli-core';
|
|
4
4
|
import { watch as chokidarWatch } from 'chokidar';
|
|
5
|
+
import { toForwardSlashes } from '../../util/toForwardSlashes.js';
|
|
5
6
|
import { buildDebug } from './buildDebug.js';
|
|
6
7
|
import { decorateIndexWithAutoGeneratedWarning } from './decorateIndexWithAutoGeneratedWarning.js';
|
|
7
8
|
import { decorateIndexWithBridgeScript } from './decorateIndexWithBridgeScript.js';
|
|
@@ -28,7 +29,7 @@ import { renderDocument } from './renderDocument.js';
|
|
|
28
29
|
isApp,
|
|
29
30
|
props: {
|
|
30
31
|
basePath: basePath || '/',
|
|
31
|
-
entryPath: `/${path.relative(cwd, path.join(runtimeDir, 'app.js'))}`
|
|
32
|
+
entryPath: `/${toForwardSlashes(path.relative(cwd, path.join(runtimeDir, 'app.js')))}`
|
|
32
33
|
},
|
|
33
34
|
studioRootPath: cwd
|
|
34
35
|
})));
|
|
@@ -44,9 +45,9 @@ import { renderDocument } from './renderDocument.js';
|
|
|
44
45
|
let relativeConfigLocation = null;
|
|
45
46
|
if (!isApp) {
|
|
46
47
|
const studioConfigPath = await tryFindStudioConfigPath(cwd);
|
|
47
|
-
relativeConfigLocation = studioConfigPath ? path.relative(runtimeDir, studioConfigPath) : null;
|
|
48
|
+
relativeConfigLocation = studioConfigPath ? toForwardSlashes(path.relative(runtimeDir, studioConfigPath)) : null;
|
|
48
49
|
}
|
|
49
|
-
const relativeEntry =
|
|
50
|
+
const relativeEntry = toForwardSlashes(path.relative(runtimeDir, path.resolve(cwd, entry || './src/App')));
|
|
50
51
|
const appJsContent = getEntryModule({
|
|
51
52
|
basePath,
|
|
52
53
|
entry: relativeEntry,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/build/writeSanityRuntime.ts"],"sourcesContent":["import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {tryFindStudioConfigPath} from '@sanity/cli-core'\nimport {watch as chokidarWatch, type FSWatcher} from 'chokidar'\n\nimport {buildDebug} from './buildDebug.js'\nimport {decorateIndexWithAutoGeneratedWarning} from './decorateIndexWithAutoGeneratedWarning.js'\nimport {decorateIndexWithBridgeScript} from './decorateIndexWithBridgeScript.js'\nimport {getEntryModule} from './getEntryModule.js'\nimport {getPossibleDocumentComponentLocations} from './getPossibleDocumentComponentLocations.js'\nimport {renderDocument} from './renderDocument.js'\n\ninterface RuntimeOptions {\n cwd: string\n reactStrictMode: boolean\n watch: boolean\n\n basePath?: string\n entry?: string\n isApp?: boolean\n}\n\n/**\n * Generates the `.sanity/runtime` directory, and optionally watches for custom\n * document files, rebuilding when they change\n *\n * @param options - Current working directory (Sanity root dir), and whether or not to watch\n * @returns A watcher instance if watch is enabled, undefined otherwise\n * @internal\n */\nexport async function writeSanityRuntime(options: RuntimeOptions): Promise<FSWatcher | undefined> {\n const {basePath, cwd, entry, isApp, reactStrictMode, watch} = options\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n\n buildDebug('Making runtime directory')\n await fs.mkdir(runtimeDir, {recursive: true})\n\n async function renderAndWriteDocument() {\n buildDebug('Rendering document template')\n const indexHtml = decorateIndexWithBridgeScript(\n decorateIndexWithAutoGeneratedWarning(\n await renderDocument({\n isApp,\n props: {\n basePath: basePath || '/',\n entryPath: `/${path.relative(cwd, path.join(runtimeDir, 'app.js'))}`,\n },\n studioRootPath: cwd,\n }),\n ),\n )\n\n buildDebug('Writing index.html to runtime directory')\n await fs.writeFile(path.join(runtimeDir, 'index.html'), indexHtml)\n }\n\n let watcher: FSWatcher | undefined\n\n if (watch) {\n watcher = chokidarWatch(getPossibleDocumentComponentLocations(cwd)).on('all', () =>\n renderAndWriteDocument(),\n )\n }\n\n await renderAndWriteDocument()\n\n buildDebug('Writing app.js to runtime directory')\n let relativeConfigLocation: string | null = null\n if (!isApp) {\n const studioConfigPath = await tryFindStudioConfigPath(cwd)\n relativeConfigLocation = studioConfigPath
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/build/writeSanityRuntime.ts"],"sourcesContent":["import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {tryFindStudioConfigPath} from '@sanity/cli-core'\nimport {watch as chokidarWatch, type FSWatcher} from 'chokidar'\n\nimport {toForwardSlashes} from '../../util/toForwardSlashes.js'\nimport {buildDebug} from './buildDebug.js'\nimport {decorateIndexWithAutoGeneratedWarning} from './decorateIndexWithAutoGeneratedWarning.js'\nimport {decorateIndexWithBridgeScript} from './decorateIndexWithBridgeScript.js'\nimport {getEntryModule} from './getEntryModule.js'\nimport {getPossibleDocumentComponentLocations} from './getPossibleDocumentComponentLocations.js'\nimport {renderDocument} from './renderDocument.js'\n\ninterface RuntimeOptions {\n cwd: string\n reactStrictMode: boolean\n watch: boolean\n\n basePath?: string\n entry?: string\n isApp?: boolean\n}\n\n/**\n * Generates the `.sanity/runtime` directory, and optionally watches for custom\n * document files, rebuilding when they change\n *\n * @param options - Current working directory (Sanity root dir), and whether or not to watch\n * @returns A watcher instance if watch is enabled, undefined otherwise\n * @internal\n */\nexport async function writeSanityRuntime(options: RuntimeOptions): Promise<FSWatcher | undefined> {\n const {basePath, cwd, entry, isApp, reactStrictMode, watch} = options\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n\n buildDebug('Making runtime directory')\n await fs.mkdir(runtimeDir, {recursive: true})\n\n async function renderAndWriteDocument() {\n buildDebug('Rendering document template')\n const indexHtml = decorateIndexWithBridgeScript(\n decorateIndexWithAutoGeneratedWarning(\n await renderDocument({\n isApp,\n props: {\n basePath: basePath || '/',\n entryPath: `/${toForwardSlashes(path.relative(cwd, path.join(runtimeDir, 'app.js')))}`,\n },\n studioRootPath: cwd,\n }),\n ),\n )\n\n buildDebug('Writing index.html to runtime directory')\n await fs.writeFile(path.join(runtimeDir, 'index.html'), indexHtml)\n }\n\n let watcher: FSWatcher | undefined\n\n if (watch) {\n watcher = chokidarWatch(getPossibleDocumentComponentLocations(cwd)).on('all', () =>\n renderAndWriteDocument(),\n )\n }\n\n await renderAndWriteDocument()\n\n buildDebug('Writing app.js to runtime directory')\n let relativeConfigLocation: string | null = null\n if (!isApp) {\n const studioConfigPath = await tryFindStudioConfigPath(cwd)\n relativeConfigLocation = studioConfigPath\n ? toForwardSlashes(path.relative(runtimeDir, studioConfigPath))\n : null\n }\n\n const relativeEntry = toForwardSlashes(\n path.relative(runtimeDir, path.resolve(cwd, entry || './src/App')),\n )\n const appJsContent = getEntryModule({\n basePath,\n entry: relativeEntry,\n isApp,\n reactStrictMode,\n relativeConfigLocation,\n })\n await fs.writeFile(path.join(runtimeDir, 'app.js'), appJsContent)\n\n return watcher\n}\n"],"names":["fs","path","tryFindStudioConfigPath","watch","chokidarWatch","toForwardSlashes","buildDebug","decorateIndexWithAutoGeneratedWarning","decorateIndexWithBridgeScript","getEntryModule","getPossibleDocumentComponentLocations","renderDocument","writeSanityRuntime","options","basePath","cwd","entry","isApp","reactStrictMode","runtimeDir","join","mkdir","recursive","renderAndWriteDocument","indexHtml","props","entryPath","relative","studioRootPath","writeFile","watcher","on","relativeConfigLocation","studioConfigPath","relativeEntry","resolve","appJsContent"],"mappings":"AAAA,OAAOA,QAAQ,mBAAkB;AACjC,OAAOC,UAAU,YAAW;AAE5B,SAAQC,uBAAuB,QAAO,mBAAkB;AACxD,SAAQC,SAASC,aAAa,QAAuB,WAAU;AAE/D,SAAQC,gBAAgB,QAAO,iCAAgC;AAC/D,SAAQC,UAAU,QAAO,kBAAiB;A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Ae;QAClCK;QACAE,OAAOkB;QACPjB;QACAC;QACAc;IACF;IACA,MAAMhC,GAAG6B,SAAS,CAAC5B,KAAKmB,IAAI,CAACD,YAAY,WAAWiB;IAEpD,OAAON;AACT"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { getSanityUrl, subdebug } from '@sanity/cli-core';
|
|
2
|
+
const debug = subdebug('dev:getDashboardAppURL');
|
|
3
|
+
const DEFAULT_TIMEOUT = 5000;
|
|
4
|
+
const getDefaultDashboardURL = ({ organizationId, url })=>{
|
|
5
|
+
return `${getSanityUrl()}/@${organizationId}?${new URLSearchParams({
|
|
6
|
+
dev: url
|
|
7
|
+
}).toString()}`;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Gets the dashboard URL from API or uses the default dashboard URL
|
|
11
|
+
*/ export const getDashboardAppURL = async ({ httpHost = 'localhost', httpPort = 3333, organizationId })=>{
|
|
12
|
+
const url = `http://${httpHost}:${httpPort}`;
|
|
13
|
+
const abortController = new AbortController();
|
|
14
|
+
// Wait for 5 seconds before aborting the request
|
|
15
|
+
const timer = setTimeout(()=>abortController.abort(), DEFAULT_TIMEOUT);
|
|
16
|
+
try {
|
|
17
|
+
const queryParams = new URLSearchParams({
|
|
18
|
+
organizationId,
|
|
19
|
+
url
|
|
20
|
+
});
|
|
21
|
+
const res = await globalThis.fetch(`${getSanityUrl()}/api/dashboard/mode/development/resolve-url?${queryParams.toString()}`, {
|
|
22
|
+
signal: abortController.signal
|
|
23
|
+
});
|
|
24
|
+
if (!res.ok) {
|
|
25
|
+
debug(`Failed to fetch dashboard URL: ${res.statusText}`);
|
|
26
|
+
return getDefaultDashboardURL({
|
|
27
|
+
organizationId,
|
|
28
|
+
url
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
const body = await res.json();
|
|
32
|
+
// <dashboard-app-url>/<orgniazationId>?dev=<dev-server-url>
|
|
33
|
+
return body?.url ?? getDefaultDashboardURL({
|
|
34
|
+
organizationId,
|
|
35
|
+
url
|
|
36
|
+
});
|
|
37
|
+
} catch (err) {
|
|
38
|
+
debug(`Failed to fetch dashboard URL: ${err instanceof Error ? err.message : String(err)}`);
|
|
39
|
+
return getDefaultDashboardURL({
|
|
40
|
+
organizationId,
|
|
41
|
+
url
|
|
42
|
+
});
|
|
43
|
+
} finally{
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=getDashboardAppUrl.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/getDashboardAppUrl.ts"],"sourcesContent":["import {getSanityUrl, subdebug} from '@sanity/cli-core'\n\nconst debug = subdebug('dev:getDashboardAppURL')\n\nconst DEFAULT_TIMEOUT = 5000\n\nconst getDefaultDashboardURL = ({\n organizationId,\n url,\n}: {\n organizationId: string\n url: string\n}): string => {\n return `${getSanityUrl()}/@${organizationId}?${new URLSearchParams({\n dev: url,\n }).toString()}`\n}\n\n/**\n * Gets the dashboard URL from API or uses the default dashboard URL\n */\nexport const getDashboardAppURL = async ({\n httpHost = 'localhost',\n httpPort = 3333,\n organizationId,\n}: {\n httpHost?: string\n httpPort?: number\n organizationId: string\n}): Promise<string> => {\n const url = `http://${httpHost}:${httpPort}`\n\n const abortController = new AbortController()\n // Wait for 5 seconds before aborting the request\n const timer = setTimeout(() => abortController.abort(), DEFAULT_TIMEOUT)\n try {\n const queryParams = new URLSearchParams({\n organizationId,\n url,\n })\n\n const res = await globalThis.fetch(\n `${getSanityUrl()}/api/dashboard/mode/development/resolve-url?${queryParams.toString()}`,\n {\n signal: abortController.signal,\n },\n )\n\n if (!res.ok) {\n debug(`Failed to fetch dashboard URL: ${res.statusText}`)\n return getDefaultDashboardURL({organizationId, url})\n }\n\n const body = await res.json()\n // <dashboard-app-url>/<orgniazationId>?dev=<dev-server-url>\n return body?.url ?? getDefaultDashboardURL({organizationId, url})\n } catch (err) {\n debug(`Failed to fetch dashboard URL: ${err instanceof Error ? err.message : String(err)}`)\n return getDefaultDashboardURL({organizationId, url})\n } finally {\n clearTimeout(timer)\n }\n}\n"],"names":["getSanityUrl","subdebug","debug","DEFAULT_TIMEOUT","getDefaultDashboardURL","organizationId","url","URLSearchParams","dev","toString","getDashboardAppURL","httpHost","httpPort","abortController","AbortController","timer","setTimeout","abort","queryParams","res","globalThis","fetch","signal","ok","statusText","body","json","err","Error","message","String","clearTimeout"],"mappings":"AAAA,SAAQA,YAAY,EAAEC,QAAQ,QAAO,mBAAkB;AAEvD,MAAMC,QAAQD,SAAS;AAEvB,MAAME,kBAAkB;AAExB,MAAMC,yBAAyB,CAAC,EAC9BC,cAAc,EACdC,GAAG,EAIJ;IACC,OAAO,GAAGN,eAAe,EAAE,EAAEK,eAAe,CAAC,EAAE,IAAIE,gBAAgB;QACjEC,KAAKF;IACP,GAAGG,QAAQ,IAAI;AACjB;AAEA;;CAEC,GACD,OAAO,MAAMC,qBAAqB,OAAO,EACvCC,WAAW,WAAW,EACtBC,WAAW,IAAI,EACfP,cAAc,EAKf;IACC,MAAMC,MAAM,CAAC,OAAO,EAAEK,SAAS,CAAC,EAAEC,UAAU;IAE5C,MAAMC,kBAAkB,IAAIC;IAC5B,iDAAiD;IACjD,MAAMC,QAAQC,WAAW,IAAMH,gBAAgBI,KAAK,IAAId;IACxD,IAAI;QACF,MAAMe,cAAc,IAAIX,gBAAgB;YACtCF;YACAC;QACF;QAEA,MAAMa,MAAM,MAAMC,WAAWC,KAAK,CAChC,GAAGrB,eAAe,4CAA4C,EAAEkB,YAAYT,QAAQ,IAAI,EACxF;YACEa,QAAQT,gBAAgBS,MAAM;QAChC;QAGF,IAAI,CAACH,IAAII,EAAE,EAAE;YACXrB,MAAM,CAAC,+BAA+B,EAAEiB,IAAIK,UAAU,EAAE;YACxD,OAAOpB,uBAAuB;gBAACC;gBAAgBC;YAAG;QACpD;QAEA,MAAMmB,OAAO,MAAMN,IAAIO,IAAI;QAC3B,4DAA4D;QAC5D,OAAOD,MAAMnB,OAAOF,uBAAuB;YAACC;YAAgBC;QAAG;IACjE,EAAE,OAAOqB,KAAK;QACZzB,MAAM,CAAC,+BAA+B,EAAEyB,eAAeC,QAAQD,IAAIE,OAAO,GAAGC,OAAOH,MAAM;QAC1F,OAAOvB,uBAAuB;YAACC;YAAgBC;QAAG;IACpD,SAAU;QACRyB,aAAahB;IACf;AACF,EAAC"}
|
|
@@ -24,7 +24,8 @@ export function getDevServerConfig({ cliConfig, flags, output, workDir }) {
|
|
|
24
24
|
...baseConfig,
|
|
25
25
|
reactCompiler: cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,
|
|
26
26
|
reactStrictMode,
|
|
27
|
-
staticPath: path.join(workDir, 'static')
|
|
27
|
+
staticPath: path.join(workDir, 'static'),
|
|
28
|
+
typegen: cliConfig?.typegen
|
|
28
29
|
};
|
|
29
30
|
}
|
|
30
31
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/getDevServerConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type CliConfig, getSanityEnvVar, type Output} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {type DevServerOptions} from '../../server/devServer.js'\nimport {getSharedServerConfig} from '../../util/getSharedServerConfig.js'\nimport {type DevFlags} from './types.js'\n\nexport function getDevServerConfig({\n cliConfig,\n flags,\n output,\n workDir,\n}: {\n cliConfig?: CliConfig\n flags: DevFlags\n output: Output\n workDir: string\n}): Omit<DevServerOptions, 'spinner'> {\n const configSpinner = spinner('Checking configuration files...')\n\n const baseConfig = getSharedServerConfig({\n cliConfig,\n flags: {\n host: flags.host,\n port: flags.port,\n },\n workDir,\n })\n\n configSpinner.succeed()\n\n const isApp = cliConfig && 'app' in cliConfig\n const env = process.env\n const reactStrictMode = env.SANITY_STUDIO_REACT_STRICT_MODE\n ? env.SANITY_STUDIO_REACT_STRICT_MODE === 'true'\n : Boolean(cliConfig?.reactStrictMode)\n\n const envBasePath = getSanityEnvVar('BASEPATH', isApp ?? false)\n if (envBasePath && cliConfig?.project?.basePath) {\n output.warn(\n `Overriding configured base path (${cliConfig.project.basePath}) with value from environment variable (${envBasePath})`,\n )\n }\n\n return {\n ...baseConfig,\n reactCompiler: cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,\n reactStrictMode,\n staticPath: path.join(workDir, 'static'),\n }\n}\n"],"names":["path","getSanityEnvVar","spinner","getSharedServerConfig","getDevServerConfig","cliConfig","flags","output","workDir","configSpinner","baseConfig","host","port","succeed","isApp","env","process","reactStrictMode","SANITY_STUDIO_REACT_STRICT_MODE","Boolean","envBasePath","project","basePath","warn","reactCompiler","undefined","staticPath","join"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAwBC,eAAe,QAAoB,mBAAkB;AAC7E,SAAQC,OAAO,QAAO,sBAAqB;AAG3C,SAAQC,qBAAqB,QAAO,sCAAqC;AAGzE,OAAO,SAASC,mBAAmB,EACjCC,SAAS,EACTC,KAAK,EACLC,MAAM,EACNC,OAAO,EAMR;IACC,MAAMC,gBAAgBP,QAAQ;IAE9B,MAAMQ,aAAaP,sBAAsB;QACvCE;QACAC,OAAO;YACLK,MAAML,MAAMK,IAAI;YAChBC,MAAMN,MAAMM,IAAI;QAClB;QACAJ;IACF;IAEAC,cAAcI,OAAO;IAErB,MAAMC,QAAQT,aAAa,SAASA;IACpC,MAAMU,MAAMC,QAAQD,GAAG;IACvB,MAAME,kBAAkBF,IAAIG,+BAA+B,GACvDH,IAAIG,+BAA+B,KAAK,SACxCC,QAAQd,WAAWY;IAEvB,MAAMG,cAAcnB,gBAAgB,YAAYa,SAAS;IACzD,IAAIM,eAAef,WAAWgB,SAASC,UAAU;QAC/Cf,OAAOgB,IAAI,CACT,CAAC,iCAAiC,EAAElB,UAAUgB,OAAO,CAACC,QAAQ,CAAC,wCAAwC,EAAEF,YAAY,CAAC,CAAC;IAE3H;IAEA,OAAO;QACL,GAAGV,UAAU;QACbc,eAAenB,aAAa,mBAAmBA,YAAYA,UAAUmB,aAAa,GAAGC;QACrFR;QACAS,YAAY1B,KAAK2B,IAAI,CAACnB,SAAS;
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/getDevServerConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type CliConfig, getSanityEnvVar, type Output} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {type DevServerOptions} from '../../server/devServer.js'\nimport {getSharedServerConfig} from '../../util/getSharedServerConfig.js'\nimport {type DevFlags} from './types.js'\n\nexport function getDevServerConfig({\n cliConfig,\n flags,\n output,\n workDir,\n}: {\n cliConfig?: CliConfig\n flags: DevFlags\n output: Output\n workDir: string\n}): Omit<DevServerOptions, 'spinner'> {\n const configSpinner = spinner('Checking configuration files...')\n\n const baseConfig = getSharedServerConfig({\n cliConfig,\n flags: {\n host: flags.host,\n port: flags.port,\n },\n workDir,\n })\n\n configSpinner.succeed()\n\n const isApp = cliConfig && 'app' in cliConfig\n const env = process.env\n const reactStrictMode = env.SANITY_STUDIO_REACT_STRICT_MODE\n ? env.SANITY_STUDIO_REACT_STRICT_MODE === 'true'\n : Boolean(cliConfig?.reactStrictMode)\n\n const envBasePath = getSanityEnvVar('BASEPATH', isApp ?? false)\n if (envBasePath && cliConfig?.project?.basePath) {\n output.warn(\n `Overriding configured base path (${cliConfig.project.basePath}) with value from environment variable (${envBasePath})`,\n )\n }\n\n return {\n ...baseConfig,\n reactCompiler: cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,\n reactStrictMode,\n staticPath: path.join(workDir, 'static'),\n typegen: cliConfig?.typegen,\n }\n}\n"],"names":["path","getSanityEnvVar","spinner","getSharedServerConfig","getDevServerConfig","cliConfig","flags","output","workDir","configSpinner","baseConfig","host","port","succeed","isApp","env","process","reactStrictMode","SANITY_STUDIO_REACT_STRICT_MODE","Boolean","envBasePath","project","basePath","warn","reactCompiler","undefined","staticPath","join","typegen"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAwBC,eAAe,QAAoB,mBAAkB;AAC7E,SAAQC,OAAO,QAAO,sBAAqB;AAG3C,SAAQC,qBAAqB,QAAO,sCAAqC;AAGzE,OAAO,SAASC,mBAAmB,EACjCC,SAAS,EACTC,KAAK,EACLC,MAAM,EACNC,OAAO,EAMR;IACC,MAAMC,gBAAgBP,QAAQ;IAE9B,MAAMQ,aAAaP,sBAAsB;QACvCE;QACAC,OAAO;YACLK,MAAML,MAAMK,IAAI;YAChBC,MAAMN,MAAMM,IAAI;QAClB;QACAJ;IACF;IAEAC,cAAcI,OAAO;IAErB,MAAMC,QAAQT,aAAa,SAASA;IACpC,MAAMU,MAAMC,QAAQD,GAAG;IACvB,MAAME,kBAAkBF,IAAIG,+BAA+B,GACvDH,IAAIG,+BAA+B,KAAK,SACxCC,QAAQd,WAAWY;IAEvB,MAAMG,cAAcnB,gBAAgB,YAAYa,SAAS;IACzD,IAAIM,eAAef,WAAWgB,SAASC,UAAU;QAC/Cf,OAAOgB,IAAI,CACT,CAAC,iCAAiC,EAAElB,UAAUgB,OAAO,CAACC,QAAQ,CAAC,wCAAwC,EAAEF,YAAY,CAAC,CAAC;IAE3H;IAEA,OAAO;QACL,GAAGV,UAAU;QACbc,eAAenB,aAAa,mBAAmBA,YAAYA,UAAUmB,aAAa,GAAGC;QACrFR;QACAS,YAAY1B,KAAK2B,IAAI,CAACnB,SAAS;QAC/BoB,SAASvB,WAAWuB;IACtB;AACF"}
|
|
@@ -2,7 +2,7 @@ import { styleText } from 'node:util';
|
|
|
2
2
|
import { startDevServer } from '../../server/devServer.js';
|
|
3
3
|
import { gracefulServerDeath } from '../../server/gracefulServerDeath.js';
|
|
4
4
|
import { devDebug } from './devDebug.js';
|
|
5
|
-
import {
|
|
5
|
+
import { getDashboardAppURL } from './getDashboardAppUrl.js';
|
|
6
6
|
import { getDevServerConfig } from './getDevServerConfig.js';
|
|
7
7
|
export async function startAppDevServer(options) {
|
|
8
8
|
const { cliConfig, flags, output, workDir } = options;
|
|
@@ -34,7 +34,7 @@ export async function startAppDevServer(options) {
|
|
|
34
34
|
});
|
|
35
35
|
const { port } = server.config.server;
|
|
36
36
|
const httpHost = config.httpHost || 'localhost';
|
|
37
|
-
const
|
|
37
|
+
const dashboardAppUrl = await getDashboardAppURL({
|
|
38
38
|
httpHost,
|
|
39
39
|
httpPort: port,
|
|
40
40
|
organizationId
|
|
@@ -44,7 +44,7 @@ export async function startAppDevServer(options) {
|
|
|
44
44
|
output.log(styleText([
|
|
45
45
|
'blue',
|
|
46
46
|
'underline'
|
|
47
|
-
],
|
|
47
|
+
], dashboardAppUrl));
|
|
48
48
|
return {
|
|
49
49
|
close
|
|
50
50
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/startAppDevServer.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {startDevServer} from '../../server/devServer.js'\nimport {gracefulServerDeath} from '../../server/gracefulServerDeath.js'\nimport {devDebug} from './devDebug.js'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/startAppDevServer.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {startDevServer} from '../../server/devServer.js'\nimport {gracefulServerDeath} from '../../server/gracefulServerDeath.js'\nimport {devDebug} from './devDebug.js'\nimport {getDashboardAppURL} from './getDashboardAppUrl.js'\nimport {getDevServerConfig} from './getDevServerConfig.js'\nimport {type DevActionOptions} from './types.js'\n\nexport async function startAppDevServer(\n options: DevActionOptions,\n): Promise<{close?: () => Promise<void>}> {\n const {cliConfig, flags, output, workDir} = options\n\n if (!flags['load-in-dashboard']) {\n output.warn(`Apps cannot run without the Sanity dashboard`)\n output.warn(`Starting dev server with the --load-in-dashboard flag set to true`)\n }\n\n let organizationId: string | undefined\n if (cliConfig && 'app' in cliConfig && cliConfig.app?.organizationId) {\n organizationId = cliConfig.app.organizationId\n }\n\n if (!organizationId) {\n output.error(`Apps require an organization ID (orgId) specified in your sanity.cli.ts file`, {\n exit: 1,\n })\n return {}\n }\n\n const config = getDevServerConfig({cliConfig, flags, output, workDir})\n\n try {\n output.log('Starting dev server')\n\n const {close, server} = await startDevServer({...config, isApp: true})\n\n const {port} = server.config.server\n const httpHost = config.httpHost || 'localhost'\n\n const dashboardAppUrl = await getDashboardAppURL({\n httpHost,\n httpPort: port,\n organizationId,\n })\n output.log(`Dev server started on port ${port}`)\n output.log(`View your app in the Sanity dashboard here:`)\n output.log(styleText(['blue', 'underline'], dashboardAppUrl))\n\n return {close}\n } catch (err) {\n devDebug('Error starting app dev server', err)\n throw gracefulServerDeath('dev', config.httpHost, config.httpPort, err)\n }\n}\n"],"names":["styleText","startDevServer","gracefulServerDeath","devDebug","getDashboardAppURL","getDevServerConfig","startAppDevServer","options","cliConfig","flags","output","workDir","warn","organizationId","app","error","exit","config","log","close","server","isApp","port","httpHost","dashboardAppUrl","httpPort","err"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,cAAc,QAAO,4BAA2B;AACxD,SAAQC,mBAAmB,QAAO,sCAAqC;AACvE,SAAQC,QAAQ,QAAO,gBAAe;AACtC,SAAQC,kBAAkB,QAAO,0BAAyB;AAC1D,SAAQC,kBAAkB,QAAO,0BAAyB;AAG1D,OAAO,eAAeC,kBACpBC,OAAyB;IAEzB,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,MAAM,EAAEC,OAAO,EAAC,GAAGJ;IAE5C,IAAI,CAACE,KAAK,CAAC,oBAAoB,EAAE;QAC/BC,OAAOE,IAAI,CAAC,CAAC,4CAA4C,CAAC;QAC1DF,OAAOE,IAAI,CAAC,CAAC,iEAAiE,CAAC;IACjF;IAEA,IAAIC;IACJ,IAAIL,aAAa,SAASA,aAAaA,UAAUM,GAAG,EAAED,gBAAgB;QACpEA,iBAAiBL,UAAUM,GAAG,CAACD,cAAc;IAC/C;IAEA,IAAI,CAACA,gBAAgB;QACnBH,OAAOK,KAAK,CAAC,CAAC,4EAA4E,CAAC,EAAE;YAC3FC,MAAM;QACR;QACA,OAAO,CAAC;IACV;IAEA,MAAMC,SAASZ,mBAAmB;QAACG;QAAWC;QAAOC;QAAQC;IAAO;IAEpE,IAAI;QACFD,OAAOQ,GAAG,CAAC;QAEX,MAAM,EAACC,KAAK,EAAEC,MAAM,EAAC,GAAG,MAAMnB,eAAe;YAAC,GAAGgB,MAAM;YAAEI,OAAO;QAAI;QAEpE,MAAM,EAACC,IAAI,EAAC,GAAGF,OAAOH,MAAM,CAACG,MAAM;QACnC,MAAMG,WAAWN,OAAOM,QAAQ,IAAI;QAEpC,MAAMC,kBAAkB,MAAMpB,mBAAmB;YAC/CmB;YACAE,UAAUH;YACVT;QACF;QACAH,OAAOQ,GAAG,CAAC,CAAC,2BAA2B,EAAEI,MAAM;QAC/CZ,OAAOQ,GAAG,CAAC,CAAC,2CAA2C,CAAC;QACxDR,OAAOQ,GAAG,CAAClB,UAAU;YAAC;YAAQ;SAAY,EAAEwB;QAE5C,OAAO;YAACL;QAAK;IACf,EAAE,OAAOO,KAAK;QACZvB,SAAS,iCAAiCuB;QAC1C,MAAMxB,oBAAoB,OAAOe,OAAOM,QAAQ,EAAEN,OAAOQ,QAAQ,EAAEC;IACrE;AACF"}
|
|
@@ -10,12 +10,11 @@ import { compareDependencyVersions } from '../../util/compareDependencyVersions.
|
|
|
10
10
|
import { getLocalPackageVersion } from '../../util/getLocalPackageVersion.js';
|
|
11
11
|
import { getPackageManagerChoice } from '../../util/packageManager/packageManagerChoice.js';
|
|
12
12
|
import { upgradePackages } from '../../util/packageManager/upgradePackages.js';
|
|
13
|
-
import { warnAboutMissingAppId } from '../../util/warnAboutMissingAppId.js';
|
|
14
13
|
import { checkRequiredDependencies } from '../build/checkRequiredDependencies.js';
|
|
15
14
|
import { checkStudioDependencyVersions } from '../build/checkStudioDependencyVersions.js';
|
|
16
15
|
import { shouldAutoUpdate } from '../build/shouldAutoUpdate.js';
|
|
17
16
|
import { devDebug } from './devDebug.js';
|
|
18
|
-
import {
|
|
17
|
+
import { getDashboardAppURL } from './getDashboardAppUrl.js';
|
|
19
18
|
import { getDevServerConfig } from './getDevServerConfig.js';
|
|
20
19
|
export async function startStudioDevServer(options) {
|
|
21
20
|
const { cliConfig, flags, output, workDir } = options;
|
|
@@ -58,13 +57,6 @@ export async function startStudioDevServer(options) {
|
|
|
58
57
|
} catch (err) {
|
|
59
58
|
output.warn(`Failed to compare local versions against auto-updating versions: ${err}`);
|
|
60
59
|
}
|
|
61
|
-
if (!appId) {
|
|
62
|
-
warnAboutMissingAppId({
|
|
63
|
-
appType: 'studio',
|
|
64
|
-
output,
|
|
65
|
-
projectId
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
60
|
if (result?.unresolvedPrerelease.length) {
|
|
69
61
|
for (const mod of result.unresolvedPrerelease){
|
|
70
62
|
output.warn(`Your local version of ${mod.pkg} (${mod.version}) is a prerelease not available on the auto-updates CDN. The locally installed version will be used.`);
|
|
@@ -98,6 +90,9 @@ export async function startStudioDevServer(options) {
|
|
|
98
90
|
}
|
|
99
91
|
}
|
|
100
92
|
}
|
|
93
|
+
if (cliConfig?.schemaExtraction?.enabled) {
|
|
94
|
+
output.log(`${logSymbols.info} Running dev server with schema extraction enabled`);
|
|
95
|
+
}
|
|
101
96
|
const config = getDevServerConfig({
|
|
102
97
|
cliConfig,
|
|
103
98
|
flags,
|
|
@@ -134,7 +129,7 @@ export async function startStudioDevServer(options) {
|
|
|
134
129
|
output.log(styleText([
|
|
135
130
|
'blue',
|
|
136
131
|
'underline'
|
|
137
|
-
],
|
|
132
|
+
], await getDashboardAppURL({
|
|
138
133
|
httpHost,
|
|
139
134
|
httpPort: port,
|
|
140
135
|
organizationId: organizationId
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/startStudioDevServer.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {isInteractive} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner} from '@sanity/cli-core/ux'\nimport semver from 'semver'\n\nimport {startDevServer} from '../../server/devServer.js'\nimport {gracefulServerDeath} from '../../server/gracefulServerDeath.js'\nimport {getProjectById} from '../../services/projects.js'\nimport {getAppId} from '../../util/appId.js'\nimport {compareDependencyVersions} from '../../util/compareDependencyVersions.js'\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {getPackageManagerChoice} from '../../util/packageManager/packageManagerChoice.js'\nimport {upgradePackages} from '../../util/packageManager/upgradePackages.js'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId.js'\nimport {checkRequiredDependencies} from '../build/checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from '../build/checkStudioDependencyVersions.js'\nimport {shouldAutoUpdate} from '../build/shouldAutoUpdate.js'\nimport {devDebug} from './devDebug.js'\nimport {getCoreAppURL} from './getCoreAppUrl.js'\nimport {getDevServerConfig} from './getDevServerConfig.js'\nimport {type DevActionOptions} from './types.js'\n\nexport async function startStudioDevServer(\n options: DevActionOptions,\n): Promise<{close?: () => Promise<void>}> {\n const {cliConfig, flags, output, workDir} = options\n const projectId = cliConfig?.api?.projectId\n let organizationId: string | undefined\n\n const loadInDashboard = flags['load-in-dashboard']\n\n // Check studio dependency versions\n await checkStudioDependencyVersions(workDir, output)\n\n const {installedSanityVersion} = await checkRequiredDependencies(options)\n\n // Check if auto-updates are enabled\n const autoUpdatesEnabled = shouldAutoUpdate({cliConfig, flags, output})\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSanityVersion = semver.parse(installedSanityVersion)?.version\n if (!cleanSanityVersion) {\n throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`)\n }\n\n const sanityDependencies = [\n {name: 'sanity', version: cleanSanityVersion},\n {name: '@sanity/vision', version: cleanSanityVersion},\n ]\n\n output.log(`${logSymbols.info} Running with auto-updates enabled`)\n\n // Check local versions against deployed versions\n let result: Awaited<ReturnType<typeof compareDependencyVersions>> | undefined\n\n const appId = getAppId(cliConfig)\n\n try {\n result = await compareDependencyVersions(sanityDependencies, workDir, {appId})\n } catch (err) {\n output.warn(`Failed to compare local versions against auto-updating versions: ${err}`)\n }\n\n if (!appId) {\n warnAboutMissingAppId({\n appType: 'studio',\n output,\n projectId,\n })\n }\n\n if (result?.unresolvedPrerelease.length) {\n for (const mod of result.unresolvedPrerelease) {\n output.warn(\n `Your local version of ${mod.pkg} (${mod.version}) is a prerelease not available on the auto-updates CDN. The locally installed version will be used.`,\n )\n }\n }\n\n // mismatch between local and auto-updating dependencies\n if (result?.mismatched.length) {\n const message =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you run with the same versions locally as will be used when deploying.\\n\\n` +\n `${result.mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}\\n\\n`\n\n if (isInteractive()) {\n const shouldUpgrade = await confirm({\n default: true,\n message: styleText('yellow', `${message}Do you want to upgrade local versions?`),\n })\n if (shouldUpgrade) {\n await upgradePackages(\n {\n packageManager: (await getPackageManagerChoice(workDir, {interactive: false})).chosen,\n packages: result.mismatched.map((res) => [res.pkg, res.remote]),\n },\n {output, workDir},\n )\n }\n } else {\n // In this case we warn the user but we don't ask them if they want to upgrade because it's not interactive.\n output.log(styleText('yellow', message))\n }\n }\n }\n\n const config = getDevServerConfig({cliConfig, flags, output, workDir})\n\n if (loadInDashboard) {\n if (!projectId) {\n output.error('Project Id is required to load in dashboard', {exit: 1})\n }\n\n try {\n const project = await getProjectById(projectId!)\n organizationId = project.organizationId!\n } catch (error) {\n devDebug('Error getting organization id from project id', error)\n output.error('Failed to get organization id from project id', {exit: 1})\n }\n }\n\n try {\n const startTime = Date.now()\n const spin = spinner('Starting dev server').start()\n const {close, server} = await startDevServer(config)\n\n const {info: loggerInfo} = server.config.logger\n const {port} = server.config.server\n const httpHost = config.httpHost || 'localhost'\n\n if (loadInDashboard) {\n spin.succeed()\n\n output.log(`Dev server started on port ${port}`)\n output.log(`View your studio in the Sanity dashboard here:`)\n output.log(\n styleText(\n ['blue', 'underline'],\n getCoreAppURL({\n httpHost,\n httpPort: port,\n organizationId: organizationId!,\n }),\n ),\n )\n } else {\n const startupDuration = Date.now() - startTime\n const url = `http://${httpHost || 'localhost'}:${port}${config.basePath}`\n const appType = 'Sanity Studio'\n\n const viteVersion = await getLocalPackageVersion('vite', import.meta.url)\n spin.succeed()\n\n loggerInfo(\n `${appType} ` +\n `using ${styleText('cyan', `vite@${viteVersion}`)} ` +\n `ready in ${styleText('cyan', `${Math.ceil(startupDuration)}ms`)} ` +\n `and running at ${styleText('cyan', url)}`,\n )\n }\n\n return {close}\n } catch (err) {\n devDebug('Error starting studio dev server', err)\n throw gracefulServerDeath('dev', config.httpHost, config.httpPort, err)\n }\n}\n"],"names":["styleText","isInteractive","confirm","logSymbols","spinner","semver","startDevServer","gracefulServerDeath","getProjectById","getAppId","compareDependencyVersions","getLocalPackageVersion","getPackageManagerChoice","upgradePackages","warnAboutMissingAppId","checkRequiredDependencies","checkStudioDependencyVersions","shouldAutoUpdate","devDebug","getCoreAppURL","getDevServerConfig","startStudioDevServer","options","cliConfig","flags","output","workDir","projectId","api","organizationId","loadInDashboard","installedSanityVersion","autoUpdatesEnabled","cleanSanityVersion","parse","version","Error","sanityDependencies","name","log","info","result","appId","err","warn","appType","unresolvedPrerelease","length","mod","pkg","mismatched","message","map","installed","remote","join","shouldUpgrade","default","packageManager","interactive","chosen","packages","res","config","error","exit","project","startTime","Date","now","spin","start","close","server","loggerInfo","logger","port","httpHost","succeed","httpPort","startupDuration","url","basePath","viteVersion","Math","ceil"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAChE,OAAOC,YAAY,SAAQ;AAE3B,SAAQC,c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EJ,YAAY,YAAY,CAAC,EAAED,OAAOb,OAAOmB,QAAQ,EAAE;YACzE,MAAMrC,UAAU;YAEhB,MAAMsC,cAAc,MAAMxE,uBAAuB,QAAQ,YAAYsE,GAAG;YACxEX,KAAKQ,OAAO;YAEZJ,WACE,GAAG7B,QAAQ,CAAC,CAAC,GACX,CAAC,MAAM,EAAE7C,UAAU,QAAQ,CAAC,KAAK,EAAEmF,aAAa,EAAE,CAAC,CAAC,GACpD,CAAC,SAAS,EAAEnF,UAAU,QAAQ,GAAGoF,KAAKC,IAAI,CAACL,iBAAiB,EAAE,CAAC,EAAE,CAAC,CAAC,GACnE,CAAC,eAAe,EAAEhF,UAAU,QAAQiF,MAAM;QAEhD;QAEA,OAAO;YAACT;QAAK;IACf,EAAE,OAAO7B,KAAK;QACZzB,SAAS,oCAAoCyB;QAC7C,MAAMpC,oBAAoB,OAAOwD,OAAOc,QAAQ,EAAEd,OAAOgB,QAAQ,EAAEpC;IACrE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/startStudioDevServer.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {isInteractive} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner} from '@sanity/cli-core/ux'\nimport semver from 'semver'\n\nimport {startDevServer} from '../../server/devServer.js'\nimport {gracefulServerDeath} from '../../server/gracefulServerDeath.js'\nimport {getProjectById} from '../../services/projects.js'\nimport {getAppId} from '../../util/appId.js'\nimport {compareDependencyVersions} from '../../util/compareDependencyVersions.js'\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {getPackageManagerChoice} from '../../util/packageManager/packageManagerChoice.js'\nimport {upgradePackages} from '../../util/packageManager/upgradePackages.js'\nimport {checkRequiredDependencies} from '../build/checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from '../build/checkStudioDependencyVersions.js'\nimport {shouldAutoUpdate} from '../build/shouldAutoUpdate.js'\nimport {devDebug} from './devDebug.js'\nimport {getDashboardAppURL} from './getDashboardAppUrl.js'\nimport {getDevServerConfig} from './getDevServerConfig.js'\nimport {type DevActionOptions} from './types.js'\n\nexport async function startStudioDevServer(\n options: DevActionOptions,\n): Promise<{close?: () => Promise<void>}> {\n const {cliConfig, flags, output, workDir} = options\n const projectId = cliConfig?.api?.projectId\n let organizationId: string | undefined\n\n const loadInDashboard = flags['load-in-dashboard']\n\n // Check studio dependency versions\n await checkStudioDependencyVersions(workDir, output)\n\n const {installedSanityVersion} = await checkRequiredDependencies(options)\n\n // Check if auto-updates are enabled\n const autoUpdatesEnabled = shouldAutoUpdate({cliConfig, flags, output})\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSanityVersion = semver.parse(installedSanityVersion)?.version\n if (!cleanSanityVersion) {\n throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`)\n }\n\n const sanityDependencies = [\n {name: 'sanity', version: cleanSanityVersion},\n {name: '@sanity/vision', version: cleanSanityVersion},\n ]\n\n output.log(`${logSymbols.info} Running with auto-updates enabled`)\n\n // Check local versions against deployed versions\n let result: Awaited<ReturnType<typeof compareDependencyVersions>> | undefined\n\n const appId = getAppId(cliConfig)\n\n try {\n result = await compareDependencyVersions(sanityDependencies, workDir, {appId})\n } catch (err) {\n output.warn(`Failed to compare local versions against auto-updating versions: ${err}`)\n }\n\n if (result?.unresolvedPrerelease.length) {\n for (const mod of result.unresolvedPrerelease) {\n output.warn(\n `Your local version of ${mod.pkg} (${mod.version}) is a prerelease not available on the auto-updates CDN. The locally installed version will be used.`,\n )\n }\n }\n\n // mismatch between local and auto-updating dependencies\n if (result?.mismatched.length) {\n const message =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you run with the same versions locally as will be used when deploying.\\n\\n` +\n `${result.mismatched.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')}\\n\\n`\n\n if (isInteractive()) {\n const shouldUpgrade = await confirm({\n default: true,\n message: styleText('yellow', `${message}Do you want to upgrade local versions?`),\n })\n if (shouldUpgrade) {\n await upgradePackages(\n {\n packageManager: (await getPackageManagerChoice(workDir, {interactive: false})).chosen,\n packages: result.mismatched.map((res) => [res.pkg, res.remote]),\n },\n {output, workDir},\n )\n }\n } else {\n // In this case we warn the user but we don't ask them if they want to upgrade because it's not interactive.\n output.log(styleText('yellow', message))\n }\n }\n }\n\n if (cliConfig?.schemaExtraction?.enabled) {\n output.log(`${logSymbols.info} Running dev server with schema extraction enabled`)\n }\n\n const config = getDevServerConfig({cliConfig, flags, output, workDir})\n\n if (loadInDashboard) {\n if (!projectId) {\n output.error('Project Id is required to load in dashboard', {exit: 1})\n }\n\n try {\n const project = await getProjectById(projectId!)\n organizationId = project.organizationId!\n } catch (error) {\n devDebug('Error getting organization id from project id', error)\n output.error('Failed to get organization id from project id', {exit: 1})\n }\n }\n\n try {\n const startTime = Date.now()\n const spin = spinner('Starting dev server').start()\n const {close, server} = await startDevServer(config)\n\n const {info: loggerInfo} = server.config.logger\n const {port} = server.config.server\n const httpHost = config.httpHost || 'localhost'\n\n if (loadInDashboard) {\n spin.succeed()\n\n output.log(`Dev server started on port ${port}`)\n output.log(`View your studio in the Sanity dashboard here:`)\n output.log(\n styleText(\n ['blue', 'underline'],\n await getDashboardAppURL({\n httpHost,\n httpPort: port,\n organizationId: organizationId!,\n }),\n ),\n )\n } else {\n const startupDuration = Date.now() - startTime\n const url = `http://${httpHost || 'localhost'}:${port}${config.basePath}`\n const appType = 'Sanity Studio'\n\n const viteVersion = await getLocalPackageVersion('vite', import.meta.url)\n spin.succeed()\n\n loggerInfo(\n `${appType} ` +\n `using ${styleText('cyan', `vite@${viteVersion}`)} ` +\n `ready in ${styleText('cyan', `${Math.ceil(startupDuration)}ms`)} ` +\n `and running at ${styleText('cyan', url)}`,\n )\n }\n\n return {close}\n } catch (err) {\n devDebug('Error starting studio dev server', err)\n throw gracefulServerDeath('dev', config.httpHost, config.httpPort, err)\n }\n}\n"],"names":["styleText","isInteractive","confirm","logSymbols","spinner","semver","startDevServer","gracefulServerDeath","getProjectById","getAppId","compareDependencyVersions","getLocalPackageVersion","getPackageManagerChoice","upgradePackages","checkRequiredDependencies","checkStudioDependencyVersions","shouldAutoUpdate","devDebug","getDashboardAppURL","getDevServerConfig","startStudioDevServer","options","cliConfig","flags","output","workDir","projectId","api","organizationId","loadInDashboard","installedSanityVersion","autoUpdatesEnabled","cleanSanityVersion","parse","version","Error","sanityDependencies","name","log","info","result","appId","err","warn","unresolvedPrerelease","length","mod","pkg","mismatched","message","map","installed","remote","join","shouldUpgrade","default","packageManager","interactive","chosen","packages","res","schemaExtraction","enabled","config","error","exit","project","startTime","Date","now","spin","start","close","server","loggerInfo","logger","port","httpHost","succeed","httpPort","startupDuration","url","basePath","appType","viteVersion","Math","ceil"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAChE,OAAOC,YAAY,SAAQ;AAE3B,SAAQC,cAAc,QAAO,4BAA2B;AACxD,SAAQC,mBAAmB,QAAO,sCAAqC;AACvE,SAAQC,cAAc,QAAO,6BAA4B;AACzD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,yBAAyB,QAAO,0CAAyC;AACjF,SAAQC,sBAAsB,QAAO,uCAAsC;AAC3E,SAAQC,uBAAuB,QAAO,oDAAmD;AACzF,SAAQC,eAAe,QAAO,+CAA8C;AAC5E,SAAQC,yBAAyB,QAAO,wCAAuC;AAC/E,SAAQC,6BAA6B,QAAO,4CAA2C;AACvF,SAAQC,gBAAgB,QAAO,+BAA8B;AAC7D,SAAQC,QAAQ,QAAO,gBAAe;AACtC,SAAQC,kBAAkB,QAAO,0BAAyB;AAC1D,SAAQC,kBAAkB,QAAO,0BAAyB;AAG1D,OAAO,eAAeC,qBACpBC,OAAyB;IAEzB,MAAM,EA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AMnC,oBAAoB,OAAOwD,OAAOc,QAAQ,EAAEd,OAAOgB,QAAQ,EAAErC;IACrE;AACF"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { dirname, isAbsolute, relative } from 'node:path';
|
|
1
|
+
import { dirname, isAbsolute, join, relative } from 'node:path';
|
|
2
2
|
import { spinner } from '@sanity/cli-core/ux';
|
|
3
3
|
import { watch as chokidarWatch } from 'chokidar';
|
|
4
4
|
import debounce from 'lodash-es/debounce.js';
|
|
5
|
-
import { glob } from 'tinyglobby';
|
|
6
5
|
import { formatSchemaValidation } from './formatSchemaValidation.js';
|
|
6
|
+
import { createSchemaPatternMatcher } from './matchSchemaPattern.js';
|
|
7
7
|
import { runSchemaExtraction } from './runSchemaExtraction.js';
|
|
8
8
|
import { schemasExtractDebug } from './utils/debug.js';
|
|
9
9
|
import { SchemaExtractionError } from './utils/SchemaExtractionError.js';
|
|
@@ -92,10 +92,7 @@ import { SchemaExtractionError } from './utils/SchemaExtractionError.js';
|
|
|
92
92
|
};
|
|
93
93
|
// Run initial extraction
|
|
94
94
|
await runExtraction();
|
|
95
|
-
const absoluteWatchPatterns =
|
|
96
|
-
absolute: true,
|
|
97
|
-
ignore: IGNORED_PATTERNS
|
|
98
|
-
});
|
|
95
|
+
const absoluteWatchPatterns = watchPatterns.map((pattern)=>join(workDir, pattern));
|
|
99
96
|
// Create extraction runner with concurrency control
|
|
100
97
|
const { runExtraction: runConcurrentExtraction } = createExtractionRunner(async ()=>{
|
|
101
98
|
await runExtraction();
|
|
@@ -104,11 +101,16 @@ import { SchemaExtractionError } from './utils/SchemaExtractionError.js';
|
|
|
104
101
|
const debouncedExtract = debounce(()=>{
|
|
105
102
|
void runConcurrentExtraction();
|
|
106
103
|
}, 1000);
|
|
104
|
+
const { isMatch } = createSchemaPatternMatcher(watchPatterns);
|
|
107
105
|
const watcher = chokidarWatch(absoluteWatchPatterns, {
|
|
108
106
|
cwd: workDir,
|
|
107
|
+
ignored: IGNORED_PATTERNS,
|
|
109
108
|
ignoreInitial: true
|
|
110
109
|
});
|
|
111
110
|
watcher.on('all', (event, filePath)=>{
|
|
111
|
+
if (!isMatch(filePath, workDir)) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
112
114
|
const timestamp = new Date().toLocaleTimeString();
|
|
113
115
|
const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath;
|
|
114
116
|
output.log(`[${timestamp}] ${event}: ${relativePath}`);
|