@sanity/cli 3.93.1-next.9.198ab74452 → 3.94.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/lib/_chunks-cjs/cli.js +1 -1
  2. package/lib/_chunks-cjs/cli.js.map +1 -1
  3. package/package.json +10 -11
  4. package/templates/blog/README.md +1 -1
  5. package/templates/clean/README.md +1 -1
  6. package/templates/ecommerce/README.md +1 -1
  7. package/templates/get-started/README.md +1 -1
  8. package/templates/moviedb/README.md +1 -1
  9. package/templates/quickstart/README.md +1 -1
  10. package/src/CommandRunner.ts +0 -219
  11. package/src/__telemetry__/cli.telemetry.ts +0 -29
  12. package/src/__telemetry__/init.telemetry.ts +0 -95
  13. package/src/actions/codemod/codemodAction.ts +0 -109
  14. package/src/actions/codemod/mods/deskRename.ts +0 -19
  15. package/src/actions/codemod/mods/index.ts +0 -9
  16. package/src/actions/codemod/mods/partsTypeDirective.ts +0 -28
  17. package/src/actions/codemod/mods/reactIconsV3.ts +0 -54
  18. package/src/actions/codemod/types.ts +0 -10
  19. package/src/actions/init-plugin/bootstrapFromTemplate.ts +0 -196
  20. package/src/actions/init-project/bootstrapLocalTemplate.ts +0 -201
  21. package/src/actions/init-project/bootstrapRemoteTemplate.ts +0 -118
  22. package/src/actions/init-project/createAppCliConfig.ts +0 -24
  23. package/src/actions/init-project/createCliConfig.ts +0 -31
  24. package/src/actions/init-project/createPackageManifest.ts +0 -102
  25. package/src/actions/init-project/createStudioConfig.ts +0 -53
  26. package/src/actions/init-project/determineAppTemplate.ts +0 -13
  27. package/src/actions/init-project/fsUtils.ts +0 -40
  28. package/src/actions/init-project/git.ts +0 -59
  29. package/src/actions/init-project/initProject.ts +0 -1708
  30. package/src/actions/init-project/processTemplate.ts +0 -55
  31. package/src/actions/init-project/promptForDatasetName.ts +0 -68
  32. package/src/actions/init-project/prompts/index.ts +0 -51
  33. package/src/actions/init-project/prompts/nextjs.ts +0 -59
  34. package/src/actions/init-project/readPackageJson.ts +0 -17
  35. package/src/actions/init-project/templates/appQuickstart.ts +0 -23
  36. package/src/actions/init-project/templates/appSanityUi.ts +0 -25
  37. package/src/actions/init-project/templates/blog.ts +0 -5
  38. package/src/actions/init-project/templates/clean.ts +0 -5
  39. package/src/actions/init-project/templates/getStarted.ts +0 -37
  40. package/src/actions/init-project/templates/index.ts +0 -24
  41. package/src/actions/init-project/templates/moviedb.ts +0 -35
  42. package/src/actions/init-project/templates/nextjs/index.ts +0 -238
  43. package/src/actions/init-project/templates/nextjs/schemaTypes/blog.ts +0 -252
  44. package/src/actions/init-project/templates/quickstart.ts +0 -5
  45. package/src/actions/init-project/templates/shopify.ts +0 -78
  46. package/src/actions/init-project/templates/shopifyOnline.ts +0 -50
  47. package/src/actions/init-project/updateInitialTemplateMetadata.ts +0 -24
  48. package/src/actions/login/login.telemetry.ts +0 -18
  49. package/src/actions/login/login.ts +0 -350
  50. package/src/actions/login/types.ts +0 -19
  51. package/src/actions/project/createProject.ts +0 -36
  52. package/src/actions/telemetry/setTelemetryConsent.ts +0 -101
  53. package/src/actions/typegen/generate.telemetry.ts +0 -20
  54. package/src/actions/typegen/generateAction.ts +0 -210
  55. package/src/actions/versions/findSanityModuleVersions.ts +0 -185
  56. package/src/actions/yarn/events.ts +0 -73
  57. package/src/cli.ts +0 -350
  58. package/src/cliClient.ts +0 -62
  59. package/src/commands/blueprints/addBlueprintsCommand.ts +0 -155
  60. package/src/commands/blueprints/blueprintsGroup.ts +0 -10
  61. package/src/commands/blueprints/configBlueprintsCommand.ts +0 -86
  62. package/src/commands/blueprints/deployBlueprintsCommand.ts +0 -63
  63. package/src/commands/blueprints/destroyBlueprintsCommand.ts +0 -78
  64. package/src/commands/blueprints/infoBlueprintsCommand.ts +0 -55
  65. package/src/commands/blueprints/initBlueprintsCommand.ts +0 -99
  66. package/src/commands/blueprints/logsBlueprintsCommand.ts +0 -66
  67. package/src/commands/blueprints/planBlueprintsCommand.ts +0 -51
  68. package/src/commands/blueprints/stacksBlueprintsCommand.ts +0 -66
  69. package/src/commands/codemod/codemodCommand.ts +0 -32
  70. package/src/commands/debug/debugCommand.ts +0 -26
  71. package/src/commands/debug/printDebugInfo.ts +0 -243
  72. package/src/commands/docs/docsCommand.ts +0 -20
  73. package/src/commands/functions/devFunctionsCommand.ts +0 -73
  74. package/src/commands/functions/envFunctionsCommand.ts +0 -105
  75. package/src/commands/functions/functionsGroup.ts +0 -10
  76. package/src/commands/functions/logsFunctionsCommand.ts +0 -94
  77. package/src/commands/functions/testFunctionsCommand.ts +0 -93
  78. package/src/commands/help/helpCommand.ts +0 -21
  79. package/src/commands/help/showHelp.ts +0 -58
  80. package/src/commands/index.ts +0 -72
  81. package/src/commands/init/initCommand.ts +0 -123
  82. package/src/commands/install/installCommand.ts +0 -38
  83. package/src/commands/learn/learnCommand.ts +0 -20
  84. package/src/commands/login/loginCommand.ts +0 -29
  85. package/src/commands/logout/logoutCommand.ts +0 -52
  86. package/src/commands/manage/manageCommand.ts +0 -24
  87. package/src/commands/projects/listProjectsCommand.ts +0 -62
  88. package/src/commands/projects/projectsGroup.ts +0 -10
  89. package/src/commands/telemetry/disableTelemetryCommand.ts +0 -19
  90. package/src/commands/telemetry/enableTelemetryCommand.ts +0 -19
  91. package/src/commands/telemetry/telemetryGroup.ts +0 -10
  92. package/src/commands/telemetry/telemetryStatusCommand.ts +0 -89
  93. package/src/commands/typegen/generateTypesCommand.ts +0 -56
  94. package/src/commands/typegen/typegenGroup.ts +0 -10
  95. package/src/commands/versions/printVersionResult.ts +0 -51
  96. package/src/commands/versions/versionsCommand.ts +0 -13
  97. package/src/config.ts +0 -14
  98. package/src/debug.ts +0 -3
  99. package/src/index.ts +0 -6
  100. package/src/outputters/cliOutputter.ts +0 -47
  101. package/src/packageManager/getInstallCommand.ts +0 -26
  102. package/src/packageManager/getUpgradeCommand.ts +0 -52
  103. package/src/packageManager/index.ts +0 -33
  104. package/src/packageManager/installPackages.ts +0 -99
  105. package/src/packageManager/packageManagerChoice.ts +0 -204
  106. package/src/packageManager/uninstallPackages.ts +0 -44
  107. package/src/packageManager/yarnStub.ts +0 -22
  108. package/src/prompters/cliPrompter.ts +0 -9
  109. package/src/run.ts +0 -8
  110. package/src/studioDependencies.ts +0 -25
  111. package/src/types.ts +0 -387
  112. package/src/util/canLaunchBrowser.ts +0 -12
  113. package/src/util/cliWorker.ts +0 -34
  114. package/src/util/clientWrapper.ts +0 -119
  115. package/src/util/copy.ts +0 -50
  116. package/src/util/createExpiringConfig.ts +0 -80
  117. package/src/util/createTelemetryStore.ts +0 -204
  118. package/src/util/detectRuntime.ts +0 -12
  119. package/src/util/dynamicRequire.ts +0 -17
  120. package/src/util/frameworkPort.ts +0 -63
  121. package/src/util/generateCommandsDocumentation.ts +0 -62
  122. package/src/util/getCliConfig.ts +0 -172
  123. package/src/util/getCliVersion.ts +0 -22
  124. package/src/util/getLocalVersion.ts +0 -35
  125. package/src/util/getProjectDefaults.ts +0 -103
  126. package/src/util/getProviderName.ts +0 -9
  127. package/src/util/getUserConfig.ts +0 -15
  128. package/src/util/isCi.ts +0 -7
  129. package/src/util/isCommandGroup.ts +0 -7
  130. package/src/util/isInteractive.ts +0 -3
  131. package/src/util/isTrueish.ts +0 -8
  132. package/src/util/journeyConfig.ts +0 -280
  133. package/src/util/loadEnv.ts +0 -110
  134. package/src/util/mergeCommands.ts +0 -78
  135. package/src/util/neatStack.ts +0 -30
  136. package/src/util/noSuchCommandText.ts +0 -91
  137. package/src/util/parseArguments.ts +0 -76
  138. package/src/util/pathExists.ts +0 -14
  139. package/src/util/readJson.ts +0 -6
  140. package/src/util/readdirRecursive.ts +0 -26
  141. package/src/util/remoteTemplate.ts +0 -320
  142. package/src/util/resolveLatestVersions.ts +0 -24
  143. package/src/util/resolveRootDir.ts +0 -59
  144. package/src/util/telemetryDisclosure.ts +0 -45
  145. package/src/util/updateNotifier.ts +0 -158
  146. package/src/util/writeJson.ts +0 -6
  147. package/src/workers/getAndWriteJourneySchema.ts +0 -7
  148. package/src/workers/getCliConfig.ts +0 -14
  149. package/src/workers/typegenGenerate.ts +0 -228
