@sanity/cli 3.77.3-server-side-schemas.26 → 3.77.3-server-side-schemas.36
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/bin/xdg-open +1066 -0
- package/lib/_chunks-cjs/cli.js +384 -195
- package/lib/_chunks-cjs/cli.js.map +1 -1
- package/lib/_chunks-cjs/loadEnv.js +5 -5
- package/lib/_chunks-cjs/loadEnv.js.map +1 -1
- package/lib/index.d.mts +2 -3
- package/lib/index.d.ts +2 -3
- package/lib/index.esm.js +5 -5
- package/lib/index.esm.js.map +1 -1
- package/lib/index.mjs +5 -5
- package/lib/index.mjs.map +1 -1
- package/package.json +12 -11
- package/src/actions/init-project/bootstrapLocalTemplate.ts +10 -10
- package/src/actions/init-project/{createCoreAppCliConfig.ts → createAppCliConfig.ts} +4 -4
- package/src/actions/init-project/{determineCoreAppTemplate.ts → determineAppTemplate.ts} +3 -3
- package/src/actions/init-project/initProject.ts +125 -48
- package/src/actions/init-project/templates/{coreApp.ts → appQuickstart.ts} +7 -8
- package/src/actions/init-project/templates/index.ts +2 -2
- package/src/cli.ts +4 -14
- package/src/commands/functions/devFunctionsCommand.ts +42 -0
- package/src/commands/functions/functionsGroup.ts +11 -0
- package/src/commands/functions/logsFunctionsCommand.ts +46 -0
- package/src/commands/functions/testFunctionsCommand.ts +62 -0
- package/src/commands/index.ts +8 -0
- package/src/commands/init/initCommand.ts +0 -1
- package/src/types.ts +2 -3
- package/src/util/clientWrapper.ts +1 -1
- package/src/util/resolveRootDir.ts +5 -5
- package/templates/core-app/src/App.css +18 -0
- package/templates/core-app/src/App.tsx +15 -17
- package/templates/core-app/src/ExampleComponent.css +26 -0
- package/templates/core-app/src/ExampleComponent.tsx +15 -4
package/lib/index.mjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/util/dynamicRequire.ts","../src/util/getCliConfig.ts","../src/debug.ts","../src/util/resolveRootDir.ts","../src/cliClient.ts","../src/config.ts","../../../../node_modules/.pnpm/dotenv@16.4.7/node_modules/dotenv/lib/main.js","../../../../node_modules/.pnpm/dotenv-expand@9.0.0/node_modules/dotenv-expand/lib/main.js","../src/util/loadEnv.ts"],"sourcesContent":["// Prevent webpack from bundling in webpack context,\n// use regular node require for unbundled context\n\n/* eslint-disable camelcase, no-undef */\ndeclare const __webpack_require__: boolean\ndeclare const __non_webpack_require__: typeof require\n\nconst requireFunc: typeof require =\n typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require\n/* eslint-enable camelcase, no-undef */\n\nexport function dynamicRequire<T = any>(request: string): T {\n const mod = requireFunc(request)\n return mod.__esModule && mod.default ? mod.default : mod\n}\n\ndynamicRequire.resolve = requireFunc.resolve\n","/* eslint-disable no-sync */\n\n/**\n * Reads the Sanity CLI config from one of the following files (in preferred order):\n * - sanity.cli.js\n * - sanity.cli.ts\n *\n * Note: There are two ways of using this:\n * a) `getCliConfig(cwd)`\n * b) `getCliConfig(cwd, {forked: true})`\n *\n * Approach a is generally a bit faster as it avoids the forking startup time, while\n * approach b could be considered \"safer\" since any side-effects of running the config\n * file will not bleed into the current CLI process directly.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport {Worker} from 'node:worker_threads'\n\nimport {type CliConfig, type SanityJson} from '../types'\nimport {getCliWorkerPath} from './cliWorker'\nimport {dynamicRequire} from './dynamicRequire'\n\nexport type CliMajorVersion = 2 | 3\n\nexport type CliConfigResult =\n | {config: SanityJson; path: string; version: 2}\n | {config: CliConfig; path: string; version: 3}\n | {config: null; path: string; version: CliMajorVersion}\n\nexport async function getCliConfig(\n cwd: string,\n {forked}: {forked?: boolean} = {},\n): Promise<CliConfigResult | null> {\n if (forked) {\n try {\n return await getCliConfigForked(cwd)\n } catch (err) {\n // Intentional noop - try unforked variant\n }\n }\n\n const {unregister} = __DEV__\n ? {unregister: () => undefined}\n : require('esbuild-register/dist/node').register({supported: {'dynamic-import': true}})\n\n try {\n const v3Config = getSanityCliConfig(cwd)\n if (v3Config) {\n return v3Config\n }\n\n return getSanityJsonConfig(cwd)\n } catch (err) {\n throw err\n } finally {\n unregister()\n }\n}\n\nexport function getCliConfigSync(cwd: string): CliConfigResult | null {\n const v3Config = getSanityCliConfig(cwd)\n return v3Config ? v3Config : getSanityJsonConfig(cwd)\n}\n\nasync function getCliConfigForked(cwd: string): Promise<CliConfigResult | null> {\n const workerPath = await getCliWorkerPath('getCliConfig')\n return new Promise((resolve, reject) => {\n const worker = new Worker(workerPath, {\n workerData: cwd,\n // eslint-disable-next-line no-process-env\n env: process.env,\n })\n worker.on('message', (message) => {\n if (message.type === 'config') {\n resolve(message.config)\n } else {\n const error = new Error(message.error)\n ;(error as any).type = message.errorType\n reject(new Error(message.error))\n }\n })\n worker.on('error', reject)\n worker.on('exit', (code) => {\n if (code !== 0) {\n reject(new Error(`Worker stopped with exit code ${code}`))\n }\n })\n })\n}\n\nfunction getSanityJsonConfig(cwd: string): CliConfigResult | null {\n const configPath = path.join(cwd, 'sanity.json')\n\n if (!fs.existsSync(configPath)) {\n return null\n }\n\n return {\n config: loadJsonConfig(configPath),\n path: configPath,\n version: 2,\n }\n}\n\nfunction getSanityCliConfig(cwd: string): CliConfigResult | null {\n const jsConfigPath = path.join(cwd, 'sanity.cli.js')\n const tsConfigPath = path.join(cwd, 'sanity.cli.ts')\n\n const [js, ts] = [fs.existsSync(jsConfigPath), fs.existsSync(tsConfigPath)]\n\n if (!js && !ts) {\n return null\n }\n\n if (!js && ts) {\n return {\n config: importConfig(tsConfigPath),\n path: tsConfigPath,\n version: 3,\n }\n }\n\n if (js && ts) {\n warn('Found both `sanity.cli.js` and `sanity.cli.ts` - using sanity.cli.js')\n }\n\n return {\n config: importConfig(jsConfigPath),\n path: jsConfigPath,\n version: 3,\n }\n}\n\nfunction loadJsonConfig(filePath: string): SanityJson | null {\n try {\n const content = fs.readFileSync(filePath, 'utf8')\n return JSON.parse(content)\n } catch (err) {\n console.error(`Error reading \"${filePath}\": ${err.message}`)\n return null\n }\n}\n\nfunction importConfig(filePath: string): CliConfig | null {\n try {\n const config = dynamicRequire<CliConfig | {default: CliConfig} | null>(filePath)\n if (config === null || typeof config !== 'object') {\n throw new Error('Module export is not a configuration object')\n }\n\n return 'default' in config ? config.default : config\n } catch (err) {\n // If attempting to import `defineCliConfig` or similar from `sanity/cli`,\n // accept the fact that it might not be installed. Instead, let the CLI\n // give a warning about the `sanity` module not being installed\n if (err.code === 'MODULE_NOT_FOUND' && err.message.includes('sanity/cli')) {\n return null\n }\n\n console.error(`Error reading \"${filePath}\": ${err.message}`)\n return null\n }\n}\n\nfunction warn(warning: string) {\n if (typeof process.send === 'function') {\n process.send({type: 'warning', warning})\n } else {\n console.warn(warning)\n }\n}\n","import debugIt from 'debug'\n\nexport const debug = debugIt('sanity:cli')\n","/* eslint-disable no-sync */\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport {debug} from '../debug'\n\n/**\n * Resolve project root directory, falling back to cwd if it cannot be found\n */\nexport function resolveRootDir(cwd: string, isCoreApp = false): string {\n try {\n return resolveProjectRoot(cwd, 0, isCoreApp) || cwd\n } catch (err) {\n throw new Error(`Error occurred trying to resolve project root:\\n${err.message}`)\n }\n}\n\nfunction hasSanityConfig(basePath: string, configName: string): boolean {\n const buildConfigs = [\n fileExists(path.join(basePath, `${configName}.js`)),\n fileExists(path.join(basePath, `${configName}.ts`)),\n isSanityV2StudioRoot(basePath),\n ]\n\n return buildConfigs.some(Boolean)\n}\n\nfunction resolveProjectRoot(basePath: string, iterations = 0, isCoreApp = false): string | false {\n const configName = isCoreApp ? 'sanity.cli' : 'sanity.config'\n if (hasSanityConfig(basePath, configName)) {\n return basePath\n }\n\n const parentDir = path.resolve(basePath, '..')\n if (parentDir === basePath || iterations > 30) {\n // Reached root (or max depth), give up\n return false\n }\n\n return resolveProjectRoot(parentDir, iterations + 1, isCoreApp)\n}\n\nfunction isSanityV2StudioRoot(basePath: string): boolean {\n try {\n const content = fs.readFileSync(path.join(basePath, 'sanity.json'), 'utf8')\n const sanityJson = JSON.parse(content)\n const isRoot = Boolean(sanityJson?.root)\n if (isRoot) {\n debug('Found Sanity v2 studio root at %s', basePath)\n }\n return isRoot\n } catch (err) {\n return false\n }\n}\n\nfunction fileExists(filePath: string): boolean {\n return fs.existsSync(filePath)\n}\n","import {createClient, type SanityClient} from '@sanity/client'\n\nimport {getCliConfigSync} from './util/getCliConfig'\nimport {resolveRootDir} from './util/resolveRootDir'\n\nexport interface CliClientOptions {\n cwd?: string\n\n projectId?: string\n dataset?: string\n useCdn?: boolean\n token?: string\n apiVersion?: string\n}\n\nexport function getCliClient(options: CliClientOptions = {}): SanityClient {\n if (typeof process !== 'object') {\n throw new Error('getCliClient() should only be called from node.js scripts')\n }\n\n const {\n // eslint-disable-next-line no-process-env\n cwd = process.env.SANITY_BASE_PATH || process.cwd(),\n useCdn = false,\n apiVersion = '2022-06-06',\n projectId,\n dataset,\n token = getCliClient.__internal__getToken(),\n } = options\n\n if (projectId && dataset) {\n return createClient({projectId, dataset, apiVersion, useCdn, token})\n }\n\n const rootDir = resolveRootDir(cwd)\n const {config} = getCliConfigSync(rootDir) || {}\n if (!config) {\n throw new Error('Unable to resolve CLI configuration')\n }\n\n const apiConfig = config?.api || {}\n if (!apiConfig.projectId || !apiConfig.dataset) {\n throw new Error('Unable to resolve project ID/dataset from CLI configuration')\n }\n\n return createClient({\n projectId: apiConfig.projectId,\n dataset: apiConfig.dataset,\n apiVersion,\n useCdn,\n token,\n })\n}\n\n/* eslint-disable camelcase */\n/**\n * @internal\n * @deprecated This is only for INTERNAL use, and should not be relied upon outside of official Sanity modules\n * @returns A token to use when constructing a client without a `token` explicitly defined, or undefined\n */\ngetCliClient.__internal__getToken = (): string | undefined => undefined\n/* eslint-enable camelcase */\n","import {type CliConfig} from './types'\n\n/** @beta */\nexport function defineCliConfig(config: CliConfig): CliConfig {\n return config\n}\n\n/**\n * @deprecated Use `defineCliConfig` instead\n * @beta\n */\nexport function createCliConfig(config: CliConfig): CliConfig {\n return config\n}\n","const fs = require('fs')\nconst path = require('path')\nconst os = require('os')\nconst crypto = require('crypto')\nconst packageJson = require('../package.json')\n\nconst version = packageJson.version\n\nconst LINE = /(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/mg\n\n// Parse src into an Object\nfunction parse (src) {\n const obj = {}\n\n // Convert buffer to string\n let lines = src.toString()\n\n // Convert line breaks to same format\n lines = lines.replace(/\\r\\n?/mg, '\\n')\n\n let match\n while ((match = LINE.exec(lines)) != null) {\n const key = match[1]\n\n // Default undefined or null to empty string\n let value = (match[2] || '')\n\n // Remove whitespace\n value = value.trim()\n\n // Check if double quoted\n const maybeQuote = value[0]\n\n // Remove surrounding quotes\n value = value.replace(/^(['\"`])([\\s\\S]*)\\1$/mg, '$2')\n\n // Expand newlines if double quoted\n if (maybeQuote === '\"') {\n value = value.replace(/\\\\n/g, '\\n')\n value = value.replace(/\\\\r/g, '\\r')\n }\n\n // Add to object\n obj[key] = value\n }\n\n return obj\n}\n\nfunction _parseVault (options) {\n const vaultPath = _vaultPath(options)\n\n // Parse .env.vault\n const result = DotenvModule.configDotenv({ path: vaultPath })\n if (!result.parsed) {\n const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)\n err.code = 'MISSING_DATA'\n throw err\n }\n\n // handle scenario for comma separated keys - for use with key rotation\n // example: DOTENV_KEY=\"dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod\"\n const keys = _dotenvKey(options).split(',')\n const length = keys.length\n\n let decrypted\n for (let i = 0; i < length; i++) {\n try {\n // Get full key\n const key = keys[i].trim()\n\n // Get instructions for decrypt\n const attrs = _instructions(result, key)\n\n // Decrypt\n decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)\n\n break\n } catch (error) {\n // last key\n if (i + 1 >= length) {\n throw error\n }\n // try next key\n }\n }\n\n // Parse decrypted .env string\n return DotenvModule.parse(decrypted)\n}\n\nfunction _log (message) {\n console.log(`[dotenv@${version}][INFO] ${message}`)\n}\n\nfunction _warn (message) {\n console.log(`[dotenv@${version}][WARN] ${message}`)\n}\n\nfunction _debug (message) {\n console.log(`[dotenv@${version}][DEBUG] ${message}`)\n}\n\nfunction _dotenvKey (options) {\n // prioritize developer directly setting options.DOTENV_KEY\n if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {\n return options.DOTENV_KEY\n }\n\n // secondary infra already contains a DOTENV_KEY environment variable\n if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {\n return process.env.DOTENV_KEY\n }\n\n // fallback to empty string\n return ''\n}\n\nfunction _instructions (result, dotenvKey) {\n // Parse DOTENV_KEY. Format is a URI\n let uri\n try {\n uri = new URL(dotenvKey)\n } catch (error) {\n if (error.code === 'ERR_INVALID_URL') {\n const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n throw error\n }\n\n // Get decrypt key\n const key = uri.password\n if (!key) {\n const err = new Error('INVALID_DOTENV_KEY: Missing key part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get environment\n const environment = uri.searchParams.get('environment')\n if (!environment) {\n const err = new Error('INVALID_DOTENV_KEY: Missing environment part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get ciphertext payload\n const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`\n const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION\n if (!ciphertext) {\n const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)\n err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'\n throw err\n }\n\n return { ciphertext, key }\n}\n\nfunction _vaultPath (options) {\n let possibleVaultPath = null\n\n if (options && options.path && options.path.length > 0) {\n if (Array.isArray(options.path)) {\n for (const filepath of options.path) {\n if (fs.existsSync(filepath)) {\n possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`\n }\n }\n } else {\n possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`\n }\n } else {\n possibleVaultPath = path.resolve(process.cwd(), '.env.vault')\n }\n\n if (fs.existsSync(possibleVaultPath)) {\n return possibleVaultPath\n }\n\n return null\n}\n\nfunction _resolveHome (envPath) {\n return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath\n}\n\nfunction _configVault (options) {\n _log('Loading env from encrypted .env.vault')\n\n const parsed = DotenvModule._parseVault(options)\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsed, options)\n\n return { parsed }\n}\n\nfunction configDotenv (options) {\n const dotenvPath = path.resolve(process.cwd(), '.env')\n let encoding = 'utf8'\n const debug = Boolean(options && options.debug)\n\n if (options && options.encoding) {\n encoding = options.encoding\n } else {\n if (debug) {\n _debug('No encoding is specified. UTF-8 is used by default')\n }\n }\n\n let optionPaths = [dotenvPath] // default, look for .env\n if (options && options.path) {\n if (!Array.isArray(options.path)) {\n optionPaths = [_resolveHome(options.path)]\n } else {\n optionPaths = [] // reset default\n for (const filepath of options.path) {\n optionPaths.push(_resolveHome(filepath))\n }\n }\n }\n\n // Build the parsed data in a temporary object (because we need to return it). Once we have the final\n // parsed data, we will combine it with process.env (or options.processEnv if provided).\n let lastError\n const parsedAll = {}\n for (const path of optionPaths) {\n try {\n // Specifying an encoding returns a string instead of a buffer\n const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))\n\n DotenvModule.populate(parsedAll, parsed, options)\n } catch (e) {\n if (debug) {\n _debug(`Failed to load ${path} ${e.message}`)\n }\n lastError = e\n }\n }\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsedAll, options)\n\n if (lastError) {\n return { parsed: parsedAll, error: lastError }\n } else {\n return { parsed: parsedAll }\n }\n}\n\n// Populates process.env from .env file\nfunction config (options) {\n // fallback to original dotenv if DOTENV_KEY is not set\n if (_dotenvKey(options).length === 0) {\n return DotenvModule.configDotenv(options)\n }\n\n const vaultPath = _vaultPath(options)\n\n // dotenvKey exists but .env.vault file does not exist\n if (!vaultPath) {\n _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)\n\n return DotenvModule.configDotenv(options)\n }\n\n return DotenvModule._configVault(options)\n}\n\nfunction decrypt (encrypted, keyStr) {\n const key = Buffer.from(keyStr.slice(-64), 'hex')\n let ciphertext = Buffer.from(encrypted, 'base64')\n\n const nonce = ciphertext.subarray(0, 12)\n const authTag = ciphertext.subarray(-16)\n ciphertext = ciphertext.subarray(12, -16)\n\n try {\n const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)\n aesgcm.setAuthTag(authTag)\n return `${aesgcm.update(ciphertext)}${aesgcm.final()}`\n } catch (error) {\n const isRange = error instanceof RangeError\n const invalidKeyLength = error.message === 'Invalid key length'\n const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'\n\n if (isRange || invalidKeyLength) {\n const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n } else if (decryptionFailed) {\n const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')\n err.code = 'DECRYPTION_FAILED'\n throw err\n } else {\n throw error\n }\n }\n}\n\n// Populate process.env with parsed values\nfunction populate (processEnv, parsed, options = {}) {\n const debug = Boolean(options && options.debug)\n const override = Boolean(options && options.override)\n\n if (typeof parsed !== 'object') {\n const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')\n err.code = 'OBJECT_REQUIRED'\n throw err\n }\n\n // Set process.env\n for (const key of Object.keys(parsed)) {\n if (Object.prototype.hasOwnProperty.call(processEnv, key)) {\n if (override === true) {\n processEnv[key] = parsed[key]\n }\n\n if (debug) {\n if (override === true) {\n _debug(`\"${key}\" is already defined and WAS overwritten`)\n } else {\n _debug(`\"${key}\" is already defined and was NOT overwritten`)\n }\n }\n } else {\n processEnv[key] = parsed[key]\n }\n }\n}\n\nconst DotenvModule = {\n configDotenv,\n _configVault,\n _parseVault,\n config,\n decrypt,\n parse,\n populate\n}\n\nmodule.exports.configDotenv = DotenvModule.configDotenv\nmodule.exports._configVault = DotenvModule._configVault\nmodule.exports._parseVault = DotenvModule._parseVault\nmodule.exports.config = DotenvModule.config\nmodule.exports.decrypt = DotenvModule.decrypt\nmodule.exports.parse = DotenvModule.parse\nmodule.exports.populate = DotenvModule.populate\n\nmodule.exports = DotenvModule\n","'use strict'\n\nfunction _interpolate (envValue, environment, config) {\n const matches = envValue.match(/(.?\\${*[\\w]*(?::-[\\w/]*)?}*)/g) || []\n\n return matches.reduce(function (newEnv, match, index) {\n const parts = /(.?)\\${*([\\w]*(?::-[\\w/]*)?)?}*/g.exec(match)\n if (!parts || parts.length === 0) {\n return newEnv\n }\n\n const prefix = parts[1]\n\n let value, replacePart\n\n if (prefix === '\\\\') {\n replacePart = parts[0]\n value = replacePart.replace('\\\\$', '$')\n } else {\n const keyParts = parts[2].split(':-')\n const key = keyParts[0]\n replacePart = parts[0].substring(prefix.length)\n // process.env value 'wins' over .env file's value\n value = Object.prototype.hasOwnProperty.call(environment, key)\n ? environment[key]\n : (config.parsed[key] || keyParts[1] || '')\n\n // If the value is found, remove nested expansions.\n if (keyParts.length > 1 && value) {\n const replaceNested = matches[index + 1]\n matches[index + 1] = ''\n\n newEnv = newEnv.replace(replaceNested, '')\n }\n // Resolve recursive interpolations\n value = _interpolate(value, environment, config)\n }\n\n return newEnv.replace(replacePart, value)\n }, envValue)\n}\n\nfunction expand (config) {\n // if ignoring process.env, use a blank object\n const environment = config.ignoreProcessEnv ? {} : process.env\n\n for (const configKey in config.parsed) {\n const value = Object.prototype.hasOwnProperty.call(environment, configKey) ? environment[configKey] : config.parsed[configKey]\n\n config.parsed[configKey] = _interpolate(value, environment, config)\n }\n\n for (const processKey in config.parsed) {\n environment[processKey] = config.parsed[processKey]\n }\n\n return config\n}\n\nmodule.exports.expand = expand\n","/**\n * This is an \"inlined\" version of Vite's `loadEnv` function,\n * simplified somewhat to only support our use case.\n *\n * Ideally we'd just use `loadEnv` from Vite, but importing it\n * causes bundling issues due to node APIs and downstream dependencies.\n *\n * Vite is MIT licensed, copyright (c) Yuxi (Evan) You and Vite contributors.\n */\n\n/* eslint-disable no-process-env */\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport {parse} from 'dotenv'\nimport {expand} from 'dotenv-expand'\n\nexport function loadEnv(\n mode: string,\n envDir: string,\n prefixes: string[] = ['VITE_'],\n): Record<string, string> {\n if (mode === 'local') {\n throw new Error(\n `\"local\" cannot be used as a mode name because it conflicts with ` +\n `the .local postfix for .env files.`,\n )\n }\n\n const env: Record<string, string> = {}\n const envFiles = [\n /** default file */ `.env`,\n /** local file */ `.env.local`,\n /** mode file */ `.env.${mode}`,\n /** mode local file */ `.env.${mode}.local`,\n ]\n\n const parsed = Object.fromEntries(\n envFiles.flatMap((file) => {\n const envPath = lookupFile(envDir, [file], {\n rootDir: envDir,\n })\n if (!envPath) return []\n return Object.entries(parse(fs.readFileSync(envPath)))\n }),\n )\n\n // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this\n if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) {\n process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV\n }\n // support BROWSER and BROWSER_ARGS env variables\n if (parsed.BROWSER && process.env.BROWSER === undefined) {\n process.env.BROWSER = parsed.BROWSER\n }\n if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) {\n process.env.BROWSER_ARGS = parsed.BROWSER_ARGS\n }\n\n try {\n // let environment variables use each other\n expand({parsed})\n } catch (e) {\n // custom error handling until https://github.com/motdotla/dotenv-expand/issues/65 is fixed upstream\n // check for message \"TypeError: Cannot read properties of undefined (reading 'split')\"\n if (e.message.includes('split')) {\n throw new Error('dotenv-expand failed to expand env vars. Maybe you need to escape `$`?')\n }\n throw e\n }\n\n // only keys that start with prefix are exposed to client\n for (const [key, value] of Object.entries(parsed)) {\n if (prefixes.some((prefix) => key.startsWith(prefix))) {\n env[key] = value\n }\n }\n\n // check if there are actual env variables starting with VITE_*\n // these are typically provided inline and should be prioritized\n for (const key in process.env) {\n if (prefixes.some((prefix) => key.startsWith(prefix))) {\n env[key] = process.env[key] as string\n }\n }\n\n return env\n}\n\nfunction lookupFile(\n dir: string,\n formats: string[],\n options?: {\n rootDir?: string\n },\n): string | undefined {\n for (const format of formats) {\n const fullPath = path.join(dir, format)\n // eslint-disable-next-line no-sync\n if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {\n return fullPath\n }\n }\n const parentDir = path.dirname(dir)\n if (parentDir !== dir && (!options?.rootDir || parentDir.startsWith(options?.rootDir))) {\n return lookupFile(parentDir, formats, options)\n }\n\n return undefined\n}\n"],"names":["fs","path","version","debug","mainModule","parse","expand"],"mappings":";;;;;;;;AAOA,MAAM,cACJ,OAAO,uBAAwB,aAAa,0BAA0B;AAGjE,SAAS,eAAwB,SAAoB;AACpD,QAAA,MAAM,YAAY,OAAO;AAC/B,SAAO,IAAI,cAAc,IAAI,UAAU,IAAI,UAAU;AACvD;AAEA,eAAe,UAAU,YAAY;AC4C9B,SAAS,iBAAiB,KAAqC;AAE7D,SADU,mBAAmB,GAAG,KACV,oBAAoB,GAAG;AACtD;AA4BA,SAAS,oBAAoB,KAAqC;AAChE,QAAM,aAAa,KAAK,KAAK,KAAK,aAAa;AAE1C,SAAA,GAAG,WAAW,UAAU,IAItB;AAAA,IACL,QAAQ,eAAe,UAAU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SAAS,OAAO,IACtB,IAAI,MAAM,wEAAwE,IAEpF;AAAA,EAAA;AAIR,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM;AAC1C,aAAS,KAAK,CAAC,WAAW,IAAI,WAAW,MAAM,CAAC,MAClD,IAAI,GAAG,IAAI;AAMf,aAAW,OAAO,QAAQ;AACpB,aAAS,KAAK,CAAC,WAAW,IAAI,WAAW,MAAM,CAAC,MAClD,IAAI,GAAG,IAAI,QAAQ,IAAI,GAAG;AAIvB,SAAA;AACT;AAEA,SAAS,WACP,KACA,SACA,SAGoB;AACpB,aAAW,UAAU,SAAS;AAC5B,UAAM,WAAW,KAAK,KAAK,KAAK,MAAM;AAElC,QAAA,GAAG,WAAW,QAAQ,KAAK,GAAG,SAAS,QAAQ,EAAE,OAAO;AACnD,aAAA;AAAA,EAAA;AAGL,QAAA,YAAY,KAAK,QAAQ,GAAG;AAC9B,MAAA,cAAc,QAAQ,CAAC,SAAS,WAAW,UAAU,WAAW,SAAS,OAAO;AAC3E,WAAA,WAAW,WAAW,SAAS,OAAO;AAIjD;","x_google_ignoreList":[6,7]}
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/util/dynamicRequire.ts","../src/util/getCliConfig.ts","../src/debug.ts","../src/util/resolveRootDir.ts","../src/cliClient.ts","../src/config.ts","../../../../node_modules/.pnpm/dotenv@16.4.7/node_modules/dotenv/lib/main.js","../../../../node_modules/.pnpm/dotenv-expand@9.0.0/node_modules/dotenv-expand/lib/main.js","../src/util/loadEnv.ts"],"sourcesContent":["// Prevent webpack from bundling in webpack context,\n// use regular node require for unbundled context\n\n/* eslint-disable camelcase, no-undef */\ndeclare const __webpack_require__: boolean\ndeclare const __non_webpack_require__: typeof require\n\nconst requireFunc: typeof require =\n typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require\n/* eslint-enable camelcase, no-undef */\n\nexport function dynamicRequire<T = any>(request: string): T {\n const mod = requireFunc(request)\n return mod.__esModule && mod.default ? mod.default : mod\n}\n\ndynamicRequire.resolve = requireFunc.resolve\n","/* eslint-disable no-sync */\n\n/**\n * Reads the Sanity CLI config from one of the following files (in preferred order):\n * - sanity.cli.js\n * - sanity.cli.ts\n *\n * Note: There are two ways of using this:\n * a) `getCliConfig(cwd)`\n * b) `getCliConfig(cwd, {forked: true})`\n *\n * Approach a is generally a bit faster as it avoids the forking startup time, while\n * approach b could be considered \"safer\" since any side-effects of running the config\n * file will not bleed into the current CLI process directly.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport {Worker} from 'node:worker_threads'\n\nimport {type CliConfig, type SanityJson} from '../types'\nimport {getCliWorkerPath} from './cliWorker'\nimport {dynamicRequire} from './dynamicRequire'\n\nexport type CliMajorVersion = 2 | 3\n\nexport type CliConfigResult =\n | {config: SanityJson; path: string; version: 2}\n | {config: CliConfig; path: string; version: 3}\n | {config: null; path: string; version: CliMajorVersion}\n\nexport async function getCliConfig(\n cwd: string,\n {forked}: {forked?: boolean} = {},\n): Promise<CliConfigResult | null> {\n if (forked) {\n try {\n return await getCliConfigForked(cwd)\n } catch (err) {\n // Intentional noop - try unforked variant\n }\n }\n\n const {unregister} = __DEV__\n ? {unregister: () => undefined}\n : require('esbuild-register/dist/node').register({supported: {'dynamic-import': true}})\n\n try {\n const v3Config = getSanityCliConfig(cwd)\n if (v3Config) {\n return v3Config\n }\n\n return getSanityJsonConfig(cwd)\n } catch (err) {\n throw err\n } finally {\n unregister()\n }\n}\n\nexport function getCliConfigSync(cwd: string): CliConfigResult | null {\n const v3Config = getSanityCliConfig(cwd)\n return v3Config ? v3Config : getSanityJsonConfig(cwd)\n}\n\nasync function getCliConfigForked(cwd: string): Promise<CliConfigResult | null> {\n const workerPath = await getCliWorkerPath('getCliConfig')\n return new Promise((resolve, reject) => {\n const worker = new Worker(workerPath, {\n workerData: cwd,\n // eslint-disable-next-line no-process-env\n env: process.env,\n })\n worker.on('message', (message) => {\n if (message.type === 'config') {\n resolve(message.config)\n } else {\n const error = new Error(message.error)\n ;(error as any).type = message.errorType\n reject(new Error(message.error))\n }\n })\n worker.on('error', reject)\n worker.on('exit', (code) => {\n if (code !== 0) {\n reject(new Error(`Worker stopped with exit code ${code}`))\n }\n })\n })\n}\n\nfunction getSanityJsonConfig(cwd: string): CliConfigResult | null {\n const configPath = path.join(cwd, 'sanity.json')\n\n if (!fs.existsSync(configPath)) {\n return null\n }\n\n return {\n config: loadJsonConfig(configPath),\n path: configPath,\n version: 2,\n }\n}\n\nfunction getSanityCliConfig(cwd: string): CliConfigResult | null {\n const jsConfigPath = path.join(cwd, 'sanity.cli.js')\n const tsConfigPath = path.join(cwd, 'sanity.cli.ts')\n\n const [js, ts] = [fs.existsSync(jsConfigPath), fs.existsSync(tsConfigPath)]\n\n if (!js && !ts) {\n return null\n }\n\n if (!js && ts) {\n return {\n config: importConfig(tsConfigPath),\n path: tsConfigPath,\n version: 3,\n }\n }\n\n if (js && ts) {\n warn('Found both `sanity.cli.js` and `sanity.cli.ts` - using sanity.cli.js')\n }\n\n return {\n config: importConfig(jsConfigPath),\n path: jsConfigPath,\n version: 3,\n }\n}\n\nfunction loadJsonConfig(filePath: string): SanityJson | null {\n try {\n const content = fs.readFileSync(filePath, 'utf8')\n return JSON.parse(content)\n } catch (err) {\n console.error(`Error reading \"${filePath}\": ${err.message}`)\n return null\n }\n}\n\nfunction importConfig(filePath: string): CliConfig | null {\n try {\n const config = dynamicRequire<CliConfig | {default: CliConfig} | null>(filePath)\n if (config === null || typeof config !== 'object') {\n throw new Error('Module export is not a configuration object')\n }\n\n return 'default' in config ? config.default : config\n } catch (err) {\n // If attempting to import `defineCliConfig` or similar from `sanity/cli`,\n // accept the fact that it might not be installed. Instead, let the CLI\n // give a warning about the `sanity` module not being installed\n if (err.code === 'MODULE_NOT_FOUND' && err.message.includes('sanity/cli')) {\n return null\n }\n\n console.error(`Error reading \"${filePath}\": ${err.message}`)\n return null\n }\n}\n\nfunction warn(warning: string) {\n if (typeof process.send === 'function') {\n process.send({type: 'warning', warning})\n } else {\n console.warn(warning)\n }\n}\n","import debugIt from 'debug'\n\nexport const debug = debugIt('sanity:cli')\n","/* eslint-disable no-sync */\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport {debug} from '../debug'\n\n/**\n * Resolve project root directory, falling back to cwd if it cannot be found\n */\nexport function resolveRootDir(cwd: string): string {\n try {\n return resolveProjectRoot(cwd) || cwd\n } catch (err) {\n throw new Error(`Error occurred trying to resolve project root:\\n${err.message}`)\n }\n}\n\nfunction hasSanityConfig(basePath: string, configName: string): boolean {\n const buildConfigs = [\n fileExists(path.join(basePath, `${configName}.js`)),\n fileExists(path.join(basePath, `${configName}.ts`)),\n isSanityV2StudioRoot(basePath),\n ]\n\n return buildConfigs.some(Boolean)\n}\n\nfunction resolveProjectRoot(basePath: string, iterations = 0): string | false {\n const configName = 'sanity.config'\n if (hasSanityConfig(basePath, configName)) {\n return basePath\n }\n\n const parentDir = path.resolve(basePath, '..')\n if (parentDir === basePath || iterations > 30) {\n // Reached root (or max depth), give up\n return false\n }\n\n return resolveProjectRoot(parentDir, iterations + 1)\n}\n\nfunction isSanityV2StudioRoot(basePath: string): boolean {\n try {\n const content = fs.readFileSync(path.join(basePath, 'sanity.json'), 'utf8')\n const sanityJson = JSON.parse(content)\n const isRoot = Boolean(sanityJson?.root)\n if (isRoot) {\n debug('Found Sanity v2 studio root at %s', basePath)\n }\n return isRoot\n } catch (err) {\n return false\n }\n}\n\nfunction fileExists(filePath: string): boolean {\n return fs.existsSync(filePath)\n}\n","import {createClient, type SanityClient} from '@sanity/client'\n\nimport {getCliConfigSync} from './util/getCliConfig'\nimport {resolveRootDir} from './util/resolveRootDir'\n\nexport interface CliClientOptions {\n cwd?: string\n\n projectId?: string\n dataset?: string\n useCdn?: boolean\n token?: string\n apiVersion?: string\n}\n\nexport function getCliClient(options: CliClientOptions = {}): SanityClient {\n if (typeof process !== 'object') {\n throw new Error('getCliClient() should only be called from node.js scripts')\n }\n\n const {\n // eslint-disable-next-line no-process-env\n cwd = process.env.SANITY_BASE_PATH || process.cwd(),\n useCdn = false,\n apiVersion = '2022-06-06',\n projectId,\n dataset,\n token = getCliClient.__internal__getToken(),\n } = options\n\n if (projectId && dataset) {\n return createClient({projectId, dataset, apiVersion, useCdn, token})\n }\n\n const rootDir = resolveRootDir(cwd)\n const {config} = getCliConfigSync(rootDir) || {}\n if (!config) {\n throw new Error('Unable to resolve CLI configuration')\n }\n\n const apiConfig = config?.api || {}\n if (!apiConfig.projectId || !apiConfig.dataset) {\n throw new Error('Unable to resolve project ID/dataset from CLI configuration')\n }\n\n return createClient({\n projectId: apiConfig.projectId,\n dataset: apiConfig.dataset,\n apiVersion,\n useCdn,\n token,\n })\n}\n\n/* eslint-disable camelcase */\n/**\n * @internal\n * @deprecated This is only for INTERNAL use, and should not be relied upon outside of official Sanity modules\n * @returns A token to use when constructing a client without a `token` explicitly defined, or undefined\n */\ngetCliClient.__internal__getToken = (): string | undefined => undefined\n/* eslint-enable camelcase */\n","import {type CliConfig} from './types'\n\n/** @beta */\nexport function defineCliConfig(config: CliConfig): CliConfig {\n return config\n}\n\n/**\n * @deprecated Use `defineCliConfig` instead\n * @beta\n */\nexport function createCliConfig(config: CliConfig): CliConfig {\n return config\n}\n","const fs = require('fs')\nconst path = require('path')\nconst os = require('os')\nconst crypto = require('crypto')\nconst packageJson = require('../package.json')\n\nconst version = packageJson.version\n\nconst LINE = /(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/mg\n\n// Parse src into an Object\nfunction parse (src) {\n const obj = {}\n\n // Convert buffer to string\n let lines = src.toString()\n\n // Convert line breaks to same format\n lines = lines.replace(/\\r\\n?/mg, '\\n')\n\n let match\n while ((match = LINE.exec(lines)) != null) {\n const key = match[1]\n\n // Default undefined or null to empty string\n let value = (match[2] || '')\n\n // Remove whitespace\n value = value.trim()\n\n // Check if double quoted\n const maybeQuote = value[0]\n\n // Remove surrounding quotes\n value = value.replace(/^(['\"`])([\\s\\S]*)\\1$/mg, '$2')\n\n // Expand newlines if double quoted\n if (maybeQuote === '\"') {\n value = value.replace(/\\\\n/g, '\\n')\n value = value.replace(/\\\\r/g, '\\r')\n }\n\n // Add to object\n obj[key] = value\n }\n\n return obj\n}\n\nfunction _parseVault (options) {\n const vaultPath = _vaultPath(options)\n\n // Parse .env.vault\n const result = DotenvModule.configDotenv({ path: vaultPath })\n if (!result.parsed) {\n const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)\n err.code = 'MISSING_DATA'\n throw err\n }\n\n // handle scenario for comma separated keys - for use with key rotation\n // example: DOTENV_KEY=\"dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod\"\n const keys = _dotenvKey(options).split(',')\n const length = keys.length\n\n let decrypted\n for (let i = 0; i < length; i++) {\n try {\n // Get full key\n const key = keys[i].trim()\n\n // Get instructions for decrypt\n const attrs = _instructions(result, key)\n\n // Decrypt\n decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)\n\n break\n } catch (error) {\n // last key\n if (i + 1 >= length) {\n throw error\n }\n // try next key\n }\n }\n\n // Parse decrypted .env string\n return DotenvModule.parse(decrypted)\n}\n\nfunction _log (message) {\n console.log(`[dotenv@${version}][INFO] ${message}`)\n}\n\nfunction _warn (message) {\n console.log(`[dotenv@${version}][WARN] ${message}`)\n}\n\nfunction _debug (message) {\n console.log(`[dotenv@${version}][DEBUG] ${message}`)\n}\n\nfunction _dotenvKey (options) {\n // prioritize developer directly setting options.DOTENV_KEY\n if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {\n return options.DOTENV_KEY\n }\n\n // secondary infra already contains a DOTENV_KEY environment variable\n if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {\n return process.env.DOTENV_KEY\n }\n\n // fallback to empty string\n return ''\n}\n\nfunction _instructions (result, dotenvKey) {\n // Parse DOTENV_KEY. Format is a URI\n let uri\n try {\n uri = new URL(dotenvKey)\n } catch (error) {\n if (error.code === 'ERR_INVALID_URL') {\n const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n throw error\n }\n\n // Get decrypt key\n const key = uri.password\n if (!key) {\n const err = new Error('INVALID_DOTENV_KEY: Missing key part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get environment\n const environment = uri.searchParams.get('environment')\n if (!environment) {\n const err = new Error('INVALID_DOTENV_KEY: Missing environment part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get ciphertext payload\n const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`\n const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION\n if (!ciphertext) {\n const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)\n err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'\n throw err\n }\n\n return { ciphertext, key }\n}\n\nfunction _vaultPath (options) {\n let possibleVaultPath = null\n\n if (options && options.path && options.path.length > 0) {\n if (Array.isArray(options.path)) {\n for (const filepath of options.path) {\n if (fs.existsSync(filepath)) {\n possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`\n }\n }\n } else {\n possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`\n }\n } else {\n possibleVaultPath = path.resolve(process.cwd(), '.env.vault')\n }\n\n if (fs.existsSync(possibleVaultPath)) {\n return possibleVaultPath\n }\n\n return null\n}\n\nfunction _resolveHome (envPath) {\n return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath\n}\n\nfunction _configVault (options) {\n _log('Loading env from encrypted .env.vault')\n\n const parsed = DotenvModule._parseVault(options)\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsed, options)\n\n return { parsed }\n}\n\nfunction configDotenv (options) {\n const dotenvPath = path.resolve(process.cwd(), '.env')\n let encoding = 'utf8'\n const debug = Boolean(options && options.debug)\n\n if (options && options.encoding) {\n encoding = options.encoding\n } else {\n if (debug) {\n _debug('No encoding is specified. UTF-8 is used by default')\n }\n }\n\n let optionPaths = [dotenvPath] // default, look for .env\n if (options && options.path) {\n if (!Array.isArray(options.path)) {\n optionPaths = [_resolveHome(options.path)]\n } else {\n optionPaths = [] // reset default\n for (const filepath of options.path) {\n optionPaths.push(_resolveHome(filepath))\n }\n }\n }\n\n // Build the parsed data in a temporary object (because we need to return it). Once we have the final\n // parsed data, we will combine it with process.env (or options.processEnv if provided).\n let lastError\n const parsedAll = {}\n for (const path of optionPaths) {\n try {\n // Specifying an encoding returns a string instead of a buffer\n const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))\n\n DotenvModule.populate(parsedAll, parsed, options)\n } catch (e) {\n if (debug) {\n _debug(`Failed to load ${path} ${e.message}`)\n }\n lastError = e\n }\n }\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsedAll, options)\n\n if (lastError) {\n return { parsed: parsedAll, error: lastError }\n } else {\n return { parsed: parsedAll }\n }\n}\n\n// Populates process.env from .env file\nfunction config (options) {\n // fallback to original dotenv if DOTENV_KEY is not set\n if (_dotenvKey(options).length === 0) {\n return DotenvModule.configDotenv(options)\n }\n\n const vaultPath = _vaultPath(options)\n\n // dotenvKey exists but .env.vault file does not exist\n if (!vaultPath) {\n _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)\n\n return DotenvModule.configDotenv(options)\n }\n\n return DotenvModule._configVault(options)\n}\n\nfunction decrypt (encrypted, keyStr) {\n const key = Buffer.from(keyStr.slice(-64), 'hex')\n let ciphertext = Buffer.from(encrypted, 'base64')\n\n const nonce = ciphertext.subarray(0, 12)\n const authTag = ciphertext.subarray(-16)\n ciphertext = ciphertext.subarray(12, -16)\n\n try {\n const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)\n aesgcm.setAuthTag(authTag)\n return `${aesgcm.update(ciphertext)}${aesgcm.final()}`\n } catch (error) {\n const isRange = error instanceof RangeError\n const invalidKeyLength = error.message === 'Invalid key length'\n const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'\n\n if (isRange || invalidKeyLength) {\n const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n } else if (decryptionFailed) {\n const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')\n err.code = 'DECRYPTION_FAILED'\n throw err\n } else {\n throw error\n }\n }\n}\n\n// Populate process.env with parsed values\nfunction populate (processEnv, parsed, options = {}) {\n const debug = Boolean(options && options.debug)\n const override = Boolean(options && options.override)\n\n if (typeof parsed !== 'object') {\n const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')\n err.code = 'OBJECT_REQUIRED'\n throw err\n }\n\n // Set process.env\n for (const key of Object.keys(parsed)) {\n if (Object.prototype.hasOwnProperty.call(processEnv, key)) {\n if (override === true) {\n processEnv[key] = parsed[key]\n }\n\n if (debug) {\n if (override === true) {\n _debug(`\"${key}\" is already defined and WAS overwritten`)\n } else {\n _debug(`\"${key}\" is already defined and was NOT overwritten`)\n }\n }\n } else {\n processEnv[key] = parsed[key]\n }\n }\n}\n\nconst DotenvModule = {\n configDotenv,\n _configVault,\n _parseVault,\n config,\n decrypt,\n parse,\n populate\n}\n\nmodule.exports.configDotenv = DotenvModule.configDotenv\nmodule.exports._configVault = DotenvModule._configVault\nmodule.exports._parseVault = DotenvModule._parseVault\nmodule.exports.config = DotenvModule.config\nmodule.exports.decrypt = DotenvModule.decrypt\nmodule.exports.parse = DotenvModule.parse\nmodule.exports.populate = DotenvModule.populate\n\nmodule.exports = DotenvModule\n","'use strict'\n\nfunction _interpolate (envValue, environment, config) {\n const matches = envValue.match(/(.?\\${*[\\w]*(?::-[\\w/]*)?}*)/g) || []\n\n return matches.reduce(function (newEnv, match, index) {\n const parts = /(.?)\\${*([\\w]*(?::-[\\w/]*)?)?}*/g.exec(match)\n if (!parts || parts.length === 0) {\n return newEnv\n }\n\n const prefix = parts[1]\n\n let value, replacePart\n\n if (prefix === '\\\\') {\n replacePart = parts[0]\n value = replacePart.replace('\\\\$', '$')\n } else {\n const keyParts = parts[2].split(':-')\n const key = keyParts[0]\n replacePart = parts[0].substring(prefix.length)\n // process.env value 'wins' over .env file's value\n value = Object.prototype.hasOwnProperty.call(environment, key)\n ? environment[key]\n : (config.parsed[key] || keyParts[1] || '')\n\n // If the value is found, remove nested expansions.\n if (keyParts.length > 1 && value) {\n const replaceNested = matches[index + 1]\n matches[index + 1] = ''\n\n newEnv = newEnv.replace(replaceNested, '')\n }\n // Resolve recursive interpolations\n value = _interpolate(value, environment, config)\n }\n\n return newEnv.replace(replacePart, value)\n }, envValue)\n}\n\nfunction expand (config) {\n // if ignoring process.env, use a blank object\n const environment = config.ignoreProcessEnv ? {} : process.env\n\n for (const configKey in config.parsed) {\n const value = Object.prototype.hasOwnProperty.call(environment, configKey) ? environment[configKey] : config.parsed[configKey]\n\n config.parsed[configKey] = _interpolate(value, environment, config)\n }\n\n for (const processKey in config.parsed) {\n environment[processKey] = config.parsed[processKey]\n }\n\n return config\n}\n\nmodule.exports.expand = expand\n","/**\n * This is an \"inlined\" version of Vite's `loadEnv` function,\n * simplified somewhat to only support our use case.\n *\n * Ideally we'd just use `loadEnv` from Vite, but importing it\n * causes bundling issues due to node APIs and downstream dependencies.\n *\n * Vite is MIT licensed, copyright (c) Yuxi (Evan) You and Vite contributors.\n */\n\n/* eslint-disable no-process-env */\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport {parse} from 'dotenv'\nimport {expand} from 'dotenv-expand'\n\nexport function loadEnv(\n mode: string,\n envDir: string,\n prefixes: string[] = ['VITE_'],\n): Record<string, string> {\n if (mode === 'local') {\n throw new Error(\n `\"local\" cannot be used as a mode name because it conflicts with ` +\n `the .local postfix for .env files.`,\n )\n }\n\n const env: Record<string, string> = {}\n const envFiles = [\n /** default file */ `.env`,\n /** local file */ `.env.local`,\n /** mode file */ `.env.${mode}`,\n /** mode local file */ `.env.${mode}.local`,\n ]\n\n const parsed = Object.fromEntries(\n envFiles.flatMap((file) => {\n const envPath = lookupFile(envDir, [file], {\n rootDir: envDir,\n })\n if (!envPath) return []\n return Object.entries(parse(fs.readFileSync(envPath)))\n }),\n )\n\n // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this\n if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) {\n process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV\n }\n // support BROWSER and BROWSER_ARGS env variables\n if (parsed.BROWSER && process.env.BROWSER === undefined) {\n process.env.BROWSER = parsed.BROWSER\n }\n if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) {\n process.env.BROWSER_ARGS = parsed.BROWSER_ARGS\n }\n\n try {\n // let environment variables use each other\n expand({parsed})\n } catch (e) {\n // custom error handling until https://github.com/motdotla/dotenv-expand/issues/65 is fixed upstream\n // check for message \"TypeError: Cannot read properties of undefined (reading 'split')\"\n if (e.message.includes('split')) {\n throw new Error('dotenv-expand failed to expand env vars. Maybe you need to escape `$`?')\n }\n throw e\n }\n\n // only keys that start with prefix are exposed to client\n for (const [key, value] of Object.entries(parsed)) {\n if (prefixes.some((prefix) => key.startsWith(prefix))) {\n env[key] = value\n }\n }\n\n // check if there are actual env variables starting with VITE_*\n // these are typically provided inline and should be prioritized\n for (const key in process.env) {\n if (prefixes.some((prefix) => key.startsWith(prefix))) {\n env[key] = process.env[key] as string\n }\n }\n\n return env\n}\n\nfunction lookupFile(\n dir: string,\n formats: string[],\n options?: {\n rootDir?: string\n },\n): string | undefined {\n for (const format of formats) {\n const fullPath = path.join(dir, format)\n // eslint-disable-next-line no-sync\n if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {\n return fullPath\n }\n }\n const parentDir = path.dirname(dir)\n if (parentDir !== dir && (!options?.rootDir || parentDir.startsWith(options?.rootDir))) {\n return lookupFile(parentDir, formats, options)\n }\n\n return undefined\n}\n"],"names":["fs","path","version","debug","mainModule","parse","expand"],"mappings":";;;;;;;;AAOA,MAAM,cACJ,OAAO,uBAAwB,aAAa,0BAA0B;AAGjE,SAAS,eAAwB,SAAoB;AACpD,QAAA,MAAM,YAAY,OAAO;AAC/B,SAAO,IAAI,cAAc,IAAI,UAAU,IAAI,UAAU;AACvD;AAEA,eAAe,UAAU,YAAY;AC4C9B,SAAS,iBAAiB,KAAqC;AAE7D,SADU,mBAAmB,GAAG,KACV,oBAAoB,GAAG;AACtD;AA4BA,SAAS,oBAAoB,KAAqC;AAChE,QAAM,aAAa,KAAK,KAAK,KAAK,aAAa;AAE1C,SAAA,GAAG,WAAW,UAAU,IAItB;AAAA,IACL,QAAQ,eAAe,UAAU;AAAA,IACjC,MAAM;AAAA,IACN,SAAS;AAAA,EAAA,IANF;AAQX;AAEA,SAAS,mBAAmB,KAAqC;AACzD,QAAA,eAAe,KAAK,KAAK,KAAK,eAAe,GAC7C,eAAe,KAAK,KAAK,KAAK,eAAe,GAE7C,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,WAAW,YAAY,GAAG,GAAG,WAAW,YAAY,CAAC;AAE1E,SAAI,CAAC,MAAM,CAAC,KACH,OAGL,CAAC,MAAM,KACF;AAAA,IACL,QAAQ,aAAa,YAAY;AAAA,IACjC,MAAM;AAAA,IACN,SAAS;AAAA,EAIT,KAAA,MAAM,MACR,KAAK,sEAAsE,GAGtE;AAAA,IACL,QAAQ,aAAa,YAAY;AAAA,IACjC,MAAM;AAAA,IACN,SAAS;AAA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KAAK,QAAQ,GAAG;AAC9B,MAAA,cAAc,QAAQ,CAAC,SAAS,WAAW,UAAU,WAAW,SAAS,OAAO;AAC3E,WAAA,WAAW,WAAW,SAAS,OAAO;AAIjD;","x_google_ignoreList":[6,7]}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@sanity/cli",
|
3
|
-
"version": "3.77.3-server-side-schemas.
|
3
|
+
"version": "3.77.3-server-side-schemas.36+cd5f8b9685",
|
4
4
|
"description": "Sanity CLI tool for managing Sanity installations, managing plugins, schemas and datasets",
|
5
5
|
"keywords": [
|
6
6
|
"sanity",
|
@@ -57,31 +57,32 @@
|
|
57
57
|
},
|
58
58
|
"dependencies": {
|
59
59
|
"@babel/traverse": "^7.23.5",
|
60
|
-
"@sanity/client": "^6.28.
|
61
|
-
"@sanity/codegen": "3.77.3-server-side-schemas.
|
60
|
+
"@sanity/client": "^6.28.3",
|
61
|
+
"@sanity/codegen": "3.77.3-server-side-schemas.36+cd5f8b9685",
|
62
|
+
"@sanity/runtime-cli": "^1.1.1",
|
62
63
|
"@sanity/telemetry": "^0.7.7",
|
63
64
|
"@sanity/template-validator": "^2.4.0",
|
64
|
-
"@sanity/util": "3.77.3-server-side-schemas.
|
65
|
+
"@sanity/util": "3.77.3-server-side-schemas.36+cd5f8b9685",
|
65
66
|
"chalk": "^4.1.2",
|
66
67
|
"debug": "^4.3.4",
|
67
68
|
"decompress": "^4.2.0",
|
68
69
|
"esbuild": "0.21.5",
|
69
70
|
"esbuild-register": "^3.5.0",
|
70
71
|
"get-it": "^8.6.7",
|
71
|
-
"groq-js": "^1.
|
72
|
+
"groq-js": "^1.16.1",
|
72
73
|
"pkg-dir": "^5.0.0",
|
73
74
|
"prettier": "^3.3.0",
|
74
75
|
"semver": "^7.3.5",
|
75
76
|
"validate-npm-package-name": "^3.0.0"
|
76
77
|
},
|
77
78
|
"devDependencies": {
|
78
|
-
"@repo/package.config": "3.
|
79
|
-
"@repo/test-config": "3.
|
79
|
+
"@repo/package.config": "3.79.0",
|
80
|
+
"@repo/test-config": "3.79.0",
|
80
81
|
"@rexxars/gitconfiglocal": "^3.0.1",
|
81
82
|
"@rollup/plugin-node-resolve": "^15.2.3",
|
82
83
|
"@sanity/eslint-config-studio": "^4.0.0",
|
83
84
|
"@sanity/generate-help-url": "^3.0.0",
|
84
|
-
"@sanity/types": "3.77.3-server-side-schemas.
|
85
|
+
"@sanity/types": "3.77.3-server-side-schemas.36+cd5f8b9685",
|
85
86
|
"@types/babel__traverse": "^7.20.5",
|
86
87
|
"@types/configstore": "^5.0.1",
|
87
88
|
"@types/cpx": "^1.5.2",
|
@@ -115,7 +116,7 @@
|
|
115
116
|
"minimist": "^1.2.5",
|
116
117
|
"open": "^8.4.0",
|
117
118
|
"ora": "^8.0.1",
|
118
|
-
"p-
|
119
|
+
"p-map": "^4.0.0",
|
119
120
|
"p-timeout": "^4.0.0",
|
120
121
|
"preferred-pm": "^3.0.3",
|
121
122
|
"promise-props-recursive": "^2.0.2",
|
@@ -126,12 +127,12 @@
|
|
126
127
|
"semver-compare": "^1.0.0",
|
127
128
|
"tar": "^6.1.11",
|
128
129
|
"vite": "^6.2.0",
|
129
|
-
"vitest": "^3.0.
|
130
|
+
"vitest": "^3.0.8",
|
130
131
|
"which": "^2.0.2",
|
131
132
|
"xdg-basedir": "^4.0.0"
|
132
133
|
},
|
133
134
|
"engines": {
|
134
135
|
"node": ">=18"
|
135
136
|
},
|
136
|
-
"gitHead": "
|
137
|
+
"gitHead": "cd5f8b968534b6b9eb3ce0ac884e2dfa88360cdc"
|
137
138
|
}
|
@@ -9,11 +9,11 @@ import {type CliCommandContext} from '../../types'
|
|
9
9
|
import {copy} from '../../util/copy'
|
10
10
|
import {getAndWriteJourneySchemaWorker} from '../../util/journeyConfig'
|
11
11
|
import {resolveLatestVersions} from '../../util/resolveLatestVersions'
|
12
|
+
import {createAppCliConfig} from './createAppCliConfig'
|
12
13
|
import {createCliConfig} from './createCliConfig'
|
13
|
-
import {createCoreAppCliConfig} from './createCoreAppCliConfig'
|
14
14
|
import {createPackageManifest} from './createPackageManifest'
|
15
15
|
import {createStudioConfig, type GenerateConfigOptions} from './createStudioConfig'
|
16
|
-
import {
|
16
|
+
import {determineAppTemplate} from './determineAppTemplate'
|
17
17
|
import {type ProjectTemplate} from './initProject'
|
18
18
|
import templates from './templates'
|
19
19
|
import {updateInitialTemplateMetadata} from './updateInitialTemplateMetadata'
|
@@ -40,7 +40,7 @@ export async function bootstrapLocalTemplate(
|
|
40
40
|
const {outputPath, templateName, useTypeScript, packageName, variables} = opts
|
41
41
|
const sourceDir = path.join(templatesDir, templateName)
|
42
42
|
const sharedDir = path.join(templatesDir, 'shared')
|
43
|
-
const
|
43
|
+
const isAppTemplate = determineAppTemplate(templateName)
|
44
44
|
|
45
45
|
// Check that we have a template info file (dependencies, plugins etc)
|
46
46
|
const template = templates[templateName]
|
@@ -83,8 +83,8 @@ export async function bootstrapLocalTemplate(
|
|
83
83
|
// Resolve latest versions of Sanity-dependencies
|
84
84
|
spinner = output.spinner('Resolving latest module versions').start()
|
85
85
|
const dependencyVersions = await resolveLatestVersions({
|
86
|
-
...(
|
87
|
-
...(
|
86
|
+
...(isAppTemplate ? {} : studioDependencies.dependencies),
|
87
|
+
...(isAppTemplate ? {} : studioDependencies.devDependencies),
|
88
88
|
...(template.dependencies || {}),
|
89
89
|
...(template.devDependencies || {}),
|
90
90
|
})
|
@@ -92,7 +92,7 @@ export async function bootstrapLocalTemplate(
|
|
92
92
|
|
93
93
|
// Use the resolved version for the given dependency
|
94
94
|
const dependencies = Object.keys({
|
95
|
-
...(
|
95
|
+
...(isAppTemplate ? {} : studioDependencies.dependencies),
|
96
96
|
...template.dependencies,
|
97
97
|
}).reduce(
|
98
98
|
(deps, dependency) => {
|
@@ -103,7 +103,7 @@ export async function bootstrapLocalTemplate(
|
|
103
103
|
)
|
104
104
|
|
105
105
|
const devDependencies = Object.keys({
|
106
|
-
...(
|
106
|
+
...(isAppTemplate ? {} : studioDependencies.devDependencies),
|
107
107
|
...template.devDependencies,
|
108
108
|
}).reduce(
|
109
109
|
(deps, dependency) => {
|
@@ -129,8 +129,8 @@ export async function bootstrapLocalTemplate(
|
|
129
129
|
})
|
130
130
|
|
131
131
|
// ...and a CLI config (`sanity.cli.[ts|js]`)
|
132
|
-
const cliConfig =
|
133
|
-
?
|
132
|
+
const cliConfig = isAppTemplate
|
133
|
+
? createAppCliConfig({
|
134
134
|
appLocation: template.appLocation!,
|
135
135
|
organizationId: variables.organizationId,
|
136
136
|
})
|
@@ -145,7 +145,7 @@ export async function bootstrapLocalTemplate(
|
|
145
145
|
await Promise.all(
|
146
146
|
[
|
147
147
|
...[
|
148
|
-
|
148
|
+
isAppTemplate
|
149
149
|
? Promise.resolve(null)
|
150
150
|
: writeFileIfNotExists(`sanity.config.${codeExt}`, studioConfig),
|
151
151
|
],
|
@@ -1,10 +1,10 @@
|
|
1
1
|
import {processTemplate} from './processTemplate'
|
2
2
|
|
3
|
-
const
|
3
|
+
const defaultAppTemplate = `
|
4
4
|
import {defineCliConfig} from 'sanity/cli'
|
5
5
|
|
6
6
|
export default defineCliConfig({
|
7
|
-
|
7
|
+
__experimental_appConfiguration: {
|
8
8
|
organizationId: '%organizationId%',
|
9
9
|
appLocation: '%appLocation%',
|
10
10
|
},
|
@@ -16,9 +16,9 @@ export interface GenerateCliConfigOptions {
|
|
16
16
|
appLocation: string
|
17
17
|
}
|
18
18
|
|
19
|
-
export function
|
19
|
+
export function createAppCliConfig(options: GenerateCliConfigOptions): string {
|
20
20
|
return processTemplate({
|
21
|
-
template:
|
21
|
+
template: defaultAppTemplate,
|
22
22
|
variables: options,
|
23
23
|
})
|
24
24
|
}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
const
|
1
|
+
const appTemplates = ['app-quickstart']
|
2
2
|
|
3
3
|
/**
|
4
4
|
* Determine if a given template is a studio template.
|
@@ -8,6 +8,6 @@ const coreAppTemplates = ['core-app']
|
|
8
8
|
* @param templateName - Name of the template
|
9
9
|
* @returns boolean indicating if the template is a studio template
|
10
10
|
*/
|
11
|
-
export function
|
12
|
-
return
|
11
|
+
export function determineAppTemplate(templateName: string): boolean {
|
12
|
+
return appTemplates.includes(templateName)
|
13
13
|
}
|
@@ -8,7 +8,7 @@ import {type detectFrameworkRecord} from '@vercel/fs-detectors'
|
|
8
8
|
import dotenv from 'dotenv'
|
9
9
|
import execa, {type CommonOptions} from 'execa'
|
10
10
|
import {deburr, noop} from 'lodash'
|
11
|
-
import
|
11
|
+
import pMap from 'p-map'
|
12
12
|
import resolveFrom from 'resolve-from'
|
13
13
|
import semver from 'semver'
|
14
14
|
|
@@ -49,7 +49,7 @@ import {createProject} from '../project/createProject'
|
|
49
49
|
import {bootstrapLocalTemplate} from './bootstrapLocalTemplate'
|
50
50
|
import {bootstrapRemoteTemplate} from './bootstrapRemoteTemplate'
|
51
51
|
import {type GenerateConfigOptions} from './createStudioConfig'
|
52
|
-
import {
|
52
|
+
import {determineAppTemplate} from './determineAppTemplate'
|
53
53
|
import {absolutify, validateEmptyPath} from './fsUtils'
|
54
54
|
import {tryGitInit} from './git'
|
55
55
|
import {promptForDatasetName} from './promptForDatasetName'
|
@@ -108,6 +108,16 @@ export interface ProjectOrganization {
|
|
108
108
|
slug: string
|
109
109
|
}
|
110
110
|
|
111
|
+
interface OrganizationCreateResponse {
|
112
|
+
id: string
|
113
|
+
name: string
|
114
|
+
createdByUserId: string
|
115
|
+
slug: string | null
|
116
|
+
defaultRoleName: string | null
|
117
|
+
members: unknown[]
|
118
|
+
features: unknown[]
|
119
|
+
}
|
120
|
+
|
111
121
|
// eslint-disable-next-line max-statements, complexity
|
112
122
|
export default async function initSanity(
|
113
123
|
args: CliCommandArguments<InitFlags>,
|
@@ -257,24 +267,25 @@ export default async function initSanity(
|
|
257
267
|
const hasToken = userConfig.get('authToken')
|
258
268
|
|
259
269
|
debug(hasToken ? 'User already has a token' : 'User has no token')
|
270
|
+
let user: SanityUser | undefined
|
260
271
|
if (hasToken) {
|
261
272
|
trace.log({step: 'login', alreadyLoggedIn: true})
|
262
|
-
|
273
|
+
user = await getUserData(apiClient)
|
263
274
|
success('You are logged in as %s using %s', user.email, getProviderName(user.provider))
|
264
275
|
} else if (!unattended) {
|
265
276
|
trace.log({step: 'login'})
|
266
|
-
await getOrCreateUser()
|
277
|
+
user = await getOrCreateUser()
|
267
278
|
}
|
268
279
|
|
269
280
|
// skip project / dataset prompting
|
270
|
-
const
|
281
|
+
const isAppTemplate = cliFlags.template ? determineAppTemplate(cliFlags.template) : false // Default to false
|
271
282
|
|
272
283
|
let introMessage = 'Fetching existing projects'
|
273
284
|
if (cliFlags.quickstart) {
|
274
285
|
introMessage = "Eject your existing project's Sanity configuration"
|
275
286
|
}
|
276
287
|
|
277
|
-
if (!
|
288
|
+
if (!isAppTemplate) {
|
278
289
|
success(introMessage)
|
279
290
|
print('')
|
280
291
|
}
|
@@ -667,13 +678,13 @@ export default async function initSanity(
|
|
667
678
|
if (isCurrentDir) {
|
668
679
|
print(`\n${chalk.green('Success!')} Now, use this command to continue:\n`)
|
669
680
|
print(
|
670
|
-
`${chalk.cyan(devCommand)} - to run ${
|
681
|
+
`${chalk.cyan(devCommand)} - to run ${isAppTemplate ? 'your Sanity application' : 'Sanity Studio'}\n`,
|
671
682
|
)
|
672
683
|
} else {
|
673
684
|
print(`\n${chalk.green('Success!')} Now, use these commands to continue:\n`)
|
674
685
|
print(`First: ${chalk.cyan(`cd ${outputPath}`)} - to enter project’s directory`)
|
675
686
|
print(
|
676
|
-
`Then: ${chalk.cyan(devCommand)} -to run ${
|
687
|
+
`Then: ${chalk.cyan(devCommand)} -to run ${isAppTemplate ? 'your Sanity application' : 'Sanity Studio'}\n`,
|
677
688
|
)
|
678
689
|
}
|
679
690
|
|
@@ -712,6 +723,7 @@ export default async function initSanity(
|
|
712
723
|
const {extOptions, ...otherArgs} = args
|
713
724
|
const loginArgs: CliCommandArguments<LoginFlags> = {...otherArgs, extOptions: {}}
|
714
725
|
await login(loginArgs, {...context, telemetry: trace.newContext('login')})
|
726
|
+
return getUserData(apiClient)
|
715
727
|
}
|
716
728
|
|
717
729
|
async function getProjectDetails(): Promise<{
|
@@ -736,18 +748,18 @@ export default async function initSanity(
|
|
736
748
|
return data
|
737
749
|
}
|
738
750
|
|
739
|
-
if (
|
751
|
+
if (isAppTemplate) {
|
740
752
|
const client = apiClient({requireUser: true, requireProject: false})
|
741
753
|
const organizations = await client.request({uri: '/organizations'})
|
742
754
|
|
743
|
-
const
|
755
|
+
const appOrganizationId = await getOrganizationId(organizations)
|
744
756
|
|
745
757
|
return {
|
746
758
|
projectId: '',
|
747
759
|
displayName: '',
|
748
760
|
datasetName: '',
|
749
761
|
isFirstProject: false,
|
750
|
-
organizationId:
|
762
|
+
organizationId: appOrganizationId,
|
751
763
|
}
|
752
764
|
}
|
753
765
|
|
@@ -858,7 +870,22 @@ export default async function initSanity(
|
|
858
870
|
? 'No projects found for user, prompting for name'
|
859
871
|
: 'Using a coupon - skipping project selection',
|
860
872
|
)
|
861
|
-
const projectName = await prompt.single({
|
873
|
+
const projectName = await prompt.single({
|
874
|
+
type: 'input',
|
875
|
+
message: 'Project name:',
|
876
|
+
default: 'My Sanity Project',
|
877
|
+
validate(input) {
|
878
|
+
if (!input || input.trim() === '') {
|
879
|
+
return 'Project name cannot be empty'
|
880
|
+
}
|
881
|
+
|
882
|
+
if (input.length > 80) {
|
883
|
+
return 'Project name cannot be longer than 80 characters'
|
884
|
+
}
|
885
|
+
|
886
|
+
return true
|
887
|
+
},
|
888
|
+
})
|
862
889
|
|
863
890
|
return createProject(apiClient, {
|
864
891
|
displayName: projectName,
|
@@ -1242,47 +1269,90 @@ export default async function initSanity(
|
|
1242
1269
|
return cliFlags
|
1243
1270
|
}
|
1244
1271
|
|
1272
|
+
async function createOrganization(
|
1273
|
+
props: {name?: string} = {},
|
1274
|
+
): Promise<OrganizationCreateResponse> {
|
1275
|
+
const name =
|
1276
|
+
props.name ||
|
1277
|
+
(await prompt.single({
|
1278
|
+
type: 'input',
|
1279
|
+
message: 'Organization name:',
|
1280
|
+
default: user ? user.name : undefined,
|
1281
|
+
validate(input) {
|
1282
|
+
if (input.length === 0) {
|
1283
|
+
return 'Organization name cannot be empty'
|
1284
|
+
} else if (input.length > 100) {
|
1285
|
+
return 'Organization name cannot be longer than 100 characters'
|
1286
|
+
}
|
1287
|
+
return true
|
1288
|
+
},
|
1289
|
+
}))
|
1290
|
+
|
1291
|
+
const spinner = context.output.spinner('Creating organization').start()
|
1292
|
+
const client = apiClient({requireProject: false, requireUser: true})
|
1293
|
+
const organization = await client.request({
|
1294
|
+
uri: '/organizations',
|
1295
|
+
method: 'POST',
|
1296
|
+
body: {name},
|
1297
|
+
})
|
1298
|
+
spinner.succeed()
|
1299
|
+
|
1300
|
+
return organization
|
1301
|
+
}
|
1302
|
+
|
1245
1303
|
async function getOrganizationId(organizations: ProjectOrganization[]) {
|
1246
|
-
|
1247
|
-
|
1248
|
-
|
1304
|
+
// In unattended mode, if the user hasn't specified an organization, sending null as
|
1305
|
+
// organization ID to the API will create a new organization for the user with their
|
1306
|
+
// user name. If they _have_ specified an organization, we'll use that.
|
1307
|
+
if (unattended || flags.organization) {
|
1308
|
+
return flags.organization || undefined
|
1249
1309
|
}
|
1250
1310
|
|
1251
|
-
|
1252
|
-
if
|
1253
|
-
|
1254
|
-
|
1255
|
-
|
1256
|
-
debug('User lacks project attach grant in all organizations, not prompting')
|
1257
|
-
return undefined
|
1258
|
-
}
|
1311
|
+
// If the user has no organizations, prompt them to create one with the same name as
|
1312
|
+
// their user, but allow them to customize it if they want
|
1313
|
+
if (organizations.length === 0) {
|
1314
|
+
return createOrganization().then((org) => org.id)
|
1315
|
+
}
|
1259
1316
|
|
1260
|
-
|
1261
|
-
|
1262
|
-
|
1263
|
-
|
1264
|
-
|
1265
|
-
|
1266
|
-
|
1267
|
-
|
1268
|
-
|
1269
|
-
|
1270
|
-
|
1271
|
-
|
1272
|
-
|
1273
|
-
|
1274
|
-
|
1317
|
+
// If the user has organizations, let them choose from them, but also allow them to
|
1318
|
+
// create a new one in case they do not have access to any of them, or they want to
|
1319
|
+
// create a personal/other organization.
|
1320
|
+
debug(`User has ${organizations.length} organization(s), checking attach access`)
|
1321
|
+
const withGrantInfo = await getOrganizationsWithAttachGrantInfo(organizations)
|
1322
|
+
const withAttach = withGrantInfo.filter(({hasAttachGrant}) => hasAttachGrant)
|
1323
|
+
|
1324
|
+
debug('User has attach access to %d organizations.', withAttach.length)
|
1325
|
+
const organizationChoices = [
|
1326
|
+
...withGrantInfo.map(({organization, hasAttachGrant}) => ({
|
1327
|
+
value: organization.id,
|
1328
|
+
name: `${organization.name} [${organization.id}]`,
|
1329
|
+
disabled: hasAttachGrant ? false : 'Insufficient permissions',
|
1330
|
+
})),
|
1331
|
+
new prompt.Separator(),
|
1332
|
+
{value: '-new-', name: 'Create new organization'},
|
1333
|
+
new prompt.Separator(),
|
1334
|
+
]
|
1335
|
+
|
1336
|
+
// If the user only has a single organization (and they have attach access to it),
|
1337
|
+
// we'll default to that one. Otherwise, we'll default to the organization with the
|
1338
|
+
// same name as the user if it exists.
|
1339
|
+
const defaultOrganizationId =
|
1340
|
+
withAttach.length === 1
|
1341
|
+
? withAttach[0].organization.id
|
1342
|
+
: organizations.find((org) => org.name === user?.name)?.id
|
1343
|
+
|
1344
|
+
const chosenOrg = await prompt.single({
|
1345
|
+
message: 'Select organization:',
|
1346
|
+
type: 'list',
|
1347
|
+
default: defaultOrganizationId || undefined,
|
1348
|
+
choices: organizationChoices,
|
1349
|
+
})
|
1275
1350
|
|
1276
|
-
|
1277
|
-
|
1278
|
-
}
|
1279
|
-
} else if (orgId) {
|
1280
|
-
debug(`User has defined organization flag explicitly (%s)`, orgId)
|
1281
|
-
} else if (organizations.length === 0) {
|
1282
|
-
debug('User has no organizations, skipping selection prompt')
|
1351
|
+
if (chosenOrg === '-new-') {
|
1352
|
+
return createOrganization().then((org) => org.id)
|
1283
1353
|
}
|
1284
1354
|
|
1285
|
-
return
|
1355
|
+
return chosenOrg || undefined
|
1286
1356
|
}
|
1287
1357
|
|
1288
1358
|
async function hasProjectAttachGrant(orgId: string) {
|
@@ -1301,8 +1371,15 @@ export default async function initSanity(
|
|
1301
1371
|
)
|
1302
1372
|
}
|
1303
1373
|
|
1304
|
-
function
|
1305
|
-
return
|
1374
|
+
function getOrganizationsWithAttachGrantInfo(organizations: ProjectOrganization[]) {
|
1375
|
+
return pMap(
|
1376
|
+
organizations,
|
1377
|
+
async (organization) => ({
|
1378
|
+
hasAttachGrant: await hasProjectAttachGrant(organization.id),
|
1379
|
+
organization,
|
1380
|
+
}),
|
1381
|
+
{concurrency: 3},
|
1382
|
+
)
|
1306
1383
|
}
|
1307
1384
|
|
1308
1385
|
async function createOrAppendEnvVars(
|