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

143 lines (140 loc) 5.97 kB
import path from "node:path"; import { defineTrace, noopLogger } from "@sanity/telemetry"; import chalk from "chalk"; import logSymbols from "log-symbols"; import { rimraf } from "rimraf"; import semver from "semver"; import { buildStaticFiles } from "./previewServer.js"; import "./runtime.js"; import { warnAboutMissingAppId, buildVendorDependencies, formatModuleSizes, sortModulesBySize } from "./warnAboutMissingAppId.js"; import { shouldAutoUpdate, getAutoUpdatesImportMap, compareDependencyVersions } from "./shouldAutoUpdate.js"; import { getAppId } from "./getAppId.js"; import { readModuleVersion, getTimer } from "./timing.js"; const BuildTrace = defineTrace({ name: "App Build Completed", version: 0, description: "An App build completed" }); async function buildSanityApp(args, context, overrides) { const timer = getTimer(), { output, prompt, workDir, cliConfig, telemetry = noopLogger, cliConfigPath } = context, flags = { minify: !0, stats: !1, "source-maps": !1, ...args.extOptions }, unattendedMode = !!(flags.yes || flags.y), defaultOutputDir = path.resolve(path.join(workDir, "dist")), outputDir = path.resolve(args.argsWithoutOptions[0] || defaultOutputDir), autoUpdatesEnabled = shouldAutoUpdate({ flags, cliConfig }), appId = getAppId({ cliConfig, output }), installedSdkVersion = await readModuleVersion(context.workDir, "@sanity/sdk-react"), installedSanityVersion = await readModuleVersion(context.workDir, "sanity"); if (!installedSdkVersion) throw new Error("Failed to find installed @sanity/sdk-react version"); let autoUpdatesImports = {}; if (autoUpdatesEnabled) { const cleanSDKVersion = semver.parse(installedSdkVersion)?.version; if (!cleanSDKVersion) throw new Error(`Failed to parse installed SDK version: ${installedSdkVersion}`); const cleanSanityVersion = semver.parse(installedSanityVersion)?.version, autoUpdatedPackages = [{ name: "@sanity/sdk", version: cleanSDKVersion }, { name: "@sanity/sdk-react", version: cleanSDKVersion }, ...cleanSanityVersion ? [{ name: "sanity", version: cleanSanityVersion }] : []]; autoUpdatesImports = getAutoUpdatesImportMap(autoUpdatedPackages, { appId }), output.print(`${logSymbols.info} Building with auto-updates enabled`), args.groupOrCommand !== "deploy" && !appId && warnAboutMissingAppId({ appType: "app", cliConfigPath, output, projectId: cliConfig?.api?.projectId }); const result = await compareDependencyVersions(autoUpdatedPackages, workDir, {}); if (result?.length && !unattendedMode && !await prompt.single({ type: "confirm", message: chalk.yellow(`The following local package versions are different from the versions currently served at runtime. When using auto updates, we recommend that you test locally with the same versions before deploying. ${result.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join(` `)} Continue anyway?`), default: !1 })) return process.exit(0); } const envVarKeys = getSanityEnvVars(); envVarKeys.length > 0 && (output.print(` Including the following environment variables as part of the JavaScript bundle:`), envVarKeys.forEach((key) => output.print(`- ${key}`)), output.print("")); let shouldClean = !0; outputDir !== defaultOutputDir && !unattendedMode && (shouldClean = await prompt.single({ type: "confirm", message: `Do you want to delete the existing directory (${outputDir}) first?`, default: !0 })); let basePath = "/"; const envBasePath = process.env.SANITY_APP_BASEPATH, configBasePath = cliConfig?.project?.basePath; overrides?.basePath ? basePath = overrides.basePath : envBasePath ? basePath = envBasePath : configBasePath && (basePath = configBasePath), envBasePath && configBasePath && output.warn(`Overriding configured base path (${configBasePath}) with value from environment variable (${envBasePath})`); let spin; if (shouldClean) { timer.start("cleanOutputFolder"), spin = output.spinner("Clean output folder").start(), await rimraf(outputDir); const cleanDuration = timer.end("cleanOutputFolder"); spin.text = `Clean output folder (${cleanDuration.toFixed()}ms)`, spin.succeed(); } spin = output.spinner("Build Sanity application").start(); const trace = telemetry.trace(BuildTrace); trace.start(); let importMap; autoUpdatesEnabled && (importMap = { imports: { ...await buildVendorDependencies({ cwd: workDir, outputDir, basePath }), ...autoUpdatesImports } }); try { timer.start("bundleStudio"); const bundle = await buildStaticFiles({ cwd: workDir, outputDir, basePath, sourceMap: !!flags["source-maps"], minify: !!flags.minify, vite: cliConfig && "vite" in cliConfig ? cliConfig.vite : void 0, importMap, reactCompiler: cliConfig && "reactCompiler" in cliConfig ? cliConfig.reactCompiler : void 0, entry: cliConfig && "app" in cliConfig ? cliConfig.app?.entry : void 0, isApp: !0 }); trace.log({ outputSize: bundle.chunks.flatMap((chunk) => chunk.modules.flatMap((mod) => mod.renderedLength)).reduce((sum, n) => sum + n, 0) }); const buildDuration = timer.end("bundleStudio"); spin.text = `Build Sanity application (${buildDuration.toFixed()}ms)`, spin.succeed(), trace.complete(), flags.stats && (output.print(` Largest module files:`), output.print(formatModuleSizes(sortModulesBySize(bundle.chunks).slice(0, 15)))); } catch (err) { throw spin.fail(), trace.error(err), err; } return { didCompile: !0 }; } function getSanityEnvVars(env = process.env) { return Object.keys(env).filter((key) => key.toUpperCase().startsWith("SANITY_APP_")); } export { buildSanityApp as default }; //# sourceMappingURL=buildAction.js.map