@@ -1,103 +0,0 @@
1
- import fs from 'node:fs/promises'
2
- import path from 'node:path'
3
-
4
- import getGitConfig from '@rexxars/gitconfiglocal'
5
- import {getGitUserInfo} from 'git-user-info'
6
- import promiseProps from 'promise-props-recursive'
7
-
8
- import {type CliCommandContext} from '../types'
9
- import {getCliToken} from './clientWrapper'
10
-
11
- export interface ProjectDefaults {
12
- license: string
13
- author: string | undefined
14
- gitRemote: string
15
- projectName: string
16
- description: string
17
- }
18
-
19
- export function getProjectDefaults(
20
- workDir: string,
21
- {isPlugin, context}: {isPlugin: boolean; context: CliCommandContext},
22
- ): Promise<ProjectDefaults> {
23
- const cwd = process.cwd()
24
- const isSanityRoot = workDir === cwd
25
-
26
- return promiseProps({
27
- license: 'UNLICENSED',
28
-
29
- author: getUserInfo(context),
30
-
31
- // Don't try to use git remote from main Sanity project for plugins
32
- gitRemote: isPlugin && isSanityRoot ? '' : resolveGitRemote(cwd),
33
-
34
- // Don't try to guess plugin name if we're initing from Sanity root
35
- projectName: isPlugin && isSanityRoot ? '' : path.basename(cwd),
36
-
37
- // If we're initing a plugin, don't use description from Sanity readme
38
- description: getProjectDescription({isSanityRoot, isPlugin, outputDir: cwd}),
39
- })
40
- }
41
-
42
- async function resolveGitRemote(cwd: string): Promise<string | undefined> {
43
- try {
44
- await fs.stat(path.join(cwd, '.git'))
45
- const cfg = await getGitConfig(cwd)
46
- return cfg.remote && cfg.remote.origin && cfg.remote.origin.url
47
- } catch {
48
- return undefined
49
- }
50
- }
51
-
52
- async function getUserInfo(context: CliCommandContext): Promise<string | undefined> {
53
- const user = await getGitUserInfo()
54
- if (!user) {
55
- return getSanityUserInfo(context)
56
- }
57
-
58
- if (user.name && user.email) {
59
- return `${user.name} <${user.email}>`
60
- }
61
-
62
- return undefined
63
- }
64
-
65
- async function getSanityUserInfo(context: CliCommandContext): Promise<string | undefined> {
66
- const hasToken = Boolean(getCliToken())
67
- if (!hasToken) {
68
- return undefined
69
- }
70
-
71
- const client = context.apiClient({requireUser: true, requireProject: false})
72
- try {
73
- const user = await client.users.getById('me')
74
- return user ? `${user.name} <${user.email}>` : undefined
75
- } catch {
76
- return undefined
77
- }
78
- }
79
-
80
- async function getProjectDescription({
81
- isSanityRoot,
82
- isPlugin,
83
- outputDir,
84
- }: {
85
- isSanityRoot: boolean
86
- isPlugin: boolean
87
- outputDir: string
88
- }): Promise<string> {
89
- const tryResolve = isSanityRoot && !isPlugin
90
- if (!tryResolve) {
91
- return Promise.resolve('')
92
- }
93
-
94
- // Try to grab a project description from a standard GitHub-generated readme
95
- try {
96
- const readmePath = path.join(outputDir, 'README.md')
97
- const readme = await fs.readFile(readmePath, {encoding: 'utf8'})
98
- const match = readme.match(/^# .*?\n+(\w.*?)(?:$|\n)/)
99
- return ((match && match[1]) || '').replace(/\.$/, '') || ''
100
- } catch (err) {
101
- return ''
102
- }
103
- }
@@ -1,9 +0,0 @@
1
- import {type SanityUser} from '../types'
2
-
3
- export function getProviderName(provider: SanityUser['provider']) {
4
- if (provider === 'google') return 'Google'
5
- if (provider === 'github') return 'GitHub'
6
- if (provider === 'sanity') return 'Email'
7
- if (provider.startsWith('saml-')) return 'SAML'
8
- return provider
9
- }
@@ -1,15 +0,0 @@
1
- import ConfigStore from 'configstore'
2
-
3
- // eslint-disable-next-line no-process-env
4
- const sanityEnv = (process.env.SANITY_INTERNAL_ENV || '').toLowerCase()
5
- const configName = sanityEnv && sanityEnv !== 'production' ? `sanity-${sanityEnv}` : 'sanity'
6
- const defaults = {}
7
- let config: ConfigStore
8
-
9
- export const getUserConfig = (): ConfigStore => {
10
- if (!config) {
11
- config = new ConfigStore(configName, defaults, {globalConfigPath: true})
12
- }
13
-
14
- return config
15
- }
package/src/util/isCi.ts DELETED
@@ -1,7 +0,0 @@
1
- /* eslint-disable no-process-env */
2
- import {isTrueish} from './isTrueish'
3
-
4
- export const isCi =
5
- isTrueish(process.env.CI) || // Travis CI, CircleCI, Gitlab CI, Appveyor, CodeShip
6
- isTrueish(process.env.CONTINUOUS_INTEGRATION) || // Travis CI
7
- process.env.BUILD_NUMBER // Jenkins, TeamCity
@@ -1,7 +0,0 @@
1
- import {type CliCommandDefinition, type CliCommandGroupDefinition} from '../types'
2
-
3
- export function isCommandGroup(
4
- cmdOrGroup: CliCommandDefinition | CliCommandGroupDefinition,
5
- ): cmdOrGroup is CliCommandGroupDefinition {
6
- return 'isGroupRoot' in cmdOrGroup
7
- }
@@ -1,3 +0,0 @@
1
- /* eslint-disable no-process-env */
2
- export const isInteractive =
3
- process.stdout.isTTY && process.env.TERM !== 'dumb' && !('CI' in process.env)
@@ -1,8 +0,0 @@
1
- export function isTrueish(value: string | undefined) {
2
- if (value === undefined) return false
3
- if (value.toLowerCase() === 'true') return true
4
- if (value.toLowerCase() === 'false') return false
5
- const number = parseInt(value, 10)
6
- if (isNaN(number)) return false
7
- return number > 0
8
- }
@@ -1,280 +0,0 @@
1
- import fs from 'node:fs/promises'
2
- import path from 'node:path'
3
- import {Worker} from 'node:worker_threads'
4
-
5
- import {
6
- type BaseSchemaDefinition,
7
- type DocumentDefinition,
8
- type ObjectDefinition,
9
- } from '@sanity/types'
10
- import {format} from 'prettier'
11
-
12
- import {type CliApiClient} from '../types'
13
- import {getCliWorkerPath} from './cliWorker'
14
-
15
- /**
16
- * A Journey schema is a server schema that is saved in the Journey API
17
- */
18
-
19
- interface JourneySchemaWorkerData {
20
- schemasPath: string
21
- useTypeScript: boolean
22
- schemaUrl: string
23
- }
24
-
25
- type JourneySchemaWorkerResult = {type: 'success'} | {type: 'error'; error: Error}
26
-
27
- interface JourneyConfigResponse {
28
- projectId: string
29
- datasetName: string
30
- displayName: string
31
- schemaUrl: string
32
- isFirstProject: boolean // Always true for now, making it compatible with the existing getOrCreateProject
33
- }
34
-
35
- type DocumentOrObject = DocumentDefinition | ObjectDefinition
36
- type SchemaObject = BaseSchemaDefinition & {
37
- type: string
38
- fields?: SchemaObject[]
39
- of?: SchemaObject[]
40
- preview?: object
41
- }
42
-
43
- /**
44
- * Fetch a Journey schema from the Sanity schema club API and write it to disk
45
- */
46
- export async function getAndWriteJourneySchema(data: JourneySchemaWorkerData): Promise<void> {
47
- const {schemasPath, useTypeScript, schemaUrl} = data
48
- try {
49
- const documentTypes = await fetchJourneySchema(schemaUrl)
50
- const fileExtension = useTypeScript ? 'ts' : 'js'
51
-
52
- // Write a file for each schema
53
- for (const documentType of documentTypes) {
54
- const filePath = path.join(schemasPath, `${documentType.name}.${fileExtension}`)
55
- await fs.writeFile(filePath, await assembleJourneySchemaTypeFileContent(documentType))
56
- }
57
- // Write an index file that exports all the schemas
58
- const indexContent = await assembleJourneyIndexContent(documentTypes)
59
- await fs.writeFile(path.join(schemasPath, `index.${fileExtension}`), indexContent)
60
- } catch (error) {
61
- throw new Error(`Failed to fetch remote schema: ${error.message}`)
62
- }
63
- }
64
-
65
- /**
66
- * Executes the `getAndWriteJourneySchema` operation within a worker thread.
67
- *
68
- * This method is designed to safely import network resources by leveraging the `--experimental-network-imports` flag.
69
- * Due to the experimental nature of this flag, its use is not recommended in the main process. Consequently,
70
- * the task is delegated to a worker thread to ensure both safety and compliance with best practices.
71
- *
72
- * The core functionality involves fetching schema definitions from our own trusted API and writing them to disk.
73
- * This includes handling both predefined and custom schemas. For custom schemas, a process ensures
74
- * that they undergo JSON parsing to remove any JavaScript code and are validated before being saved.
75
- *
76
- * Depending on the configuration, the schemas are saved as either TypeScript or JavaScript files, dictated by the `useTypeScript` flag within the `workerData`.
77
- *
78
- * @param workerData - An object containing the necessary data and flags for the worker thread, including the path to save schemas, flags indicating whether to use TypeScript, and any other relevant configuration details.
79
- * @returns A promise that resolves upon successful execution of the schema fetching and writing process or rejects if an error occurs during the operation.
80
- */
81
- export async function getAndWriteJourneySchemaWorker(
82
- workerData: JourneySchemaWorkerData,
83
- ): Promise<void> {
84
- const workerPath = await getCliWorkerPath('getAndWriteJourneySchema')
85
- return new Promise((resolve, reject) => {
86
- const worker = new Worker(workerPath, {
87
- workerData,
88
- env: {
89
- // eslint-disable-next-line no-process-env
90
- ...process.env,
91
- // Dynamic HTTPS imports are currently behind a Node flag
92
- NODE_OPTIONS: '--experimental-network-imports',
93
- NODE_NO_WARNINGS: '1',
94
- },
95
- })
96
- worker.on('message', (message: JourneySchemaWorkerResult) => {
97
- if (message.type === 'success') {
98
- resolve()
99
- } else {
100
- message.error.message = `Import schema worker failed: ${message.error.message}`
101
- reject(message.error)
102
- }
103
- })
104
- worker.on('error', (error) => {
105
- error.message = `Import schema worker failed: ${error.message}`
106
- reject(error)
107
- })
108
- worker.on('exit', (code) => {
109
- if (code !== 0) {
110
- reject(new Error(`Worker stopped with exit code ${code}`))
111
- }
112
- })
113
- })
114
- }
115
-
116
- /**
117
- * Fetch a Journey config from the Sanity schema club API
118
- *
119
- * @param projectId - The slug of the Journey schema to fetch
120
- * @returns The Journey schema as an array of Sanity document or object definitions
121
- */
122
- export async function fetchJourneyConfig(
123
- apiClient: CliApiClient,
124
- projectId: string,
125
- ): Promise<JourneyConfigResponse> {
126
- if (!projectId) {
127
- throw new Error('ProjectId is required')
128
- }
129
- if (!/^[a-zA-Z0-9-]+$/.test(projectId)) {
130
- throw new Error('Invalid projectId')
131
- }
132
- try {
133
- const response: {
134
- projectId: string
135
- dataset: string
136
- displayName?: string
137
- schemaUrl: string
138
- } = await apiClient({
139
- requireUser: true,
140
- requireProject: true,
141
- api: {projectId},
142
- })
143
- .config({apiVersion: 'v2024-02-23'})
144
- .request({
145
- method: 'GET',
146
- uri: `/journey/projects/${projectId}`,
147
- })
148
-
149
- return {
150
- projectId: response.projectId,
151
- datasetName: response.dataset,
152
- displayName: response.displayName || 'Sanity Project',
153
- // The endpoint returns a signed URL that can be used to fetch the schema as ESM
154
- schemaUrl: response.schemaUrl,
155
- isFirstProject: true,
156
- }
157
- } catch {
158
- throw new Error(`Failed to fetch remote schema config: ${projectId}`)
159
- }
160
- }
161
-
162
- /**
163
- * Fetch a Journey schema from the Sanity schema club API
164
- *
165
- * @param projectId - The slug of the Journey schema to fetch
166
- * @returns The Journey schema as an array of Sanity document or object definitions
167
- */
168
- async function fetchJourneySchema(schemaUrl: string): Promise<DocumentOrObject[]> {
169
- try {
170
- const response = await import(schemaUrl)
171
- return response.default
172
- } catch {
173
- throw new Error(`Failed to fetch remote schema: ${schemaUrl}`)
174
- }
175
- }
176
-
177
- /**
178
- * Assemble a Journey schema type into a module export
179
- * Include the necessary imports and export the schema type as a named export
180
- *
181
- * @param schema - The Journey schema to export
182
- * @returns The Journey schema as a module export
183
- */
184
- async function assembleJourneySchemaTypeFileContent(schemaType: DocumentOrObject): Promise<string> {
185
- const serialised = wrapSchemaTypeInHelpers(schemaType)
186
- const imports = getImports(serialised)
187
- const prettifiedSchemaType = await format(serialised, {
188
- parser: 'typescript',
189
- printWidth: 40,
190
- })
191
- // Start file with import, then export the schema type as a named export
192
- return `${imports}\n\nexport const ${schemaType.name} = ${prettifiedSchemaType}\n`
193
- }
194
-
195
- /**
196
- * Assemble a list of Journey schema module exports into a single index file
197
- *
198
- * @param schemas - The Journey schemas to assemble into an index file
199
- * @returns The index file as a string
200
- */
201
- function assembleJourneyIndexContent(schemas: DocumentOrObject[]): Promise<string> {
202
- const sortedSchema = schemas.slice().sort((a, b) => (a.name > b.name ? 1 : -1))
203
- const imports = sortedSchema.map((schema) => `import { ${schema.name} } from './${schema.name}'`)
204
- const exports = sortedSchema.map((schema) => schema.name).join(',')
205
- const fileContents = `${imports.join('\n')}\n\nexport const schemaTypes = [${exports}]`
206
- return format(fileContents, {parser: 'typescript'})
207
- }
208
-
209
- /**
210
- * Get the import statements for a schema type
211
- *
212
- * @param schemaType - The schema type to get the imports for
213
- * @returns The import statements for the schema type
214
- */
215
- function getImports(schemaType: string): string {
216
- const defaultImports = ['defineType', 'defineField']
217
- if (schemaType.includes('defineArrayMember')) {
218
- defaultImports.push('defineArrayMember')
219
- }
220
- return `import { ${defaultImports.join(', ')} } from 'sanity'`
221
- }
222
-
223
- /**
224
- * Serialize a singleSanity schema type (signular) into a string.
225
- * Wraps the schema object in the appropriate helper function.
226
- *
227
- * @param schemaType - The schema type to serialize
228
- * @returns The schema type as a string
229
- */
230
- /**
231
- * Serializes a single Sanity schema type into a string.
232
- * Wraps the schema object in the appropriate helper function.
233
- *
234
- * @param schemaType - The schema type to serialize
235
- * @param root - Whether the schemaType is the root object
236
- * @returns The serialized schema type as a string
237
- */
238
- export function wrapSchemaTypeInHelpers(schemaType: SchemaObject, root: boolean = true): string {
239
- if (root) {
240
- return generateSchemaDefinition(schemaType, 'defineType')
241
- } else if (schemaType.type === 'array') {
242
- return `${generateSchemaDefinition(schemaType, 'defineField')},`
243
- }
244
- return `${generateSchemaDefinition(schemaType, 'defineField')},`
245
-
246
- function generateSchemaDefinition(
247
- object: SchemaObject,
248
- definitionType: 'defineType' | 'defineField',
249
- ): string {
250
- const {fields, preview, of, ...otherProperties} = object
251
-
252
- const serializedProps = serialize(otherProperties)
253
- const fieldsDef =
254
- fields && `fields: [${fields.map((f) => wrapSchemaTypeInHelpers(f, false)).join('')}]`
255
- const ofDef = of && `of: [${of.map((f) => `defineArrayMember({${serialize(f)}})`).join(',')}]`
256
- const previewDef = preview && `preview: {${serialize(preview)}}`
257
-
258
- const combinedDefinitions = [serializedProps, fieldsDef, ofDef, previewDef]
259
- .filter(Boolean)
260
- .join(',')
261
- return `${definitionType}({ ${combinedDefinitions} })`
262
- }
263
-
264
- function serialize(obj: object) {
265
- return Object.entries(obj)
266
- .map(([key, value]) => {
267
- if (key === 'prepare') {
268
- return `${value.toString()}`
269
- }
270
- if (typeof value === 'string') {
271
- return `${key}: "${value}"`
272
- }
273
- if (typeof value === 'object') {
274
- return `${key}: ${JSON.stringify(value)}`
275
- }
276
- return `${key}: ${value}`
277
- })
278
- .join(',')
279
- }
280
- }
@@ -1,110 +0,0 @@
1
- /**
2
- * This is an "inlined" version of Vite's `loadEnv` function,
3
- * simplified somewhat to only support our use case.
4
- *
5
- * Ideally we'd just use `loadEnv` from Vite, but importing it
6
- * causes bundling issues due to node APIs and downstream dependencies.
7
- *
8
- * Vite is MIT licensed, copyright (c) Yuxi (Evan) You and Vite contributors.
9
- */
10
-
11
- /* eslint-disable no-process-env */
12
- import fs from 'node:fs'
13
- import path from 'node:path'
14
-
15
- import {parse} from 'dotenv'
16
- import {expand} from 'dotenv-expand'
17
-
18
- export function loadEnv(
19
- mode: string,
20
- envDir: string,
21
- prefixes: string[] = ['VITE_'],
22
- ): Record<string, string> {
23
- if (mode === 'local') {
24
- throw new Error(
25
- `"local" cannot be used as a mode name because it conflicts with ` +
26
- `the .local postfix for .env files.`,
27
- )
28
- }
29
-
30
- const env: Record<string, string> = {}
31
- const envFiles = [
32
- /** default file */ `.env`,
33
- /** local file */ `.env.local`,
34
- /** mode file */ `.env.${mode}`,
35
- /** mode local file */ `.env.${mode}.local`,
36
- ]
37
-
38
- const parsed = Object.fromEntries(
39
- envFiles.flatMap((file) => {
40
- const envPath = lookupFile(envDir, [file], {
41
- rootDir: envDir,
42
- })
43
- if (!envPath) return []
44
- return Object.entries(parse(fs.readFileSync(envPath)))
45
- }),
46
- )
47
-
48
- // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this
49
- if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) {
50
- process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV
51
- }
52
- // support BROWSER and BROWSER_ARGS env variables
53
- if (parsed.BROWSER && process.env.BROWSER === undefined) {
54
- process.env.BROWSER = parsed.BROWSER
55
- }
56
- if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) {
57
- process.env.BROWSER_ARGS = parsed.BROWSER_ARGS
58
- }
59
-
60
- try {
61
- // let environment variables use each other
62
- expand({parsed})
63
- } catch (e) {
64
- // custom error handling until https://github.com/motdotla/dotenv-expand/issues/65 is fixed upstream
65
- // check for message "TypeError: Cannot read properties of undefined (reading 'split')"
66
- if (e.message.includes('split')) {
67
- throw new Error('dotenv-expand failed to expand env vars. Maybe you need to escape `$`?')
68
- }
69
- throw e
70
- }
71
-
72
- // only keys that start with prefix are exposed to client
73
- for (const [key, value] of Object.entries(parsed)) {
74
- if (prefixes.some((prefix) => key.startsWith(prefix))) {
75
- env[key] = value
76
- }
77
- }
78
-
79
- // check if there are actual env variables starting with VITE_*
80
- // these are typically provided inline and should be prioritized
81
- for (const key in process.env) {
82
- if (prefixes.some((prefix) => key.startsWith(prefix))) {
83
- env[key] = process.env[key] as string
84
- }
85
- }
86
-
87
- return env
88
- }
89
-
90
- function lookupFile(
91
- dir: string,
92
- formats: string[],
93
- options?: {
94
- rootDir?: string
95
- },
96
- ): string | undefined {
97
- for (const format of formats) {
98
- const fullPath = path.join(dir, format)
99
- // eslint-disable-next-line no-sync
100
- if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
101
- return fullPath
102
- }
103
- }
104
- const parentDir = path.dirname(dir)
105
- if (parentDir !== dir && (!options?.rootDir || parentDir.startsWith(options?.rootDir))) {
106
- return lookupFile(parentDir, formats, options)
107
- }
108
-
109
- return undefined
110
- }
@@ -1,78 +0,0 @@
1
- import {find} from 'lodash'
2
- import semver from 'semver'
3
-
4
- import {
5
- type CliCommandDefinition,
6
- type CliCommandGroupDefinition,
7
- type SanityCore,
8
- type SanityModuleInternal,
9
- } from '../types'
10
- import {dynamicRequire} from './dynamicRequire'
11
- import {isCommandGroup} from './isCommandGroup'
12
-
13
- export interface MergeOptions {
14
- cwd: string
15
- workDir: string
16
- cliVersion: string
17
- }
18
-
19
- export async function mergeCommands(
20
- baseCommands: (CliCommandDefinition | CliCommandGroupDefinition)[],
21
- corePath: string | undefined,
22
- options: MergeOptions,
23
- ): Promise<(CliCommandDefinition | CliCommandGroupDefinition)[]> {
24
- if (!corePath) {
25
- return baseCommands
26
- }
27
-
28
- const {cwd, workDir, cliVersion} = options
29
- const coreImport = dynamicRequire<SanityCore | SanityModuleInternal>(corePath)
30
- const coercedCliVersion = semver.coerce(cliVersion) || ''
31
- const moduleName = /@sanity[/\\]core/.test(corePath) ? '@sanity/core' : 'sanity'
32
- const core = 'cliProjectCommands' in coreImport ? coreImport.cliProjectCommands : coreImport
33
-
34
- // @todo the resolving of `sanity`/`@sanity/core` here might find global installs,
35
- // which can lead to incorrect versioning being reported. We should only run this
36
- // check if we are within a project dir, and even then only if it is not global
37
- /*
38
- if (
39
- core.requiredCliVersionRange &&
40
- !semver.satisfies(coercedCliVersion, core.requiredCliVersionRange)
41
- ) {
42
- const upgradeCmd = chalk.yellow(await getCliUpgradeCommand({cwd, workDir}))
43
- console.error(
44
- `The version of the \`${moduleName}\` installed in this project requires @sanity/cli @ ${chalk.green(
45
- core.requiredCliVersionRange
46
- )}. Currently installed version is ${chalk.red(
47
- cliVersion
48
- )}.\n\nPlease upgrade by running:\n\n ${upgradeCmd}\n\n`
49
- )
50
- process.exit(1)
51
- }
52
- */
53
-
54
- const merged = baseCommands.concat(core.commands).map(addDefaultGroup)
55
-
56
- // Remove duplicate commands when within the same group,
57
- // the last defined commands with the given name wins
58
- return merged.reverse().reduce(
59
- (cmds, cmd) => {
60
- const group = isCommandGroup(cmd) ? undefined : cmd.group
61
- if (!find(cmds, {name: cmd.name, group})) {
62
- cmds.push(cmd)
63
- }
64
- return cmds
65
- },
66
- [] as (CliCommandDefinition | CliCommandGroupDefinition)[],
67
- )
68
- }
69
-
70
- function addDefaultGroup(
71
- cmd: CliCommandDefinition | CliCommandGroupDefinition,
72
- ): CliCommandDefinition | CliCommandGroupDefinition {
73
- if (!isCommandGroup(cmd) && !cmd.group) {
74
- cmd.group = 'default'
75
- }
76
-
77
- return cmd
78
- }
@@ -1,30 +0,0 @@
1
- /**
2
- * TypeScript version of the `neat-stack` module by
3
- * ISC License (ISC)
4
- * Copyright 2017 - 2019 Shinnosuke Watanabe
5
- */
6
- import {inspect} from 'node:util'
7
-
8
- import {dim, red} from 'chalk'
9
- import cleanStack from 'clean-stack'
10
-
11
- const options = {pretty: process.platform !== 'win32'}
12
-
13
- export function neatStack(error: string | Error): string {
14
- if (typeof error === 'string') {
15
- return red(cleanStack(error, options))
16
- }
17
-
18
- if (error === null || typeof error !== 'object' || typeof error.stack !== 'string') {
19
- return red(inspect(error))
20
- }
21
-
22
- const title = error.toString()
23
- const stack = cleanStack(error.stack, options)
24
-
25
- if (!stack.startsWith(title)) {
26
- return red(stack)
27
- }
28
-
29
- return red(`${title}${dim(cleanStack(error.stack, options).slice(title.length))}`)
30
- }