UNPKG

everything-dev

Version:

A consolidated product package for building Module Federation apps with oRPC APIs.

1 lines • 17.6 kB
{"version":3,"file":"boot.cjs","names":["Data","Effect","captureShellEnv","ProjectEnv","loadEnvStep","emitProgress","getProcessEnv","resolveStartConfigSource","buildRegistryConfigUrl","resolvePublishedConfig","getHostDevelopmentPort","buildRuntimePluginsForConfig","DevStepError","buildRuntimeConfig","generateCodeArtifacts","isRegistryStart","processEnvRecord","isRailwayPublicProxyUrl","operatorEnvRecord","planInfra","buildServiceDescriptorMap","findConfigPath"],"sources":["../../../src/services/start/boot.ts"],"sourcesContent":["import { Data, Effect } from \"effect\";\nimport {\n buildRuntimeConfig,\n buildRuntimePluginsForConfig,\n findConfigPath,\n getHostDevelopmentPort,\n} from \"../../config\";\nimport type { StartOptions } from \"../../contract\";\nimport { isRailwayPublicProxyUrl } from \"../../db/driver\";\nimport {\n deleteProcessEnv,\n getProcessEnv,\n operatorEnvRecord,\n processEnvRecord,\n} from \"../../env/process-env\";\nimport { captureShellEnv, ProjectEnv } from \"../../env/project-env\";\nimport { planInfra } from \"../../infra/planner\";\nimport type { InfraPlan } from \"../../infra/types\";\nimport type { BosConfig } from \"../../types\";\nimport { generateCodeArtifacts } from \"../codegen/artifacts\";\nimport { type BootstrapDeps, DevStepError, loadEnvStep } from \"../dev/boot\";\nimport { emitProgress } from \"../dev/progress\";\nimport { type AppOrchestrator, buildServiceDescriptorMap } from \"../dev/service-descriptor\";\nimport type { DevSessionData, StartSummary } from \"../dev/session\";\nimport { buildRegistryConfigUrl } from \"../registry/fastkv\";\nimport { resolvePublishedConfig } from \"../registry/published\";\nimport { isRegistryStart, resolveStartConfigSource, type StartConfigSource } from \"./source\";\n\nexport class StartFetchFailed extends Data.TaggedError(\"StartFetchFailed\")<{ message: string }> {}\n\nexport class StartRemoteConfigMissing extends Data.TaggedError(\"StartRemoteConfigMissing\")<{\n message: string;\n}> {}\n\nexport class StartConfigMissing extends Data.TaggedError(\"StartConfigMissing\")<\n Record<string, never>\n> {}\n\n/**\n * A production start booting from an explicit config has declared that config\n * as its truth — the host's SnapshotWatch must not override it with the\n * registry pointer mid-run (a fixture-booted stack carrying a live identity\n * would otherwise adopt a foreign generation 30 seconds in, and a\n * config-path production boot is the operator's declared truth). The watch\n * stays on for identity-driven boots — adopting published config changes is\n * its feature. An operator-set interval always wins.\n */\nexport function setSnapshotWatchIntervalForBoot(\n source: StartConfigSource,\n env: \"production\" | \"staging\",\n processEnv: { BOS_SNAPSHOT_WATCH_INTERVAL_MS?: string } = process.env as {\n BOS_SNAPSHOT_WATCH_INTERVAL_MS?: string;\n },\n): void {\n if (processEnv.BOS_SNAPSHOT_WATCH_INTERVAL_MS !== undefined) return;\n if (env !== \"production\" || !source.configPath) return;\n processEnv.BOS_SNAPSHOT_WATCH_INTERVAL_MS = \"0\";\n}\n\nexport const startBootstrap = (deps: BootstrapDeps, input: StartOptions) =>\n Effect.gen(function* () {\n const shell = yield* captureShellEnv;\n const projectEnv = yield* ProjectEnv;\n\n const sessionRoot = deps.session?.root ?? process.cwd();\n\n yield* loadEnvStep(projectEnv, sessionRoot);\n\n yield* emitProgress({ phase: \"config\", status: \"running\" });\n\n const bosEnv = input.env ?? (getProcessEnv(\"BOS_ENV\") === \"staging\" ? \"staging\" : \"production\");\n const explicitConfig = resolveStartConfigSource(input, {\n BOS_ACCOUNT: getProcessEnv(\"BOS_ACCOUNT\"),\n BOS_GATEWAY: getProcessEnv(\"BOS_GATEWAY\"),\n });\n const registry = input.registry ?? getProcessEnv(\"BOS_REGISTRY\");\n setSnapshotWatchIntervalForBoot(explicitConfig, bosEnv);\n\n let config: BosConfig | null = null;\n let remoteConfig: BosConfig | null = null;\n\n if (explicitConfig.configPath) {\n config = deps.session?.config ?? null;\n } else if (explicitConfig.registry) {\n const { account, domain } = explicitConfig.registry;\n const expectedUrl = buildRegistryConfigUrl(account, domain, registry);\n remoteConfig = yield* Effect.tryPromise({\n try: () => resolvePublishedConfig(account, domain, registry),\n catch: (error) =>\n new StartFetchFailed({\n message: `Failed to fetch config for bos://${account}/${domain}: ${\n error instanceof Error ? error.message : \"Unknown error\"\n }\\nExpected URL: ${expectedUrl}`,\n }),\n });\n if (remoteConfig) {\n config = remoteConfig;\n } else {\n return yield* new StartRemoteConfigMissing({\n message: `No config found at bos://${account}/${domain}. Verify the account and gateway are correct and the config has been published.\\nExpected URL: ${expectedUrl}`,\n });\n }\n } else {\n config = deps.session?.config ?? null;\n }\n\n if (!config) {\n return yield* new StartConfigMissing({});\n }\n\n if (!explicitConfig.configPath) {\n if (explicitConfig.registry?.account) {\n config = { ...config, account: explicitConfig.registry.account };\n }\n if (explicitConfig.registry?.domain) {\n config = { ...config, domain: explicitConfig.registry.domain };\n }\n }\n const baseConfig: BosConfig = config;\n\n const port = input.port ?? getHostDevelopmentPort(baseConfig.app.host.development);\n const isStaging = bosEnv === \"staging\";\n const runtimePlugins = yield* Effect.tryPromise({\n try: () => buildRuntimePluginsForConfig(baseConfig, sessionRoot, \"production\"),\n catch: (cause) => new DevStepError({ phase: \"resolve runtime plugins\", cause }),\n });\n const runtimeConfig = yield* Effect.tryPromise({\n try: () =>\n buildRuntimeConfig(baseConfig, sessionRoot, \"production\", {\n uiSource: \"remote\",\n apiSource: \"remote\",\n authSource: \"remote\",\n hostSource: \"remote\",\n plugins: runtimePlugins,\n }),\n catch: (cause) => new DevStepError({ phase: \"build runtime config\", cause }),\n });\n\n if (isStaging && baseConfig.staging?.domain) {\n runtimeConfig.domain = baseConfig.staging.domain;\n }\n\n if (isStaging) {\n runtimeConfig.env = \"staging\";\n }\n\n yield* emitProgress({ phase: \"generate artifacts\", status: \"running\" });\n yield* Effect.tryPromise({\n try: () =>\n generateCodeArtifacts(sessionRoot, baseConfig, {\n env: \"production\",\n runtimeConfig,\n }),\n catch: (cause) => new DevStepError({ phase: \"generate artifacts\", cause }),\n });\n yield* emitProgress({ phase: \"generate artifacts\", status: \"done\" });\n\n const productionEnv: Record<string, string> = {};\n const warnings: string[] = [];\n\n const localhostOrigin = /^https?:\\/\\/(localhost|127\\.0\\.0\\.1)(:\\d+)?$/i;\n const corsOrigin = getProcessEnv(\"CORS_ORIGIN\");\n const isLocalhostProductionOrigin =\n corsOrigin !== undefined && localhostOrigin.test(corsOrigin);\n if (isLocalhostProductionOrigin && isRegistryStart(explicitConfig)) {\n warnings.push(\n `CORS_ORIGIN is a localhost origin (${corsOrigin}) in a registry production start — overriding with the configured domain`,\n );\n deleteProcessEnv(\"CORS_ORIGIN\");\n deleteProcessEnv(\"BASE_URL\");\n }\n\n if (!getProcessEnv(\"CORS_ORIGIN\") && baseConfig.domain) {\n const effectiveDomain = isStaging\n ? (baseConfig.staging?.domain ?? baseConfig.domain)\n : baseConfig.domain;\n const defaultOrigin = `https://${effectiveDomain}`;\n productionEnv.CORS_ORIGIN = defaultOrigin;\n productionEnv.BASE_URL = defaultOrigin;\n warnings.push(`CORS_ORIGIN defaulting to ${defaultOrigin}`);\n }\n\n const requiredSecrets = new Set<string>();\n const missingSecrets: string[] = [];\n\n if (runtimeConfig.host.secrets) {\n for (const s of runtimeConfig.host.secrets) requiredSecrets.add(s);\n }\n if (runtimeConfig.auth?.secrets) {\n for (const s of runtimeConfig.auth.secrets) requiredSecrets.add(s);\n }\n if (runtimeConfig.api?.secrets) {\n for (const s of runtimeConfig.api.secrets) requiredSecrets.add(s);\n }\n for (const plugin of Object.values(runtimeConfig.plugins ?? {})) {\n if (plugin.secrets) {\n for (const s of plugin.secrets) {\n if (s.endsWith(\"_DATABASE_URL\")) continue;\n requiredSecrets.add(s);\n }\n }\n }\n\n for (const secret of requiredSecrets) {\n const value = getProcessEnv(secret);\n if (!value || value.length === 0) {\n missingSecrets.push(secret);\n }\n }\n\n if (missingSecrets.length > 0) {\n warnings.push(`Missing ${missingSecrets.length} secret(s): ${missingSecrets.join(\", \")}`);\n }\n\n for (const [secret, value] of Object.entries(processEnvRecord())) {\n if (!value || !secret.endsWith(\"_DATABASE_URL\")) continue;\n if (isRailwayPublicProxyUrl(value)) {\n const host = new URL(value).hostname;\n warnings.push(\n `${secret} points at Railway's public proxy (${host}) — its TLS certificate is self-signed, ` +\n `so connections use unverified TLS. Prefer the private *.railway.internal URL when the ` +\n `database runs in the same Railway project.`,\n );\n }\n }\n\n if (!operatorEnvRecord().API_DATABASE_URL && !operatorEnvRecord().AUTH_DATABASE_URL) {\n warnings.push(\n \"No *_DATABASE_URL set — plugins without explicit URLs boot on ephemeral pglite and their \" +\n \"data will not survive restarts. Set API_DATABASE_URL/AUTH_DATABASE_URL in .env for production.\",\n );\n }\n\n const stagingEnvVars: Record<string, string> = isStaging\n ? { BOS_GATEWAY: baseConfig.staging?.domain ?? baseConfig.domain ?? \"\" }\n : {};\n\n const plan: InfraPlan = yield* planInfra({\n configDir: sessionRoot,\n bosConfig: runtimeConfig,\n operatorEnv: operatorEnvRecord(),\n cli: {\n port: input.port,\n ssr: false,\n proxy: false,\n hostSource: \"remote\",\n uiSource: \"remote\",\n apiSource: \"remote\",\n authSource: \"remote\",\n interactive: input.interactive,\n },\n });\n\n const services = buildServiceDescriptorMap(plan.runtimeConfig);\n\n const configSource = explicitConfig.configPath\n ? explicitConfig.configPath\n : remoteConfig\n ? `bos://${explicitConfig.registry?.account}/${explicitConfig.registry?.domain}`\n : (findConfigPath() ?? \"bos.config.json\");\n\n const configSourceHttp =\n remoteConfig && explicitConfig.registry\n ? buildRegistryConfigUrl(\n explicitConfig.registry.account,\n explicitConfig.registry.domain,\n registry,\n )\n : undefined;\n\n const summary: StartSummary = {\n configSource,\n configSourceHttp,\n account: baseConfig.account,\n domain: baseConfig.domain ?? undefined,\n modules: {\n host: plan.runtimeConfig.host.remoteUrl ?? plan.runtimeConfig.host.url ?? \"local\",\n ui: plan.runtimeConfig.ui.url ?? \"local\",\n api: plan.runtimeConfig.api.url ?? \"local\",\n auth: plan.runtimeConfig.auth?.url ?? undefined,\n },\n warnings,\n };\n\n const orchestrator: AppOrchestrator = {\n packages: [\"host\"],\n env: {\n NODE_ENV: \"production\",\n ...productionEnv,\n ...stagingEnvVars,\n ...plan.launch.env,\n },\n description: `${isStaging ? \"Staging\" : \"Production\"} Mode (${baseConfig.account})`,\n port: plan.resolvedPorts.host ?? port,\n interactive: input.interactive,\n // Log persistence stays off for start stacks: the SSR host emits ~80\n // log events per page render (i18n uncompiled-catalog warnings), and\n // the file sink writes every event twice through a serialized\n // appendFile chain regardless of level or dedup — on a loaded machine\n // that chain starves the event loop and degrades SSR/hydration\n // mid-suite. Boot failures are diagnosed from stdout (the renderer\n // prints error-level lines; the smoke captures 400 lines of it).\n };\n\n yield* emitProgress({ phase: \"config\", status: \"done\" });\n\n return {\n session: {\n orchestrator,\n services,\n runtimeConfig: plan.runtimeConfig,\n envGenerated: plan.envGenerated,\n shellEnv: shell,\n } satisfies DevSessionData,\n summary,\n url: plan.launch.hostUrl ?? `http://localhost:${plan.resolvedPorts.host ?? port}`,\n };\n });\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,IAAa,mBAAb,cAAsCA,YAAK,YAAY,kBAAkB,CAAC,CAAsB,CAAC;AAEjG,IAAa,2BAAb,cAA8CA,YAAK,YAAY,0BAA0B,CAAC,CAEvF,CAAC;AAEJ,IAAa,qBAAb,cAAwCA,YAAK,YAAY,oBAAoB,CAAC,CAE5E,CAAC;;;;;;;;;;AAWH,SAAgB,gCACd,QACA,KACA,aAA0D,QAAQ,KAG5D;CACN,IAAI,WAAW,mCAAmC,QAAW;CAC7D,IAAI,QAAQ,gBAAgB,CAAC,OAAO,YAAY;CAChD,WAAW,iCAAiC;AAC9C;AAEA,MAAa,kBAAkB,MAAqB,UAClDC,cAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAOC;CACrB,MAAM,aAAa,OAAOC;CAE1B,MAAM,cAAc,KAAK,SAAS,QAAQ,QAAQ,IAAI;CAEtD,OAAOC,yBAAY,YAAY,WAAW;CAE1C,OAAOC,8BAAa;EAAE,OAAO;EAAU,QAAQ;CAAU,CAAC;CAE1D,MAAM,SAAS,MAAM,QA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