UNPKG

sanity

Version:

Sanity is a real-time content infrastructure with a scalable, hosted backend featuring a Graph Oriented Query Language (GROQ), asset pipelines and fast edge caches

259 lines (256 loc) • 10.4 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target, mod )); var path = require("node:path"), chalk = require("chalk"), logSymbols = require("log-symbols"), semver = require("semver"), helpers = require("yargs/helpers"), yargs = require("yargs/yargs"), _internal = require("./_internal.js"), runtime = require("./runtime.js"), upgradePackages = require("./upgradePackages.js"), shouldAutoUpdate = require("./shouldAutoUpdate.js"), servers = require("./servers.js"), timing = require("./timing.js"); function _interopDefaultCompat(e) { return e && typeof e == "object" && "default" in e ? e : { default: e }; } var path__default = /* @__PURE__ */ _interopDefaultCompat(path), chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk), semver__default = /* @__PURE__ */ _interopDefaultCompat(semver), yargs__default = /* @__PURE__ */ _interopDefaultCompat(yargs); async function startDevServer(options) { const { cwd, httpPort, httpHost, basePath, reactStrictMode, vite: extendViteConfig, reactCompiler, entry, isApp } = options; runtime.debug("Writing Sanity runtime files"), await runtime.writeSanityRuntime({ cwd, reactStrictMode, watch: !0, basePath, entry, isApp }), runtime.debug("Resolving vite config"); const mode = "development"; let viteConfig = await runtime.getViteConfig({ basePath, mode: "development", server: { port: httpPort, host: httpHost }, cwd, reactCompiler, isApp }); extendViteConfig && (viteConfig = await runtime.extendViteConfigWithUserConfig({ command: "serve", mode }, viteConfig, extendViteConfig)), runtime.debug("Creating vite server"); const { createServer } = await import("vite"), server = await createServer(viteConfig); return runtime.debug("Listening on specified port"), await server.listen(), { server, close: () => server.close() }; } const debug = _internal.debug.extend("dev"), getDefaultCoreURL = ({ organizationId, url }) => { const params = new URLSearchParams({ url }); return process.env.SANITY_INTERNAL_ENV === "staging" ? `https://sanity.work/@${organizationId}?${params.toString()}` : `https://sanity.io/@${organizationId}?${params.toString()}`; }, getCoreApiURL = () => process.env.SANITY_INTERNAL_ENV === "staging" ? "https://sanity.work" : "https://sanity.io", getCoreURL = async ({ fetchFn = globalThis.fetch, timeout = 5e3, organizationId, url }) => { const abortController = new AbortController(), timer = setTimeout(() => abortController.abort(), timeout); try { const queryParams = new URLSearchParams({ organizationId, url }), res = await fetchFn(`${getCoreApiURL()}/api/dashboard/mode/development/resolve-url?${queryParams.toString()}`, { signal: abortController.signal }); return res.ok ? (await res.json()).url : (debug(`Failed to fetch core URL: ${res.statusText}`), getDefaultCoreURL({ organizationId, url })); } catch (err) { return debug(`Failed to fetch core URL: ${err.message}`), getDefaultCoreURL({ organizationId, url }); } finally { clearTimeout(timer); } }, getCoreAppURL = async ({ organizationId, httpHost = "localhost", httpPort = 3333 }) => await getCoreURL({ organizationId, url: `http://${httpHost}:${httpPort}` }); function parseCliFlags(args) { return yargs__default.default(helpers.hideBin(args.argv || process.argv).slice(1)).options("host", { type: "string" }).options("port", { type: "number" }).options("auto-updates", { type: "boolean" }).option("load-in-dashboard", { type: "boolean", default: !1 }).argv; } async function startSanityDevServer(args, context) { const timers = timing.getTimer(), flags = await parseCliFlags(args), { output, apiClient, workDir, cliConfig, prompt } = context, { loadInDashboard } = flags; if (timers.start("checkStudioDependencyVersions"), await upgradePackages.checkStudioDependencyVersions(workDir), timers.end("checkStudioDependencyVersions"), (await upgradePackages.checkRequiredDependencies(context)).didInstall) return; const { didInstall, installedSanityVersion } = await upgradePackages.checkRequiredDependencies(context); if (didInstall) return; const autoUpdatesEnabled = shouldAutoUpdate.shouldAutoUpdate({ flags, cliConfig }), cleanSanityVersion = semver__default.default.parse(installedSanityVersion)?.version; if (autoUpdatesEnabled && !cleanSanityVersion) throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`); const version = encodeURIComponent(`^${cleanSanityVersion}`), autoUpdatesImports = shouldAutoUpdate.getStudioAutoUpdateImportMap(version); if (autoUpdatesEnabled) { output.print(`${logSymbols.info} Running with auto-updates enabled`); let result; try { result = await shouldAutoUpdate.compareDependencyVersions(autoUpdatesImports, workDir); } catch (err) { console.warn(new Error("Failed to compare local versions against auto-updating versions", { cause: err })); } if (result?.length) { const message = `The following local package versions are different from the versions currently served at runtime. When using auto updates, we recommend that you run with the same versions locally as will be used when deploying. ${result.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join(` `)} `; _internal.isInteractive ? await prompt.single({ type: "confirm", message: chalk__default.default.yellow(`${message}Do you want to upgrade local versions?`), default: !0 }) && await upgradePackages.upgradePackages({ packageManager: (await upgradePackages.getPackageManagerChoice(workDir, { interactive: !1 })).chosen, packages: result.map((res) => [res.pkg, res.remote]) }, context) : output.print(chalk__default.default.yellow(message)); } } const config = getDevServerConfig({ flags, workDir, cliConfig, output }), projectId = cliConfig?.api?.projectId; let organizationId; if (loadInDashboard) { projectId || (output.error("Project Id is required to load in dashboard"), process.exit(1)); const client = apiClient({ requireUser: !0, requireProject: !0 }); try { organizationId = (await client.request({ uri: `/projects/${projectId}` })).organizationId; } catch (err) { debug(`Failed to get organization Id from project Id: ${err}`), output.error("Failed to get organization Id from project Id"), process.exit(1); } } try { const startTime = Date.now(), spinner = output.spinner("Starting dev server").start(), { server } = await startDevServer({ ...config }), { info: loggerInfo } = server.config.logger, { port } = server.config.server, httpHost = config.httpHost || "localhost"; if (spinner.succeed(), loadInDashboard) organizationId || (output.error("Organization Id not found for project"), process.exit(1)), output.print(`Dev server started on ${config.httpPort} port`), output.print("View your app in the Sanity dashboard here:"), output.print(chalk__default.default.blue(chalk__default.default.underline(await getCoreAppURL({ organizationId, httpHost: config.httpHost, httpPort: config.httpPort })))); else { const startupDuration = Date.now() - startTime, url = `http://${httpHost || "localhost"}:${port}${config.basePath}`; loggerInfo(`Sanity Studio using ${chalk__default.default.cyan(`vite@${require("vite/package.json").version}`)} ready in ${chalk__default.default.cyan(`${Math.ceil(startupDuration)}ms`)} and running at ${chalk__default.default.cyan(url)}`); } } catch (err) { debug(`Failed to start dev server: ${err}`), servers.gracefulServerDeath("dev", config.httpHost, config.httpPort, err); } } function getDevServerConfig({ flags, workDir, cliConfig, output }) { const configSpinner = output.spinner("Checking configuration files..."), baseConfig = servers.getSharedServerConfig({ flags: { host: flags.host, port: flags.port }, workDir, cliConfig }); configSpinner.succeed(); const env = process.env, reactStrictMode = env.SANITY_STUDIO_REACT_STRICT_MODE ? env.SANITY_STUDIO_REACT_STRICT_MODE === "true" : !!cliConfig?.reactStrictMode; return env.SANITY_STUDIO_BASEPATH && cliConfig?.project?.basePath && output.warn(`Overriding configured base path (${cliConfig.project.basePath}) with value from environment variable (${env.SANITY_STUDIO_BASEPATH})`), { ...baseConfig, staticPath: path__default.default.join(workDir, "static"), reactStrictMode, reactCompiler: cliConfig && "reactCompiler" in cliConfig ? cliConfig.reactCompiler : void 0 }; } var devAction = /* @__PURE__ */ Object.freeze({ __proto__: null, default: startSanityDevServer, getCoreAppURL, getCoreURL, getDevServerConfig }); exports.devAction = devAction; exports.getCoreAppURL = getCoreAppURL; exports.getDevServerConfig = getDevServerConfig; exports.startDevServer = startDevServer; //# sourceMappingURL=devAction2.js.map