everything-dev 2.0.0-rc.8 → 2.0.0-rc.9
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/dist/apps/upload/src/client.cjs +7 -1
- package/dist/apps/upload/src/client.cjs.map +1 -1
- package/dist/apps/upload/src/client.mjs +7 -1
- package/dist/apps/upload/src/client.mjs.map +1 -1
- package/dist/auth-login.cjs +24 -1
- package/dist/auth-login.cjs.map +1 -1
- package/dist/auth-login.mjs +24 -1
- package/dist/auth-login.mjs.map +1 -1
- package/dist/auth-session.cjs +4 -2
- package/dist/auth-session.cjs.map +1 -1
- package/dist/auth-session.mjs +4 -2
- package/dist/auth-session.mjs.map +1 -1
- package/dist/cdn-deploy.cjs +11 -7
- package/dist/cdn-deploy.cjs.map +1 -1
- package/dist/cdn-deploy.mjs +11 -7
- package/dist/cdn-deploy.mjs.map +1 -1
- package/dist/cli/import.cjs +1140 -0
- package/dist/cli/import.cjs.map +1 -0
- package/dist/cli/import.mjs +1126 -0
- package/dist/cli/import.mjs.map +1 -0
- package/dist/cli/init.cjs +11 -4
- package/dist/cli/init.cjs.map +1 -1
- package/dist/cli/init.d.cts +8 -2
- package/dist/cli/init.d.mts +8 -2
- package/dist/cli/init.mjs +11 -5
- package/dist/cli/init.mjs.map +1 -1
- package/dist/cli.cjs +55 -0
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.mjs +55 -0
- package/dist/cli.mjs.map +1 -1
- package/dist/commands/import.cjs +49 -0
- package/dist/commands/import.cjs.map +1 -0
- package/dist/commands/import.mjs +46 -0
- package/dist/commands/import.mjs.map +1 -0
- package/dist/commands/keys.cjs +24 -3
- package/dist/commands/keys.cjs.map +1 -1
- package/dist/commands/keys.mjs +24 -3
- package/dist/commands/keys.mjs.map +1 -1
- package/dist/config.d.cts +1 -0
- package/dist/config.d.mts +1 -0
- package/dist/contract.cjs +89 -0
- package/dist/contract.cjs.map +1 -1
- package/dist/contract.d.cts +190 -1
- package/dist/contract.d.mts +190 -1
- package/dist/contract.meta.cjs +16 -0
- package/dist/contract.meta.cjs.map +1 -1
- package/dist/contract.meta.d.cts +26 -0
- package/dist/contract.meta.d.mts +26 -0
- package/dist/contract.meta.mjs +16 -0
- package/dist/contract.meta.mjs.map +1 -1
- package/dist/contract.mjs +84 -1
- package/dist/contract.mjs.map +1 -1
- package/dist/custody-signer.cjs +70 -0
- package/dist/custody-signer.cjs.map +1 -0
- package/dist/custody-signer.mjs +68 -0
- package/dist/custody-signer.mjs.map +1 -0
- package/dist/descriptor/schema.cjs +8 -5
- package/dist/descriptor/schema.cjs.map +1 -1
- package/dist/descriptor/schema.d.cts +1 -0
- package/dist/descriptor/schema.d.mts +1 -0
- package/dist/descriptor/schema.mjs +8 -5
- package/dist/descriptor/schema.mjs.map +1 -1
- package/dist/descriptor/serialize.cjs +1 -1
- package/dist/descriptor/serialize.cjs.map +1 -1
- package/dist/descriptor/serialize.mjs +1 -1
- package/dist/descriptor/serialize.mjs.map +1 -1
- package/dist/index.cjs +6 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/outlayer-login.cjs +54 -0
- package/dist/outlayer-login.cjs.map +1 -0
- package/dist/outlayer-login.mjs +54 -0
- package/dist/outlayer-login.mjs.map +1 -0
- package/dist/plugin.cjs +2 -0
- package/dist/plugin.cjs.map +1 -1
- package/dist/plugin.d.cts +74 -0
- package/dist/plugin.d.mts +74 -0
- package/dist/plugin.mjs +2 -0
- package/dist/plugin.mjs.map +1 -1
- package/dist/publish.cjs +145 -22
- package/dist/publish.cjs.map +1 -1
- package/dist/publish.mjs +147 -24
- package/dist/publish.mjs.map +1 -1
- package/dist/source-archive.cjs +51 -0
- package/dist/source-archive.cjs.map +1 -0
- package/dist/source-archive.mjs +50 -0
- package/dist/source-archive.mjs.map +1 -0
- package/dist/storage-upload.cjs +6 -1
- package/dist/storage-upload.cjs.map +1 -1
- package/dist/storage-upload.mjs +6 -1
- package/dist/storage-upload.mjs.map +1 -1
- package/dist/types.cjs +5 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +2 -0
- package/dist/types.d.mts +2 -0
- package/dist/types.mjs +5 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/workspace-subtree.cjs +37 -0
- package/dist/utils/workspace-subtree.cjs.map +1 -0
- package/dist/utils/workspace-subtree.mjs +36 -0
- package/dist/utils/workspace-subtree.mjs.map +1 -0
- package/dist/version-manifest-deploy.cjs +4 -2
- package/dist/version-manifest-deploy.cjs.map +1 -1
- package/dist/version-manifest-deploy.mjs +4 -2
- package/dist/version-manifest-deploy.mjs.map +1 -1
- package/dist/version-manifest-resolve.cjs +2 -1
- package/dist/version-manifest-resolve.cjs.map +1 -1
- package/dist/version-manifest-resolve.d.cts +3 -0
- package/dist/version-manifest-resolve.d.mts +3 -0
- package/dist/version-manifest-resolve.mjs +2 -1
- package/dist/version-manifest-resolve.mjs.map +1 -1
- package/package.json +3 -2
- package/skills/cli-reference/SKILL.md +17 -1
- package/skills/init-upgrade/SKILL.md +76 -3
package/dist/publish.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publish.cjs","names":["composeWorkspaceVersionManifest","uploadBundle","colors","padRight","localSriMap","resolveSlotVersion","diffWorkspaceFiles","uploadWorkspaceDist","mergedFileIntegrity","process","fetchBosConfigFromFastKv","fetchResponse","join","existsSync","readFileSync","getNetworkIdForAccount","buildRegistryConfigUrlForNetwork","readSessionHandle","resolveSigningStrategy","describeSigningStrategy","resolveCdnDeployInputs","probeStorageOrigin","fetchPublishedConfigFromFastKv","getRegistryNamespaceForNetwork","selectWorkspaceTargets","generateCodeArtifacts","buildWorkspaceTargets","icons","openResolution","findConfigPath","isAppDescriptorPath","mergeAuthoredOverPublished","pinsFromPublishedConfig","pinsFromDeployState","resolveWorkspaceTarget","collectDistFiles","readBuildReport","formatDuration","platformUrlDeployEntries","hasFolderFormUi","resolveUiRuntimeName","pluginUiUrlDeployEntries","applyDeployResults","verifyRollbackSnapshot","pointerFingerprint","slotPins","ensureDelegateKey","submitRegistryWriteDelegated","submitRegistryWrite"],"sources":["../src/publish.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport process from \"node:process\";\nimport { hasFolderFormUi } from \"every-plugin/build/ui\";\nimport { readSessionHandle } from \"./auth-session\";\nimport { buildWorkspaceTargets, resolveWorkspaceTarget, selectWorkspaceTargets } from \"./build\";\nimport { type CdnDeployInputs, probeStorageOrigin, resolveCdnDeployInputs } from \"./cdn-deploy\";\nimport { formatDuration } from \"./cli/timing\";\nimport { generateCodeArtifacts } from \"./code-artifacts\";\nimport { findConfigPath, isAppDescriptorPath, resolveUiRuntimeName } from \"./config\";\nimport type { WorkspaceDeployResult } from \"./contract\";\nimport { ensureDelegateKey, submitRegistryWriteDelegated } from \"./delegate-signer\";\nimport {\n diffWorkspaceFiles,\n localSriMap,\n mergedFileIntegrity,\n type PreviousPin,\n pinsFromDeployState,\n pinsFromPublishedConfig,\n upsertDeployStatePins,\n} from \"./deploy-diff\";\nimport {\n buildRegistryConfigUrlForNetwork,\n fetchBosConfigFromFastKv,\n fetchPublishedConfigFromFastKv,\n getRegistryNamespaceForNetwork,\n type NetworkId,\n} from \"./fastkv\";\nimport { pointerFingerprint, slotPins } from \"./fingerprint\";\nimport { fetchResponse } from \"./http-client\";\nimport { applyDeployResults, type DeployResultEntry } from \"./integrity\";\nimport { mergeAuthoredOverPublished } from \"./merge\";\nimport {\n describeSigningStrategy,\n resolveSigningStrategy,\n type SigningStrategy,\n submitRegistryWrite,\n} from \"./near-signer\";\nimport { getNetworkIdForAccount } from \"./network\";\nimport { platformUrlDeployEntries, pluginUiUrlDeployEntries } from \"./platform-deploy\";\nimport { openResolution } from \"./resolution/session\";\nimport { verifyRollbackSnapshot } from \"./rollback\";\nimport {\n collectDistFiles,\n type DistFile,\n uploadBundle,\n uploadWorkspaceDist,\n} from \"./storage-upload\";\nimport type { BosConfig, BosConfigInput, PublishConfig, RuntimeConfig } from \"./types\";\nimport { padRight } from \"./utils/string\";\nimport { colors, icons } from \"./utils/theme\";\nimport { composeWorkspaceVersionManifest, readBuildReport } from \"./version-manifest-deploy\";\nimport { resolveSlotVersion } from \"./version-manifest-resolve\";\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Compose + upload the workspace's version manifest (atomic-deploys 03): the\n * manifest is built from the dist build report + the **server-computed** SRI\n * map of the just-finished upload, uploaded additively at\n * `versions/<version>.json`, and returned as the slot's pointer. Returns\n * undefined when the dist predates hashed entry names (no report / no entry\n * SRI) — the caller aborts the train: uploaded workspaces must pin.\n */\n/**\n * The manifest's own storage backend — when every dist file was diff-skipped\n * it is the only upload of the leg, so it is the only signal for the\n * memory-backend abort below.\n */\nexport interface VersionManifestPin {\n file: string;\n integrity: string;\n storage?: \"s3\" | \"memory\";\n}\n\nasync function pinWorkspaceVersionManifest(input: {\n origin: string;\n apiKey?: string;\n account: string;\n gateway: string;\n workspace: string;\n report: ReturnType<typeof readBuildReport>;\n ssrReport: ReturnType<typeof readBuildReport>;\n integrityMap: Record<string, string>;\n /** full per-file SRI map of the dist — recorded for the next deploy's diff */\n files?: Record<string, string>;\n}): Promise<VersionManifestPin | undefined> {\n if (!input.report) return undefined;\n const versionManifest = composeWorkspaceVersionManifest({\n report: input.report,\n ssrReport: input.ssrReport,\n integrityMap: input.integrityMap,\n ...(input.files ? { files: input.files } : {}),\n });\n if (!versionManifest) return undefined;\n\n const manifestFile = `versions/${versionManifest.version}.json`;\n const manifestUpload = await uploadBundle({\n origin: input.origin,\n apiKey: input.apiKey,\n account: input.account,\n gateway: input.gateway,\n workspace: input.workspace,\n files: [\n {\n path: manifestFile,\n bytes: new TextEncoder().encode(`${JSON.stringify(versionManifest, null, 2)}\\n`),\n },\n ],\n });\n const manifestIntegrity = manifestUpload.integrity[manifestFile];\n if (!manifestIntegrity) return undefined;\n console.log(\n ` ${colors.dim(`${padRight(\"\", 28)} version manifest ${manifestFile} (SRI pinned)`)}`,\n );\n return { file: manifestFile, integrity: manifestIntegrity, storage: manifestUpload.storage };\n}\n\ninterface DiffUploadOutcome {\n result: {\n stored: number;\n totalBytes: number;\n integrity: Record<string, string>;\n storage?: \"s3\" | \"memory\";\n };\n /** per-file SRI map covering the whole dist (uploaded → server SRI, skipped → previous manifest SRI) */\n fileIntegrity: Record<string, string>;\n uploaded: number;\n skipped: number;\n total: number;\n}\n\n/**\n * One workspace's upload leg with skip-unchanged diffing: resolve the previous\n * manifest's `files` map, hash the local dist, upload only new/changed files,\n * and return the merged per-file SRI map for the version manifest. Any failure\n * to resolve the previous map degrades to a full upload.\n */\nasync function diffUploadWorkspace(input: {\n origin: string;\n apiKey?: string;\n account: string;\n gateway: string;\n workspace: string;\n files: DistFile[];\n base: string;\n previousPin: PreviousPin | undefined;\n}): Promise<DiffUploadOutcome> {\n const localSri = localSriMap(input.files);\n let uploadFiles = input.files;\n let prevFiles: Record<string, string> | undefined;\n if (input.previousPin) {\n try {\n const resolved = await resolveSlotVersion({ base: input.base, pin: input.previousPin });\n if (resolved.files) {\n const diff = diffWorkspaceFiles(input.files, localSri, resolved.files);\n prevFiles = resolved.files;\n uploadFiles = diff.upload;\n if (diff.skipped > 0) {\n console.log(\n ` ${colors.dim(`${padRight(input.workspace, 28)} ${diff.skipped} unchanged file(s) — skipping (manifest diff)`)}`,\n );\n }\n }\n } catch {\n console.log(\n ` ${colors.dim(`${padRight(input.workspace, 28)} previous manifest unusable — uploading everything`)}`,\n );\n }\n }\n\n console.log(\n ` ${padRight(input.workspace, 28)} uploading ${uploadFiles.length} of ${input.files.length} files (${formatBundleMb(uploadFiles)}) → ${input.base}`,\n );\n const result =\n uploadFiles.length > 0\n ? await uploadWorkspaceDist({\n origin: input.origin,\n apiKey: input.apiKey,\n account: input.account,\n gateway: input.gateway,\n workspace: input.workspace,\n files: uploadFiles,\n })\n : { stored: 0, totalBytes: 0, integrity: {}, storage: undefined };\n return {\n result,\n fileIntegrity: mergedFileIntegrity(input.files, result.integrity, prevFiles),\n uploaded: result.stored,\n skipped: input.files.length - uploadFiles.length,\n total: input.files.length,\n };\n}\n\nfunction formatBundleMb(files: Array<{ bytes: Uint8Array }>): string {\n const total = files.reduce((sum, file) => sum + file.bytes.byteLength, 0);\n return `${(total / 1024 / 1024).toFixed(1)} MB`;\n}\n\nexport async function waitForPublishedConfig(opts: {\n account: string;\n gateway: string;\n publishConfig: BosConfigInput;\n registry?: string;\n timeoutMs?: number;\n intervalMs?: number;\n}): Promise<void> {\n const envTimeoutMs = Number(process.env.BOS_PUBLISH_CONFIRMATION_TIMEOUT_MS);\n const envIntervalMs = Number(process.env.BOS_PUBLISH_CONFIRMATION_INTERVAL_MS);\n const timeoutMs =\n opts.timeoutMs ?? (Number.isFinite(envTimeoutMs) ? envTimeoutMs : undefined) ?? 120_000;\n const intervalMs =\n opts.intervalMs ?? (Number.isFinite(envIntervalMs) ? envIntervalMs : undefined) ?? 3_000;\n const startedAt = Date.now();\n let lastError: unknown;\n\n while (Date.now() - startedAt < timeoutMs) {\n try {\n const verifiedConfig = await fetchBosConfigFromFastKv<BosConfigInput>(\n `bos://${opts.account}/${opts.gateway}`,\n opts.registry,\n );\n\n if (JSON.stringify(verifiedConfig) === JSON.stringify(opts.publishConfig)) {\n return;\n }\n } catch (error) {\n lastError = error;\n }\n\n await sleep(intervalMs);\n }\n\n const reason = lastError instanceof Error ? ` Last error: ${lastError.message}` : \"\";\n throw new Error(\n `Timed out waiting for publish confirmation at bos://${opts.account}/${opts.gateway}.${reason}`,\n );\n}\n\nexport async function isConfigAlreadyPublished(opts: {\n account: string;\n gateway: string;\n publishConfig: BosConfigInput;\n registry?: string;\n}): Promise<boolean> {\n try {\n const current = await fetchBosConfigFromFastKv<BosConfigInput>(\n `bos://${opts.account}/${opts.gateway}`,\n opts.registry,\n );\n return JSON.stringify(current) === JSON.stringify(opts.publishConfig);\n } catch {\n return false;\n }\n}\n\ninterface PublishToFastKvInput {\n bosConfig: BosConfig;\n runtimeConfig: RuntimeConfig | null;\n configDir: string;\n env: \"production\" | \"staging\";\n build: boolean;\n dryRun: boolean;\n verbose: boolean;\n packages: string;\n network?: \"mainnet\" | \"testnet\";\n privateKey?: string;\n wallet?: boolean;\n registry?: string;\n /** Skip the diff upload and re-upload every dist file (escape hatch). */\n fullUpload?: boolean;\n /** Publish `bosConfig` verbatim — no authored/published merge, no ts-form\n * config-only guard. Rollbacks use this: the payload is the previous\n * snapshot, already assembled. */\n exactPayload?: boolean;\n}\n\ninterface PublishToFastKvResult {\n status: \"published\" | \"error\" | \"dry-run\";\n registryUrl: string;\n txHash?: string;\n built?: string[];\n skipped?: string[];\n error?: string;\n publishConfig?: BosConfigInput;\n deployResults?: WorkspaceDeployResult[];\n fingerprint?: string;\n slotPins?: Record<string, string>;\n}\n\nexport type PublishedConfigState = \"fetched\" | \"missing\" | \"unreachable\";\n\nexport interface PublishPreflightPlan {\n isStaging: boolean;\n account: string;\n gateway: string;\n network: NetworkId;\n registryUrl: string;\n registryNamespace: string;\n targets: string[];\n useWallet: boolean;\n strategy?: SigningStrategy;\n cdnOrigin: string | undefined;\n storageOrigin: string;\n storageApiKey?: string;\n /** The config currently published to FastKV (null when missing or unreachable). */\n publishedConfig: Record<string, unknown> | null;\n /** Whether the preflight FastKV read succeeded, found nothing, or failed. */\n publishedConfigState: PublishedConfigState;\n}\n\nexport type PublishPreflight =\n | { kind: \"dry-run\"; registryUrl: string }\n | { kind: \"error\"; registryUrl: string; error: string }\n | { kind: \"ready\"; plan: PublishPreflightPlan };\n\nconst FRAMEWORK_PACKAGE_NAMES = [\"better-near-auth\", \"every-plugin\", \"everything-dev\"] as const;\n\n/**\n * Whether npm serves `name@version` (true), definitively does not (404 —\n * false), or whether publishability could not be determined (network error,\n * unexpected status — null; callers must not block on that).\n */\nexport async function npmVersionPublished(name: string, version: string): Promise<boolean | null> {\n try {\n const res = await fetchResponse(`https://registry.npmjs.org/${name}/${version}`, {\n headers: { Accept: \"application/json\" },\n });\n if (res.status === 200) return true;\n if (res.status === 404) return false;\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * The npm-publish gate: a workspace that vendors the framework packages'\n * sources must not ship bundles ahead of npm — the update check, child\n * scaffolds (`bos init`), and template syncs all read those versions from\n * the registry. Reads only apply when the sources are workspace-local (the\n * parent repo); child projects install the framework from npm and are\n * inherently in sync.\n */\nexport async function findUnpublishedFrameworkPackages(\n configDir: string,\n): Promise<Array<{ name: string; version: string }>> {\n const unpublished: Array<{ name: string; version: string }> = [];\n for (const name of FRAMEWORK_PACKAGE_NAMES) {\n const manifestPath = join(configDir, \"packages\", name, \"package.json\");\n if (!existsSync(manifestPath)) continue;\n const version = (JSON.parse(readFileSync(manifestPath, \"utf-8\")) as { version?: string })\n .version;\n if (!version) continue;\n const published = await npmVersionPublished(name, version);\n if (published === false) {\n unpublished.push({ name, version });\n } else if (published === null) {\n console.log(\n colors.yellow(\n ` ! Could not verify ${name}@${version} on npm (registry unreachable) — continuing`,\n ),\n );\n }\n }\n return unpublished;\n}\n\n// Pure preflight (resolve, don't mutate) — every failure returns before the\n// build train runs (issue #287). Dry-run exits after the auth guards, before\n// any signing (keychain/TTY side effects).\nexport async function preflightPublish(input: PublishToFastKvInput): Promise<PublishPreflight> {\n const { configDir } = input;\n const bosConfig = input.bosConfig;\n\n const isStaging = input.env === \"staging\";\n const account = isStaging ? (bosConfig.staging?.account ?? bosConfig.account) : bosConfig.account;\n const gateway = isStaging ? (bosConfig.staging?.domain ?? bosConfig.domain) : bosConfig.domain;\n if (!gateway) {\n return {\n kind: \"error\",\n registryUrl: \"\",\n error: \"authored config must define domain to publish\",\n };\n }\n\n const network: NetworkId = input.network ?? getNetworkIdForAccount(account);\n const registryUrl = buildRegistryConfigUrlForNetwork(network, account, gateway, input.registry);\n const fail = (error: string): PublishPreflight => ({ kind: \"error\", registryUrl, error });\n\n const publishAuth: PublishConfig[\"auth\"] = bosConfig.publish?.auth;\n const governsWalletPublish = (publishAuth === \"session\" || input.wallet) && !input.privateKey;\n if (governsWalletPublish) {\n const session = readSessionHandle(configDir);\n if (!session?.credential) {\n return fail(\n (input.wallet\n ? \"--wallet requires\"\n : 'the authored config sets publish.auth = \"session\", but') +\n \" no CLI session is stored in .bos/ for this project. Run bos login to create one.\",\n );\n }\n if (session.credential.accountId && session.credential.accountId !== account) {\n return fail(\n `The CLI session was created for ${session.credential.accountId}, but the configured ` +\n `account is ${account}. Gasless wallet publish relays the FastKV write under the session's ` +\n \"NEAR account. Run bos login again under the matching account.\",\n );\n }\n }\n if (publishAuth && !input.privateKey) {\n if (publishAuth === \"custody\") {\n return fail(\n 'the authored config sets publish.auth = \"custody\", but custody publish is not implemented yet (see NEARBuilders/everything-dev#291).',\n );\n }\n }\n\n if (input.dryRun) {\n return { kind: \"dry-run\", registryUrl };\n }\n\n const useWallet = input.wallet === true;\n let strategy: SigningStrategy | undefined;\n if (useWallet) {\n console.log(\n ` Signing via ${colors.cyan(\"gasless NEP-366 delegate action (relayed by the platform relayer)\")}`,\n );\n } else {\n try {\n strategy = await resolveSigningStrategy({ privateKey: input.privateKey, account, network });\n console.log(` Signing via ${colors.cyan(describeSigningStrategy(strategy))}`);\n } catch (error) {\n return fail(error instanceof Error ? error.message : \"Unknown error\");\n }\n }\n\n // CDN deploy credentials (ADR 0020) — resolved before the build train so a\n // missing bundle origin or BOS_STORAGE_API_KEY fails fast instead of after\n // the full build. Config-only publishes ship the committed config verbatim;\n // nothing is uploaded, so no deploy origins are required.\n const session = readSessionHandle(configDir);\n let cdnDeploy: CdnDeployInputs = {\n cdnOrigin: undefined,\n storageOrigin: \"\",\n apiKey: undefined,\n };\n if (input.build) {\n const unpublished = await findUnpublishedFrameworkPackages(configDir);\n if (unpublished.length > 0) {\n const listing = unpublished.map((pkg) => `${pkg.name}@${pkg.version}`).join(\", \");\n return fail(\n `Framework package(s) ${listing} are not published to npm yet — deploys must not ship ` +\n \"bundles ahead of the registry (child scaffolds and update checks read these versions). \" +\n \"Re-run the Release workflow (or `pnpm run release`) first.\",\n );\n }\n\n cdnDeploy = resolveCdnDeployInputs({\n env: process.env as Record<string, string | undefined>,\n bosConfig,\n session: session?.credential ?? null,\n account,\n gateway,\n uploadsPlanned: input.build,\n });\n if (cdnDeploy.error) {\n return fail(cdnDeploy.error);\n }\n if (cdnDeploy.warning) {\n console.log(colors.yellow(` ! ${cdnDeploy.warning}`));\n }\n const cdnOrigin = cdnDeploy.cdnOrigin;\n if (!cdnOrigin) {\n return fail(\"CDN deploy resolved no bundle origin\");\n }\n const probeError = await probeStorageOrigin(cdnDeploy.storageOrigin);\n if (probeError) {\n return fail(\n `The bundle upload origin ${cdnDeploy.storageOrigin} is not running the platform API — ` +\n `${probeError}. Check BOS_STORAGE_ORIGIN / the bos login session, then re-run.`,\n );\n }\n }\n\n // Registry reachability + published-state capture: one FastKV read. A\n // missing config is fine for a first publish — an early signal, not a hard\n // gate. The captured config is the merge base for a config-only publish on\n // a TS-form project (authored hand-edits win; live pipeline state carries).\n let publishedConfig: Record<string, unknown> | null = null;\n let publishedConfigState: PublishedConfigState = \"missing\";\n try {\n publishedConfig = await fetchPublishedConfigFromFastKv<Record<string, unknown>>(registryUrl);\n publishedConfigState = \"fetched\";\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.startsWith(\"No config found\")) {\n console.log(colors.dim(\" Note: no published config found yet (first publish) — continuing\"));\n } else {\n publishedConfigState = \"unreachable\";\n console.log(colors.dim(\" Note: registry read failed — continuing\"));\n }\n }\n\n return {\n kind: \"ready\",\n plan: {\n isStaging,\n account,\n gateway,\n network,\n registryUrl,\n registryNamespace: getRegistryNamespaceForNetwork(network, input.registry),\n targets: selectWorkspaceTargets(input.packages, bosConfig),\n useWallet,\n strategy,\n cdnOrigin: cdnDeploy.cdnOrigin,\n storageOrigin: cdnDeploy.storageOrigin,\n storageApiKey: cdnDeploy.apiKey,\n publishedConfig,\n publishedConfigState,\n },\n };\n}\n\n/**\n * The deploy-train publish core (ADR 0020, as amended): preflight\n * (storage/CDN creds + signing) fails fast before the build, then build →\n * upload → version-manifest pin → config write-back → FastKV publish +\n * read-back. Scoped to one plugin via `packages`, a single-plugin redeploy\n * ships real bytes to the storage origin — same as the full train, nothing\n * image-native left.\n */\nexport async function publishToFastKv(input: PublishToFastKvInput): Promise<PublishToFastKvResult> {\n const preflight = await preflightPublish(input);\n if (preflight.kind === \"error\") {\n return { status: \"error\", registryUrl: preflight.registryUrl, error: preflight.error };\n }\n if (preflight.kind === \"dry-run\") {\n return { status: \"dry-run\", registryUrl: preflight.registryUrl };\n }\n const plan = preflight.plan;\n const {\n isStaging,\n account,\n gateway,\n network,\n registryUrl,\n registryNamespace,\n targets,\n useWallet,\n strategy,\n } = plan;\n const storageOrigin = plan.storageOrigin;\n const storageApiKey = plan.storageApiKey;\n\n const { configDir } = input;\n let bosConfig = input.bosConfig;\n const runtimeConfig = input.runtimeConfig;\n let built: string[] | undefined;\n let skipped: string[] | undefined;\n let deployResults: WorkspaceDeployResult[] | undefined;\n let refreshedRawConfig: BosConfigInput | null = null;\n\n if (input.build) {\n await generateCodeArtifacts(configDir, bosConfig, {\n env: \"production\",\n runtimeConfig: runtimeConfig ?? undefined,\n });\n\n const result = await buildWorkspaceTargets({\n configDir,\n bosConfig,\n runtimeConfig,\n targets,\n deploy: true,\n verbose: input.verbose,\n });\n built = result.built;\n skipped = result.skipped;\n deployResults = result.deployResults;\n\n if (deployResults) {\n const failures = deployResults.filter((r) => !r.success);\n if (failures.length > 0) {\n const total = deployResults.length;\n console.log();\n console.log(\n colors.error(\n ` ${icons.err} Deploy failed — ${failures.length} of ${total} workspace${total > 1 ? \"s\" : \"\"} failed`,\n ),\n );\n console.log();\n for (const f of failures) {\n const errorLine = (f.error ?? \"Failed\").split(\"\\n\")[0];\n console.log(` ${colors.error(icons.err)} ${padRight(f.key, 28)} ${errorLine}`);\n }\n console.log();\n if (!input.verbose) {\n console.log(colors.dim(\" Run with --verbose for full build output.\"));\n console.log();\n }\n return {\n status: \"error\" as const,\n registryUrl,\n built,\n skipped,\n deployResults,\n error: `${failures.length} of ${total} workspaces failed to deploy`,\n };\n }\n }\n\n const refreshed = await openResolution({ cwd: configDir });\n if (!refreshed?.config) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: \"Failed to reload the config after build\",\n };\n }\n\n bosConfig = refreshed.config;\n refreshedRawConfig = refreshed.rawConfig;\n }\n\n const authoredPath = findConfigPath(configDir);\n const tsForm = authoredPath !== null && isAppDescriptorPath(authoredPath);\n let rawConfig: BosConfigInput;\n if (refreshedRawConfig) {\n rawConfig = refreshedRawConfig;\n } else {\n const opened = await openResolution({ cwd: configDir });\n if (!opened?.rawConfig) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: \"Failed to load the authored config for publish\",\n };\n }\n rawConfig = opened.rawConfig;\n }\n if (\n tsForm &&\n !input.build &&\n input.exactPayload !== true &&\n plan.publishedConfigState === \"unreachable\"\n ) {\n // A config-only TS-form publish derives its pipeline state from the live\n // published config — publishing without it would wipe bundle URLs.\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error:\n \"Cannot read the currently published config from the registry — a config-only publish would overwrite live bundle URLs. Retry when the registry is reachable, or run a full deploy.\",\n };\n }\n let publishPayload: BosConfigInput =\n input.exactPayload === true\n ? input.bosConfig\n : tsForm && !input.build\n ? // Config-only publish on a TS-form project: the authored config owns\n // composition (hand-edits win) while live pipeline state (bundle\n // URLs, integrity) carries over from the published config.\n mergeAuthoredOverPublished((plan.publishedConfig ?? {}) as BosConfigInput, rawConfig)\n : rawConfig;\n\n const urlOrigin = plan.cdnOrigin ?? `https://${gateway}`;\n const deployTargets = (built ?? []).filter((key) => targets.includes(key));\n const platformEntries: DeployResultEntry[] = [];\n const fullUpload = input.fullUpload === true || process.env.BOS_FULL_UPLOAD === \"1\";\n // Previous per-workspace pins for the diff upload: the local pointer wins\n // (written after every confirmed publish), the published config is the\n // fallback. Neither → full upload.\n const prevPins: Record<string, PreviousPin> = fullUpload\n ? {}\n : {\n ...pinsFromPublishedConfig(\n (plan.publishedConfig ?? {}) as BosConfigInput,\n account,\n gateway,\n ),\n ...pinsFromDeployState(configDir, account, gateway),\n };\n\n console.log();\n console.log(` CDN deploy — uploading workspace dists to ${storageOrigin}...`);\n for (const key of deployTargets) {\n const ws = resolveWorkspaceTarget(key, bosConfig, runtimeConfig, configDir);\n if (!ws) continue;\n\n const distFiles = await collectDistFiles(join(ws.path, \"dist\"));\n const workspaceBase = `${urlOrigin}/bundles/${account}/${gateway}/${key}/`;\n const startedAt = Date.now();\n // an upload failure aborts the train as a structured error — the\n // previously published version stays fully live (ticket 05)\n let outcome: DiffUploadOutcome;\n try {\n outcome = await diffUploadWorkspace({\n origin: storageOrigin,\n apiKey: storageApiKey,\n account,\n gateway,\n workspace: key,\n files: distFiles,\n base: workspaceBase,\n previousPin: prevPins[key],\n });\n } catch (error) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: error instanceof Error ? error.message : `[publish] bundle upload for ${key} failed`,\n };\n }\n const report = readBuildReport(join(ws.path, \"dist\"));\n const ssrReport = readBuildReport(join(ws.path, \"dist\", \"ssr\"));\n // the entry SRI keyed by the build report's hashed name\n const integrity = report ? outcome.fileIntegrity[report.entry] : undefined;\n const ssrIntegrity = ssrReport?.entry\n ? outcome.fileIntegrity[`ssr/${ssrReport.entry}`]\n : undefined;\n\n const manifestPointer = await pinWorkspaceVersionManifest({\n origin: storageOrigin,\n apiKey: storageApiKey,\n account,\n gateway,\n workspace: key,\n report,\n ssrReport,\n integrityMap: outcome.fileIntegrity,\n files: outcome.fileIntegrity,\n });\n if (!manifestPointer) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: `bundle upload for ${key}: version manifest missing — the dist predates hashed entry names (rebuild required; atomic-deploys hard break)`,\n };\n }\n\n if (outcome.result.storage === \"memory\" || manifestPointer.storage === \"memory\") {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error:\n \"The receiving instance is serving bundle storage from memory (BOS_STORAGE_* R2 credentials are not configured there) — uploaded bytes would be lost on restart. Aborting before publish.\",\n };\n }\n\n console.log(\n ` ${colors.green(icons.ok)} ${padRight(key, 28)} → ${urlOrigin}/bundles/${account}/${gateway}/${key}/ (${outcome.uploaded} uploaded, ${outcome.skipped} skipped, ${formatDuration(Date.now() - startedAt)})`,\n );\n\n platformEntries.push(\n ...platformUrlDeployEntries({\n origin: urlOrigin,\n account,\n gateway,\n key,\n kind: ws.kind,\n integrity,\n ssrIntegrity,\n pin: manifestPointer,\n }),\n );\n\n // Folder-form plugin ui: the workspace build also produces <plugin>/ui/dist\n // (web remoteEntry + ssr container) — upload it as its own bundle key and\n // pin <slot>.<key>.ui.* so the host can compose the ui surface in production.\n if (hasFolderFormUi(ws.path)) {\n const uiDistDir = join(ws.path, \"ui\", \"dist\");\n const uiSlot = ws.kind === \"app\" ? \"app\" : \"plugins\";\n const rawSlot = (uiSlot === \"app\" ? rawConfig.app : rawConfig.plugins) as\n | Record<string, Record<string, unknown> | undefined>\n | undefined;\n const rawUi = rawSlot?.[key]?.ui as Record<string, unknown> | undefined;\n const uiName = resolveUiRuntimeName(rawUi, join(ws.path, \"ui\"), key);\n let uiIntegrity: string | undefined;\n let uiSsrIntegrity: string | undefined;\n let uiManifestPointer: VersionManifestPin | undefined;\n if (existsSync(uiDistDir)) {\n const uiDistFiles = await collectDistFiles(uiDistDir);\n const uiStartedAt = Date.now();\n const uiOutcome = await diffUploadWorkspace({\n origin: storageOrigin,\n apiKey: storageApiKey,\n account,\n gateway,\n workspace: `${key}-ui`,\n files: uiDistFiles,\n base: `${urlOrigin}/bundles/${account}/${gateway}/${key}-ui/`,\n previousPin: prevPins[`${key}-ui`],\n });\n const uiReport = readBuildReport(uiDistDir);\n const uiSsrReport = readBuildReport(join(uiDistDir, \"ssr\"));\n uiIntegrity = uiReport ? uiOutcome.fileIntegrity[uiReport.entry] : undefined;\n uiSsrIntegrity = uiSsrReport?.entry\n ? uiOutcome.fileIntegrity[`ssr/${uiSsrReport.entry}`]\n : undefined;\n\n uiManifestPointer = await pinWorkspaceVersionManifest({\n origin: storageOrigin,\n apiKey: storageApiKey,\n account,\n gateway,\n workspace: `${key}-ui`,\n report: uiReport,\n ssrReport: uiSsrReport,\n integrityMap: uiOutcome.fileIntegrity,\n files: uiOutcome.fileIntegrity,\n });\n if (!uiManifestPointer) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: `bundle upload for ${key}-ui: version manifest missing — the dist predates hashed entry names (rebuild required; atomic-deploys hard break)`,\n };\n }\n\n if (uiOutcome.result.storage === \"memory\" || uiManifestPointer.storage === \"memory\") {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error:\n \"The receiving instance is serving bundle storage from memory (BOS_STORAGE_* R2 credentials are not configured there) — uploaded bytes would be lost on restart. Aborting before publish.\",\n };\n }\n\n console.log(\n ` ${colors.green(icons.ok)} ${padRight(`${key}-ui`, 28)} → ${urlOrigin}/bundles/${account}/${gateway}/${key}-ui/ (${uiOutcome.uploaded} uploaded, ${uiOutcome.skipped} skipped, ${formatDuration(Date.now() - uiStartedAt)})`,\n );\n } else {\n console.log(\n ` ${colors.green(icons.ok)} ${padRight(`${key}-ui`, 28)} → ${urlOrigin}/bundles/${account}/${gateway}/${key}-ui/`,\n );\n }\n\n platformEntries.push(\n ...pluginUiUrlDeployEntries({\n origin: urlOrigin,\n account,\n gateway,\n key,\n kind: ws.kind,\n integrity: uiIntegrity,\n ssrIntegrity: uiSsrIntegrity,\n name: uiName,\n pin: uiManifestPointer,\n }),\n );\n }\n }\n\n if (platformEntries.length > 0) {\n const merged = applyDeployResults(rawConfig as Record<string, unknown>, platformEntries);\n if (!tsForm) {\n // Legacy JSON-form children keep their local write-back; TS-form keeps\n // pipeline state in FastKV only — a write-back would shadow the\n // authored bos.app.ts descriptor.\n try {\n writeFileSync(join(configDir, \"bos.config.json\"), `${JSON.stringify(merged, null, 2)}\\n`);\n } catch (error) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: `Failed to write bundle URLs to bos.config.json: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n publishPayload = merged as BosConfigInput;\n }\n if (isStaging) {\n publishPayload = { ...publishPayload, domain: gateway };\n }\n\n const pinVerification = await verifyRollbackSnapshot(publishPayload);\n if (pinVerification.verifiable && !pinVerification.ok) {\n const failures = pinVerification.slots\n .filter((check) => !check.ok)\n .map((check) => ` ${check.slot}: ${check.reason}`)\n .join(\"\\n\");\n console.error(\n ` ${colors.error(icons.err)} Publish blocked — a pinned slot's bytes do not serve at its production URL:\\n${failures}`,\n );\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: `Publish blocked — pinned slot bytes missing or SRI mismatched:\\n${failures}`,\n };\n }\n\n const registryKey = `apps/${account}/${gateway}/bos.config.json`;\n const publishedAt = new Date().toISOString();\n // version identity printed + returned for every deploy (atomic-deploys 12)\n const fingerprint = pointerFingerprint(publishPayload as never);\n const publishSlotPins = slotPins(publishPayload as never);\n const registryEntries: Record<string, string> = {\n [registryKey]: JSON.stringify(publishPayload),\n };\n const manifestKey = `apps/${account}/${gateway}/manifests/${publishedAt.replace(/[:.]/g, \"-\")}.json`;\n registryEntries[manifestKey] = JSON.stringify({\n account,\n gateway,\n network,\n publishedAt,\n registryUrl,\n });\n\n console.log();\n console.log(\" Publishing to:\");\n console.log(` ${colors.cyan(registryUrl)}`);\n console.log(` ${colors.dim(\"Fingerprint:\")} ${fingerprint}`);\n for (const [slot, pin] of Object.entries(publishSlotPins)) {\n console.log(` ${colors.dim(`${slot}:`)}`);\n console.log(` ${pin}`);\n }\n console.log(\n ` ${colors.dim(`+ per-deploy manifest ${manifestKey.split(\"/\").pop()} (audit trail)`)}`,\n );\n\n // Record the live pins for the next deploy's diff upload — only after the\n // config is confirmed published, so the pointer never claims undeployed state.\n const persistDeployState = () => {\n try {\n const pins = pinsFromPublishedConfig(publishPayload as BosConfigInput, account, gateway);\n if (Object.keys(pins).length > 0) {\n upsertDeployStatePins(configDir, account, gateway, pins);\n }\n } catch (error) {\n console.log(\n colors.dim(\n ` Note: could not update .bos/deploy-state.json — ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n };\n\n try {\n const alreadyPublished = await isConfigAlreadyPublished({\n account,\n gateway,\n publishConfig: publishPayload,\n registry: input.registry,\n });\n if (alreadyPublished) {\n console.log(\" Already up to date — skipping transaction\");\n persistDeployState();\n return {\n status: \"published\",\n registryUrl,\n built,\n skipped,\n deployResults,\n publishConfig: publishPayload,\n };\n }\n\n console.log(` Submitting transaction on ${network}...`);\n\n let result: { success: boolean; txHash?: string };\n if (useWallet) {\n const session = readSessionHandle(configDir);\n const credential = session?.credential;\n if (!credential || credential.accountId !== account) {\n return {\n status: \"error\",\n registryUrl,\n error: `--wallet requires a CLI session under ${account}. Run bos login first.`,\n };\n }\n const record = await ensureDelegateKey({\n configDir,\n account,\n contract: registryNamespace,\n network,\n siteUrl: credential.siteUrl,\n });\n result = await submitRegistryWriteDelegated({\n account,\n contract: registryNamespace,\n network,\n args: registryEntries,\n delegatePrivateKey: record.privateKey,\n relayEndpoint: `${credential.siteUrl}/api/auth/near/relay`,\n apiKey: credential.apiKey,\n });\n } else {\n if (!strategy) {\n return {\n status: \"error\",\n registryUrl,\n error: \"non-wallet publish requires a resolved signing strategy\",\n };\n }\n result = await submitRegistryWrite(\n {\n account,\n contract: registryNamespace,\n method: \"__fastdata_kv\",\n args: registryEntries,\n network,\n privateKey: input.privateKey,\n },\n strategy,\n );\n }\n\n if (result.txHash) {\n console.log(` Transaction submitted: ${colors.dim(result.txHash)}`);\n }\n\n console.log(\" Waiting for publish confirmation...\");\n await waitForPublishedConfig({\n account,\n gateway,\n publishConfig: publishPayload,\n registry: input.registry,\n });\n persistDeployState();\n\n return {\n status: \"published\",\n registryUrl,\n txHash: result.txHash,\n fingerprint,\n slotPins: publishSlotPins,\n built,\n skipped,\n deployResults,\n publishConfig: publishPayload,\n };\n } catch (error) {\n return {\n status: \"error\",\n registryUrl,\n error: formatNearError(error),\n built,\n skipped,\n deployResults,\n };\n }\n}\n\nfunction formatNearError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n\n if (message.includes(\"does not have enough allowance\")) {\n return (\n \"The publish access key has insufficient allowance to cover this transaction.\\n\" +\n \" Regenerate your key with a higher allowance:\\n\" +\n \" bos key generate\\n\" +\n ` Original: ${message}`\n );\n }\n\n if (message.includes(\"exceeded gas\") || message.includes(\"GasLimitExceeded\")) {\n return `Transaction exceeded gas limit.\\n Original: ${message}`;\n }\n\n if (message.includes(\"timeout\") || message.includes(\"Timeout\")) {\n return `Transaction timed out. Check NEAR network status.\\n Original: ${message}`;\n }\n\n return message;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAqBA,eAAe,4BAA4B,OAWC;CAC1C,IAAI,CAAC,MAAM,QAAQ,OAAO;CAC1B,MAAM,kBAAkBA,gEAAgC;EACtD,QAAQ,MAAM;EACd,WAAW,MAAM;EACjB,cAAc,MAAM;EACpB,GAAI,MAAM,QAAQ,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;CAC9C,CAAC;CACD,IAAI,CAAC,iBAAiB,OAAO;CAE7B,MAAM,eAAe,YAAY,gBAAgB,QAAQ;CACzD,MAAM,iBAAiB,MAAMC,oCAAa;EACxC,QAAQ,MAAM;EACd,QAAQ,MAAM;EACd,SAAS,MAAM;EACf,SAAS,MAAM;EACf,WAAW,MAAM;EACjB,OAAO,CACL;GACE,MAAM;GACN,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,GAAG,KAAK,UAAU,iBA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AEA,SAAS,gBAAgB,OAAwB;CAC/C,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAErE,IAAI,QAAQ,SAAS,gCAAgC,GACnD,OACE;;;cAGe;CAInB,IAAI,QAAQ,SAAS,cAAc,KAAK,QAAQ,SAAS,kBAAkB,GACzE,OAAO,gDAAgD;CAGzD,IAAI,QAAQ,SAAS,SAAS,KAAK,QAAQ,SAAS,SAAS,GAC3D,OAAO,kEAAkE;CAG3E,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"publish.cjs","names":["composeWorkspaceVersionManifest","uploadBundle","colors","padRight","run","makeSourceArchiveTempDir","buildSourceArchive","resolveSlotVersion","readFileSync","localSriMap","diffWorkspaceFiles","uploadWorkspaceDist","mergedFileIntegrity","process","fetchBosConfigFromFastKv","fetchResponse","join","existsSync","getNetworkIdForAccount","buildRegistryConfigUrlForNetwork","readSessionHandle","resolveSigningStrategy","describeSigningStrategy","resolveCdnDeployInputs","probeStorageOrigin","fetchPublishedConfigFromFastKv","getRegistryNamespaceForNetwork","selectWorkspaceTargets","generateCodeArtifacts","buildWorkspaceTargets","icons","openResolution","findConfigPath","isAppDescriptorPath","mergeAuthoredOverPublished","pinsFromPublishedConfig","pinsFromDeployState","resolveWorkspaceTarget","collectDistFiles","readBuildReport","dirname","basename","formatDuration","platformUrlDeployEntries","hasFolderFormUi","resolveUiRuntimeName","pluginUiUrlDeployEntries","applyDeployResults","verifyRollbackSnapshot","pointerFingerprint","slotPins","ensureCustodyBalance","submitRegistryWriteCustody","ensureDelegateKey","submitRegistryWriteDelegated","submitRegistryWrite"],"sources":["../src/publish.ts"],"sourcesContent":["import { existsSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport process from \"node:process\";\nimport { hasFolderFormUi } from \"every-plugin/build/ui\";\nimport type { SourceRef } from \"every-plugin/version-manifest\";\nimport { readSessionHandle } from \"./auth-session\";\nimport { buildWorkspaceTargets, resolveWorkspaceTarget, selectWorkspaceTargets } from \"./build\";\nimport { type CdnDeployInputs, probeStorageOrigin, resolveCdnDeployInputs } from \"./cdn-deploy\";\nimport { formatDuration } from \"./cli/timing\";\nimport { generateCodeArtifacts } from \"./code-artifacts\";\nimport { findConfigPath, isAppDescriptorPath, resolveUiRuntimeName } from \"./config\";\nimport type { WorkspaceDeployResult } from \"./contract\";\nimport { ensureCustodyBalance, submitRegistryWriteCustody } from \"./custody-signer\";\nimport { ensureDelegateKey, submitRegistryWriteDelegated } from \"./delegate-signer\";\nimport {\n diffWorkspaceFiles,\n localSriMap,\n mergedFileIntegrity,\n type PreviousPin,\n pinsFromDeployState,\n pinsFromPublishedConfig,\n upsertDeployStatePins,\n} from \"./deploy-diff\";\nimport {\n buildRegistryConfigUrlForNetwork,\n fetchBosConfigFromFastKv,\n fetchPublishedConfigFromFastKv,\n getRegistryNamespaceForNetwork,\n type NetworkId,\n} from \"./fastkv\";\nimport { pointerFingerprint, slotPins } from \"./fingerprint\";\nimport { fetchResponse } from \"./http-client\";\nimport { applyDeployResults, type DeployResultEntry } from \"./integrity\";\nimport { mergeAuthoredOverPublished } from \"./merge\";\nimport {\n describeSigningStrategy,\n resolveSigningStrategy,\n type SigningStrategy,\n submitRegistryWrite,\n} from \"./near-signer\";\nimport { getNetworkIdForAccount } from \"./network\";\nimport { platformUrlDeployEntries, pluginUiUrlDeployEntries } from \"./platform-deploy\";\nimport { openResolution } from \"./resolution/session\";\nimport { verifyRollbackSnapshot } from \"./rollback\";\nimport { buildSourceArchive, makeSourceArchiveTempDir } from \"./source-archive\";\nimport {\n collectDistFiles,\n type DistFile,\n uploadBundle,\n uploadWorkspaceDist,\n} from \"./storage-upload\";\nimport type { BosConfig, BosConfigInput, PublishConfig, RuntimeConfig } from \"./types\";\nimport { run } from \"./utils/run\";\nimport { padRight } from \"./utils/string\";\nimport { colors, icons } from \"./utils/theme\";\nimport { composeWorkspaceVersionManifest, readBuildReport } from \"./version-manifest-deploy\";\nimport { resolveSlotVersion } from \"./version-manifest-resolve\";\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Compose + upload the workspace's version manifest (atomic-deploys 03): the\n * manifest is built from the dist build report + the **server-computed** SRI\n * map of the just-finished upload, uploaded additively at\n * `versions/<version>.json`, and returned as the slot's pointer. Returns\n * undefined when the dist predates hashed entry names (no report / no entry\n * SRI) — the caller aborts the train: uploaded workspaces must pin.\n */\n/**\n * The manifest's own storage backend — when every dist file was diff-skipped\n * it is the only upload of the leg, so it is the only signal for the\n * memory-backend abort below.\n */\nexport interface VersionManifestPin {\n file: string;\n integrity: string;\n storage?: \"s3\" | \"memory\";\n}\n\nasync function pinWorkspaceVersionManifest(input: {\n origin: string;\n apiKey?: string;\n account: string;\n gateway: string;\n workspace: string;\n report: ReturnType<typeof readBuildReport>;\n ssrReport: ReturnType<typeof readBuildReport>;\n integrityMap: Record<string, string>;\n /** full per-file SRI map of the dist — recorded for the next deploy's diff */\n files?: Record<string, string>;\n /** source archive reference — server-computed SRI (MAP decision 6) */\n source?: SourceRef;\n /** repo HEAD the build was produced from — best-effort, may be absent */\n gitSha?: string;\n}): Promise<VersionManifestPin | undefined> {\n if (!input.report) return undefined;\n const versionManifest = composeWorkspaceVersionManifest({\n report: input.report,\n ssrReport: input.ssrReport,\n integrityMap: input.integrityMap,\n ...(input.files ? { files: input.files } : {}),\n ...(input.source ? { source: input.source } : {}),\n ...(input.gitSha ? { gitSha: input.gitSha } : {}),\n });\n if (!versionManifest) return undefined;\n\n const manifestFile = `versions/${versionManifest.version}.json`;\n const manifestUpload = await uploadBundle({\n origin: input.origin,\n apiKey: input.apiKey,\n account: input.account,\n gateway: input.gateway,\n workspace: input.workspace,\n files: [\n {\n path: manifestFile,\n bytes: new TextEncoder().encode(`${JSON.stringify(versionManifest, null, 2)}\\n`),\n },\n ],\n });\n const manifestIntegrity = manifestUpload.integrity[manifestFile];\n if (!manifestIntegrity) return undefined;\n console.log(\n ` ${colors.dim(`${padRight(\"\", 28)} version manifest ${manifestFile} (SRI pinned)`)}`,\n );\n return { file: manifestFile, integrity: manifestIntegrity, storage: manifestUpload.storage };\n}\n\n/**\n * Best-effort repo HEAD for the version manifest (`gitSha`): non-git\n * contexts (child bundles built outside a repo) omit the field silently —\n * it never fails the deploy.\n */\nasync function resolveGitSha(cwd: string): Promise<string | undefined> {\n try {\n const result = await run(\"git\", [\"rev-parse\", \"HEAD\"], { cwd, capture: true });\n const sha = result?.stdout.trim();\n return result && result.exitCode === 0 && sha ? sha : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The source-archive leg (publish.sourcePublish, #406): tar the workspace\n * subtree, dedupe against the previous pin's manifest by archive SRI (reuse\n * skips the upload), otherwise upload and take the **server-computed** SRI\n * (MAP decision 6). The temp archive dir is cleaned up on every path — the\n * manifest only carries `{ file, integrity }`, not the bytes.\n */\nasync function resolveSourceReference(input: {\n origin: string;\n apiKey?: string;\n account: string;\n gateway: string;\n workspace: string;\n base: string;\n previousPin: PreviousPin | undefined;\n repoRoot: string;\n workspaceDir: string;\n}): Promise<{ source: SourceRef } | { memory: true }> {\n const outDir = makeSourceArchiveTempDir();\n try {\n const archive = await buildSourceArchive({\n repoRoot: input.repoRoot,\n workspace: input.workspaceDir,\n outDir,\n });\n if (input.previousPin) {\n try {\n const resolved = await resolveSlotVersion({ base: input.base, pin: input.previousPin });\n if (resolved.source?.integrity === archive.integrity) {\n console.log(\n ` ${colors.dim(`${padRight(input.workspace, 28)} source unchanged — reusing ${archive.file}`)}`,\n );\n return {\n source: { file: resolved.source.file, integrity: resolved.source.integrity },\n };\n }\n } catch {\n // previous manifest unusable — fall through to a full upload\n }\n }\n const upload = await uploadBundle({\n origin: input.origin,\n apiKey: input.apiKey,\n account: input.account,\n gateway: input.gateway,\n workspace: input.workspace,\n files: [{ path: archive.file, bytes: new Uint8Array(readFileSync(archive.path)) }],\n });\n if (upload.storage === \"memory\") return { memory: true };\n const integrity = upload.integrity[archive.file];\n if (!integrity) {\n throw new Error(\n `[publish] source archive upload for ${input.workspace}: missing server SRI for ${archive.file}`,\n );\n }\n console.log(\n ` ${colors.dim(`${padRight(input.workspace, 28)} source archive ${archive.file}`)}`,\n );\n return { source: { file: archive.file, integrity } };\n } finally {\n rmSync(outDir, { recursive: true, force: true });\n }\n}\n\ninterface DiffUploadOutcome {\n result: {\n stored: number;\n totalBytes: number;\n integrity: Record<string, string>;\n storage?: \"s3\" | \"memory\";\n };\n /** per-file SRI map covering the whole dist (uploaded → server SRI, skipped → previous manifest SRI) */\n fileIntegrity: Record<string, string>;\n uploaded: number;\n skipped: number;\n total: number;\n}\n\n/**\n * One workspace's upload leg with skip-unchanged diffing: resolve the previous\n * manifest's `files` map, hash the local dist, upload only new/changed files,\n * and return the merged per-file SRI map for the version manifest. Any failure\n * to resolve the previous map degrades to a full upload.\n */\nasync function diffUploadWorkspace(input: {\n origin: string;\n apiKey?: string;\n account: string;\n gateway: string;\n workspace: string;\n files: DistFile[];\n base: string;\n previousPin: PreviousPin | undefined;\n}): Promise<DiffUploadOutcome> {\n const localSri = localSriMap(input.files);\n let uploadFiles = input.files;\n let prevFiles: Record<string, string> | undefined;\n if (input.previousPin) {\n try {\n const resolved = await resolveSlotVersion({ base: input.base, pin: input.previousPin });\n if (resolved.files) {\n const diff = diffWorkspaceFiles(input.files, localSri, resolved.files);\n prevFiles = resolved.files;\n uploadFiles = diff.upload;\n if (diff.skipped > 0) {\n console.log(\n ` ${colors.dim(`${padRight(input.workspace, 28)} ${diff.skipped} unchanged file(s) — skipping (manifest diff)`)}`,\n );\n }\n }\n } catch {\n console.log(\n ` ${colors.dim(`${padRight(input.workspace, 28)} previous manifest unusable — uploading everything`)}`,\n );\n }\n }\n\n console.log(\n ` ${padRight(input.workspace, 28)} uploading ${uploadFiles.length} of ${input.files.length} files (${formatBundleMb(uploadFiles)}) → ${input.base}`,\n );\n const result =\n uploadFiles.length > 0\n ? await uploadWorkspaceDist({\n origin: input.origin,\n apiKey: input.apiKey,\n account: input.account,\n gateway: input.gateway,\n workspace: input.workspace,\n files: uploadFiles,\n })\n : { stored: 0, totalBytes: 0, integrity: {}, storage: undefined };\n return {\n result,\n fileIntegrity: mergedFileIntegrity(input.files, result.integrity, prevFiles),\n uploaded: result.stored,\n skipped: input.files.length - uploadFiles.length,\n total: input.files.length,\n };\n}\n\nfunction formatBundleMb(files: Array<{ bytes: Uint8Array }>): string {\n const total = files.reduce((sum, file) => sum + file.bytes.byteLength, 0);\n return `${(total / 1024 / 1024).toFixed(1)} MB`;\n}\n\nexport async function waitForPublishedConfig(opts: {\n account: string;\n gateway: string;\n publishConfig: BosConfigInput;\n registry?: string;\n timeoutMs?: number;\n intervalMs?: number;\n}): Promise<void> {\n const envTimeoutMs = Number(process.env.BOS_PUBLISH_CONFIRMATION_TIMEOUT_MS);\n const envIntervalMs = Number(process.env.BOS_PUBLISH_CONFIRMATION_INTERVAL_MS);\n const timeoutMs =\n opts.timeoutMs ?? (Number.isFinite(envTimeoutMs) ? envTimeoutMs : undefined) ?? 120_000;\n const intervalMs =\n opts.intervalMs ?? (Number.isFinite(envIntervalMs) ? envIntervalMs : undefined) ?? 3_000;\n const startedAt = Date.now();\n let lastError: unknown;\n\n while (Date.now() - startedAt < timeoutMs) {\n try {\n const verifiedConfig = await fetchBosConfigFromFastKv<BosConfigInput>(\n `bos://${opts.account}/${opts.gateway}`,\n opts.registry,\n );\n\n if (JSON.stringify(verifiedConfig) === JSON.stringify(opts.publishConfig)) {\n return;\n }\n } catch (error) {\n lastError = error;\n }\n\n await sleep(intervalMs);\n }\n\n const reason = lastError instanceof Error ? ` Last error: ${lastError.message}` : \"\";\n throw new Error(\n `Timed out waiting for publish confirmation at bos://${opts.account}/${opts.gateway}.${reason}`,\n );\n}\n\nexport async function isConfigAlreadyPublished(opts: {\n account: string;\n gateway: string;\n publishConfig: BosConfigInput;\n registry?: string;\n}): Promise<boolean> {\n try {\n const current = await fetchBosConfigFromFastKv<BosConfigInput>(\n `bos://${opts.account}/${opts.gateway}`,\n opts.registry,\n );\n return JSON.stringify(current) === JSON.stringify(opts.publishConfig);\n } catch {\n return false;\n }\n}\n\ninterface PublishToFastKvInput {\n bosConfig: BosConfig;\n runtimeConfig: RuntimeConfig | null;\n configDir: string;\n env: \"production\" | \"staging\";\n build: boolean;\n dryRun: boolean;\n verbose: boolean;\n packages: string;\n network?: \"mainnet\" | \"testnet\";\n privateKey?: string;\n wallet?: boolean;\n registry?: string;\n /** Skip the diff upload and re-upload every dist file (escape hatch). */\n fullUpload?: boolean;\n /** Publish `bosConfig` verbatim — no authored/published merge, no ts-form\n * config-only guard. Rollbacks use this: the payload is the previous\n * snapshot, already assembled. */\n exactPayload?: boolean;\n}\n\ninterface PublishToFastKvResult {\n status: \"published\" | \"error\" | \"dry-run\";\n registryUrl: string;\n txHash?: string;\n built?: string[];\n skipped?: string[];\n error?: string;\n publishConfig?: BosConfigInput;\n deployResults?: WorkspaceDeployResult[];\n fingerprint?: string;\n slotPins?: Record<string, string>;\n}\n\nexport type PublishedConfigState = \"fetched\" | \"missing\" | \"unreachable\";\n\nexport interface PublishPreflightPlan {\n isStaging: boolean;\n account: string;\n gateway: string;\n network: NetworkId;\n registryUrl: string;\n registryNamespace: string;\n targets: string[];\n useWallet: boolean;\n useCustody: boolean;\n strategy?: SigningStrategy;\n cdnOrigin: string | undefined;\n storageOrigin: string;\n storageApiKey?: string;\n /** The config currently published to FastKV (null when missing or unreachable). */\n publishedConfig: Record<string, unknown> | null;\n /** Whether the preflight FastKV read succeeded, found nothing, or failed. */\n publishedConfigState: PublishedConfigState;\n}\n\nexport type PublishPreflight =\n | { kind: \"dry-run\"; registryUrl: string }\n | { kind: \"error\"; registryUrl: string; error: string }\n | { kind: \"ready\"; plan: PublishPreflightPlan };\n\nconst FRAMEWORK_PACKAGE_NAMES = [\"better-near-auth\", \"every-plugin\", \"everything-dev\"] as const;\n\n/**\n * Whether npm serves `name@version` (true), definitively does not (404 —\n * false), or whether publishability could not be determined (network error,\n * unexpected status — null; callers must not block on that).\n */\nexport async function npmVersionPublished(name: string, version: string): Promise<boolean | null> {\n try {\n const res = await fetchResponse(`https://registry.npmjs.org/${name}/${version}`, {\n headers: { Accept: \"application/json\" },\n });\n if (res.status === 200) return true;\n if (res.status === 404) return false;\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * The npm-publish gate: a workspace that vendors the framework packages'\n * sources must not ship bundles ahead of npm — the update check, child\n * scaffolds (`bos init`), and template syncs all read those versions from\n * the registry. Reads only apply when the sources are workspace-local (the\n * parent repo); child projects install the framework from npm and are\n * inherently in sync.\n */\nexport async function findUnpublishedFrameworkPackages(\n configDir: string,\n): Promise<Array<{ name: string; version: string }>> {\n const unpublished: Array<{ name: string; version: string }> = [];\n for (const name of FRAMEWORK_PACKAGE_NAMES) {\n const manifestPath = join(configDir, \"packages\", name, \"package.json\");\n if (!existsSync(manifestPath)) continue;\n const version = (JSON.parse(readFileSync(manifestPath, \"utf-8\")) as { version?: string })\n .version;\n if (!version) continue;\n const published = await npmVersionPublished(name, version);\n if (published === false) {\n unpublished.push({ name, version });\n } else if (published === null) {\n console.log(\n colors.yellow(\n ` ! Could not verify ${name}@${version} on npm (registry unreachable) — continuing`,\n ),\n );\n }\n }\n return unpublished;\n}\n\n// Pure preflight (resolve, don't mutate) — every failure returns before the\n// build train runs (issue #287). Dry-run exits after the auth guards, before\n// any signing (keychain/TTY side effects).\nexport async function preflightPublish(input: PublishToFastKvInput): Promise<PublishPreflight> {\n const { configDir } = input;\n const bosConfig = input.bosConfig;\n\n const isStaging = input.env === \"staging\";\n const account = isStaging ? (bosConfig.staging?.account ?? bosConfig.account) : bosConfig.account;\n const gateway = isStaging ? (bosConfig.staging?.domain ?? bosConfig.domain) : bosConfig.domain;\n if (!gateway) {\n return {\n kind: \"error\",\n registryUrl: \"\",\n error: \"authored config must define domain to publish\",\n };\n }\n\n const network: NetworkId = input.network ?? getNetworkIdForAccount(account);\n const registryUrl = buildRegistryConfigUrlForNetwork(network, account, gateway, input.registry);\n const fail = (error: string): PublishPreflight => ({ kind: \"error\", registryUrl, error });\n\n const publishAuth: PublishConfig[\"auth\"] = bosConfig.publish?.auth;\n const governsWalletPublish = (publishAuth === \"session\" || input.wallet) && !input.privateKey;\n if (governsWalletPublish) {\n const session = readSessionHandle(configDir);\n if (!session?.credential) {\n return fail(\n (input.wallet\n ? \"--wallet requires\"\n : 'the authored config sets publish.auth = \"session\", but') +\n \" no CLI session is stored in .bos/ for this project. Run bos login to create one.\",\n );\n }\n if (session.credential.accountId && session.credential.accountId !== account) {\n return fail(\n `The CLI session was created for ${session.credential.accountId}, but the configured ` +\n `account is ${account}. Gasless wallet publish relays the FastKV write under the session's ` +\n \"NEAR account. Run bos login again under the matching account.\",\n );\n }\n }\n const useCustody = publishAuth === \"custody\" && !input.privateKey && !input.wallet;\n if (useCustody) {\n const session = readSessionHandle(configDir);\n const custodyWallet = session?.custodyWallet;\n if (!custodyWallet) {\n return fail(\n 'the authored config sets publish.auth = \"custody\", but no custody wallet is stored in ' +\n \".bos/. Run `bos login --custody` first.\",\n );\n }\n if (custodyWallet.network !== network) {\n return fail(\n `The custody wallet was registered on ${custodyWallet.network}, but this project publishes ` +\n `on ${network}. Run \\`bos login --custody\\` from a ${network} account.`,\n );\n }\n if (custodyWallet.nearAccountId !== account) {\n return fail(\n `publish.auth = \"custody\" publishes under the custody wallet's account, but the configured ` +\n `account is ${account} and the custody wallet account is ${custodyWallet.nearAccountId}. ` +\n \"Set the authored config's account to the custody wallet account.\",\n );\n }\n }\n\n if (input.dryRun) {\n return { kind: \"dry-run\", registryUrl };\n }\n\n const useWallet = input.wallet === true;\n let strategy: SigningStrategy | undefined;\n if (useWallet) {\n console.log(\n ` Signing via ${colors.cyan(\"gasless NEP-366 delegate action (relayed by the platform relayer)\")}`,\n );\n } else {\n try {\n strategy = await resolveSigningStrategy({ privateKey: input.privateKey, account, network });\n console.log(` Signing via ${colors.cyan(describeSigningStrategy(strategy))}`);\n } catch (error) {\n return fail(error instanceof Error ? error.message : \"Unknown error\");\n }\n }\n\n // CDN deploy credentials (ADR 0020) — resolved before the build train so a\n // missing bundle origin or BOS_STORAGE_API_KEY fails fast instead of after\n // the full build. Config-only publishes ship the committed config verbatim;\n // nothing is uploaded, so no deploy origins are required.\n const session = readSessionHandle(configDir);\n let cdnDeploy: CdnDeployInputs = {\n cdnOrigin: undefined,\n storageOrigin: \"\",\n apiKey: undefined,\n };\n if (input.build) {\n const unpublished = await findUnpublishedFrameworkPackages(configDir);\n if (unpublished.length > 0) {\n const listing = unpublished.map((pkg) => `${pkg.name}@${pkg.version}`).join(\", \");\n return fail(\n `Framework package(s) ${listing} are not published to npm yet — deploys must not ship ` +\n \"bundles ahead of the registry (child scaffolds and update checks read these versions). \" +\n \"Re-run the Release workflow (or `pnpm run release`) first.\",\n );\n }\n\n cdnDeploy = resolveCdnDeployInputs({\n env: process.env as Record<string, string | undefined>,\n bosConfig,\n session: session?.credential ?? null,\n custodyAccount: useCustody ? session?.custodyWallet?.nearAccountId : undefined,\n account,\n gateway,\n uploadsPlanned: input.build,\n });\n if (cdnDeploy.error) {\n return fail(cdnDeploy.error);\n }\n if (cdnDeploy.warning) {\n console.log(colors.yellow(` ! ${cdnDeploy.warning}`));\n }\n const cdnOrigin = cdnDeploy.cdnOrigin;\n if (!cdnOrigin) {\n return fail(\"CDN deploy resolved no bundle origin\");\n }\n const probeError = await probeStorageOrigin(cdnDeploy.storageOrigin);\n if (probeError) {\n return fail(\n `The bundle upload origin ${cdnDeploy.storageOrigin} is not running the platform API — ` +\n `${probeError}. Check BOS_STORAGE_ORIGIN / the bos login session, then re-run.`,\n );\n }\n }\n\n // Registry reachability + published-state capture: one FastKV read. A\n // missing config is fine for a first publish — an early signal, not a hard\n // gate. The captured config is the merge base for a config-only publish on\n // a TS-form project (authored hand-edits win; live pipeline state carries).\n let publishedConfig: Record<string, unknown> | null = null;\n let publishedConfigState: PublishedConfigState = \"missing\";\n try {\n publishedConfig = await fetchPublishedConfigFromFastKv<Record<string, unknown>>(registryUrl);\n publishedConfigState = \"fetched\";\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.startsWith(\"No config found\")) {\n console.log(colors.dim(\" Note: no published config found yet (first publish) — continuing\"));\n } else {\n publishedConfigState = \"unreachable\";\n console.log(colors.dim(\" Note: registry read failed — continuing\"));\n }\n }\n\n return {\n kind: \"ready\",\n plan: {\n isStaging,\n account,\n gateway,\n network,\n registryUrl,\n registryNamespace: getRegistryNamespaceForNetwork(network, input.registry),\n targets: selectWorkspaceTargets(input.packages, bosConfig),\n useWallet,\n useCustody,\n strategy,\n cdnOrigin: cdnDeploy.cdnOrigin,\n storageOrigin: cdnDeploy.storageOrigin,\n storageApiKey: cdnDeploy.apiKey,\n publishedConfig,\n publishedConfigState,\n },\n };\n}\n\n/**\n * The deploy-train publish core (ADR 0020, as amended): preflight\n * (storage/CDN creds + signing) fails fast before the build, then build →\n * upload → version-manifest pin → config write-back → FastKV publish +\n * read-back. Scoped to one plugin via `packages`, a single-plugin redeploy\n * ships real bytes to the storage origin — same as the full train, nothing\n * image-native left.\n */\nexport async function publishToFastKv(input: PublishToFastKvInput): Promise<PublishToFastKvResult> {\n const preflight = await preflightPublish(input);\n if (preflight.kind === \"error\") {\n return { status: \"error\", registryUrl: preflight.registryUrl, error: preflight.error };\n }\n if (preflight.kind === \"dry-run\") {\n return { status: \"dry-run\", registryUrl: preflight.registryUrl };\n }\n const plan = preflight.plan;\n const {\n isStaging,\n account,\n gateway,\n network,\n registryUrl,\n registryNamespace,\n targets,\n useWallet,\n useCustody,\n strategy,\n } = plan;\n const storageOrigin = plan.storageOrigin;\n const storageApiKey = plan.storageApiKey;\n\n const { configDir } = input;\n let bosConfig = input.bosConfig;\n const runtimeConfig = input.runtimeConfig;\n let built: string[] | undefined;\n let skipped: string[] | undefined;\n let deployResults: WorkspaceDeployResult[] | undefined;\n let refreshedRawConfig: BosConfigInput | null = null;\n\n if (input.build) {\n await generateCodeArtifacts(configDir, bosConfig, {\n env: \"production\",\n runtimeConfig: runtimeConfig ?? undefined,\n });\n\n const result = await buildWorkspaceTargets({\n configDir,\n bosConfig,\n runtimeConfig,\n targets,\n deploy: true,\n verbose: input.verbose,\n });\n built = result.built;\n skipped = result.skipped;\n deployResults = result.deployResults;\n\n if (deployResults) {\n const failures = deployResults.filter((r) => !r.success);\n if (failures.length > 0) {\n const total = deployResults.length;\n console.log();\n console.log(\n colors.error(\n ` ${icons.err} Deploy failed — ${failures.length} of ${total} workspace${total > 1 ? \"s\" : \"\"} failed`,\n ),\n );\n console.log();\n for (const f of failures) {\n const errorLine = (f.error ?? \"Failed\").split(\"\\n\")[0];\n console.log(` ${colors.error(icons.err)} ${padRight(f.key, 28)} ${errorLine}`);\n }\n console.log();\n if (!input.verbose) {\n console.log(colors.dim(\" Run with --verbose for full build output.\"));\n console.log();\n }\n return {\n status: \"error\" as const,\n registryUrl,\n built,\n skipped,\n deployResults,\n error: `${failures.length} of ${total} workspaces failed to deploy`,\n };\n }\n }\n\n const refreshed = await openResolution({ cwd: configDir });\n if (!refreshed?.config) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: \"Failed to reload the config after build\",\n };\n }\n\n bosConfig = refreshed.config;\n refreshedRawConfig = refreshed.rawConfig;\n }\n\n const authoredPath = findConfigPath(configDir);\n const tsForm = authoredPath !== null && isAppDescriptorPath(authoredPath);\n let rawConfig: BosConfigInput;\n if (refreshedRawConfig) {\n rawConfig = refreshedRawConfig;\n } else {\n const opened = await openResolution({ cwd: configDir });\n if (!opened?.rawConfig) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: \"Failed to load the authored config for publish\",\n };\n }\n rawConfig = opened.rawConfig;\n }\n if (\n tsForm &&\n !input.build &&\n input.exactPayload !== true &&\n plan.publishedConfigState === \"unreachable\"\n ) {\n // A config-only TS-form publish derives its pipeline state from the live\n // published config — publishing without it would wipe bundle URLs.\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error:\n \"Cannot read the currently published config from the registry — a config-only publish would overwrite live bundle URLs. Retry when the registry is reachable, or run a full deploy.\",\n };\n }\n let publishPayload: BosConfigInput =\n input.exactPayload === true\n ? input.bosConfig\n : tsForm && !input.build\n ? // Config-only publish on a TS-form project: the authored config owns\n // composition (hand-edits win) while live pipeline state (bundle\n // URLs, integrity) carries over from the published config.\n mergeAuthoredOverPublished((plan.publishedConfig ?? {}) as BosConfigInput, rawConfig)\n : rawConfig;\n\n const urlOrigin = plan.cdnOrigin ?? `https://${gateway}`;\n const deployTargets = (built ?? []).filter((key) => targets.includes(key));\n const platformEntries: DeployResultEntry[] = [];\n const fullUpload = input.fullUpload === true || process.env.BOS_FULL_UPLOAD === \"1\";\n // Previous per-workspace pins for the diff upload: the local pointer wins\n // (written after every confirmed publish), the published config is the\n // fallback. Neither → full upload.\n const prevPins: Record<string, PreviousPin> = fullUpload\n ? {}\n : {\n ...pinsFromPublishedConfig(\n (plan.publishedConfig ?? {}) as BosConfigInput,\n account,\n gateway,\n ),\n ...pinsFromDeployState(configDir, account, gateway),\n };\n\n console.log();\n console.log(` CDN deploy — uploading workspace dists to ${storageOrigin}...`);\n const sourcePublish = bosConfig.publish?.sourcePublish === true;\n const gitSha = await resolveGitSha(configDir);\n const memoryBackendAbort = (): PublishToFastKvResult => ({\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error:\n \"The receiving instance is serving bundle storage from memory (BOS_STORAGE_* R2 credentials are not configured there) — uploaded bytes would be lost on restart. Aborting before publish.\",\n });\n for (const key of deployTargets) {\n const ws = resolveWorkspaceTarget(key, bosConfig, runtimeConfig, configDir);\n if (!ws) continue;\n\n const distFiles = await collectDistFiles(join(ws.path, \"dist\"));\n const workspaceBase = `${urlOrigin}/bundles/${account}/${gateway}/${key}/`;\n const startedAt = Date.now();\n // an upload failure aborts the train as a structured error — the\n // previously published version stays fully live (ticket 05)\n let outcome: DiffUploadOutcome;\n try {\n outcome = await diffUploadWorkspace({\n origin: storageOrigin,\n apiKey: storageApiKey,\n account,\n gateway,\n workspace: key,\n files: distFiles,\n base: workspaceBase,\n previousPin: prevPins[key],\n });\n } catch (error) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: error instanceof Error ? error.message : `[publish] bundle upload for ${key} failed`,\n };\n }\n const report = readBuildReport(join(ws.path, \"dist\"));\n const ssrReport = readBuildReport(join(ws.path, \"dist\", \"ssr\"));\n // the entry SRI keyed by the build report's hashed name\n const integrity = report ? outcome.fileIntegrity[report.entry] : undefined;\n const ssrIntegrity = ssrReport?.entry\n ? outcome.fileIntegrity[`ssr/${ssrReport.entry}`]\n : undefined;\n\n let sourceRef: SourceRef | undefined;\n if (sourcePublish) {\n if (outcome.result.storage === \"memory\") {\n return memoryBackendAbort();\n }\n try {\n const sourceOutcome = await resolveSourceReference({\n origin: storageOrigin,\n apiKey: storageApiKey,\n account,\n gateway,\n workspace: key,\n base: workspaceBase,\n previousPin: prevPins[key],\n repoRoot: dirname(ws.path),\n workspaceDir: basename(ws.path),\n });\n if (\"memory\" in sourceOutcome) {\n return memoryBackendAbort();\n }\n sourceRef = sourceOutcome.source;\n } catch (error) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error:\n error instanceof Error ? error.message : `[publish] source archive for ${key} failed`,\n };\n }\n }\n\n const manifestPointer = await pinWorkspaceVersionManifest({\n origin: storageOrigin,\n apiKey: storageApiKey,\n account,\n gateway,\n workspace: key,\n report,\n ssrReport,\n integrityMap: outcome.fileIntegrity,\n files: outcome.fileIntegrity,\n ...(sourceRef ? { source: sourceRef } : {}),\n ...(gitSha ? { gitSha } : {}),\n });\n if (!manifestPointer) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: `bundle upload for ${key}: version manifest missing — the dist predates hashed entry names (rebuild required; atomic-deploys hard break)`,\n };\n }\n\n if (outcome.result.storage === \"memory\" || manifestPointer.storage === \"memory\") {\n return memoryBackendAbort();\n }\n\n console.log(\n ` ${colors.green(icons.ok)} ${padRight(key, 28)} → ${urlOrigin}/bundles/${account}/${gateway}/${key}/ (${outcome.uploaded} uploaded, ${outcome.skipped} skipped, ${formatDuration(Date.now() - startedAt)})`,\n );\n\n platformEntries.push(\n ...platformUrlDeployEntries({\n origin: urlOrigin,\n account,\n gateway,\n key,\n kind: ws.kind,\n integrity,\n ssrIntegrity,\n pin: manifestPointer,\n }),\n );\n\n // Folder-form plugin ui: the workspace build also produces <plugin>/ui/dist\n // (web remoteEntry + ssr container) — upload it as its own bundle key and\n // pin <slot>.<key>.ui.* so the host can compose the ui surface in production.\n if (hasFolderFormUi(ws.path)) {\n const uiDistDir = join(ws.path, \"ui\", \"dist\");\n const uiSlot = ws.kind === \"app\" ? \"app\" : \"plugins\";\n const rawSlot = (uiSlot === \"app\" ? rawConfig.app : rawConfig.plugins) as\n | Record<string, Record<string, unknown> | undefined>\n | undefined;\n const rawUi = rawSlot?.[key]?.ui as Record<string, unknown> | undefined;\n const uiName = resolveUiRuntimeName(rawUi, join(ws.path, \"ui\"), key);\n let uiIntegrity: string | undefined;\n let uiSsrIntegrity: string | undefined;\n let uiManifestPointer: VersionManifestPin | undefined;\n if (existsSync(uiDistDir)) {\n const uiDistFiles = await collectDistFiles(uiDistDir);\n const uiStartedAt = Date.now();\n const uiOutcome = await diffUploadWorkspace({\n origin: storageOrigin,\n apiKey: storageApiKey,\n account,\n gateway,\n workspace: `${key}-ui`,\n files: uiDistFiles,\n base: `${urlOrigin}/bundles/${account}/${gateway}/${key}-ui/`,\n previousPin: prevPins[`${key}-ui`],\n });\n const uiReport = readBuildReport(uiDistDir);\n const uiSsrReport = readBuildReport(join(uiDistDir, \"ssr\"));\n uiIntegrity = uiReport ? uiOutcome.fileIntegrity[uiReport.entry] : undefined;\n uiSsrIntegrity = uiSsrReport?.entry\n ? uiOutcome.fileIntegrity[`ssr/${uiSsrReport.entry}`]\n : undefined;\n\n uiManifestPointer = await pinWorkspaceVersionManifest({\n origin: storageOrigin,\n apiKey: storageApiKey,\n account,\n gateway,\n workspace: `${key}-ui`,\n report: uiReport,\n ssrReport: uiSsrReport,\n integrityMap: uiOutcome.fileIntegrity,\n files: uiOutcome.fileIntegrity,\n });\n if (!uiManifestPointer) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: `bundle upload for ${key}-ui: version manifest missing — the dist predates hashed entry names (rebuild required; atomic-deploys hard break)`,\n };\n }\n\n if (uiOutcome.result.storage === \"memory\" || uiManifestPointer.storage === \"memory\") {\n return memoryBackendAbort();\n }\n\n console.log(\n ` ${colors.green(icons.ok)} ${padRight(`${key}-ui`, 28)} → ${urlOrigin}/bundles/${account}/${gateway}/${key}-ui/ (${uiOutcome.uploaded} uploaded, ${uiOutcome.skipped} skipped, ${formatDuration(Date.now() - uiStartedAt)})`,\n );\n } else {\n console.log(\n ` ${colors.green(icons.ok)} ${padRight(`${key}-ui`, 28)} → ${urlOrigin}/bundles/${account}/${gateway}/${key}-ui/`,\n );\n }\n\n platformEntries.push(\n ...pluginUiUrlDeployEntries({\n origin: urlOrigin,\n account,\n gateway,\n key,\n kind: ws.kind,\n integrity: uiIntegrity,\n ssrIntegrity: uiSsrIntegrity,\n name: uiName,\n pin: uiManifestPointer,\n }),\n );\n }\n }\n\n if (platformEntries.length > 0) {\n const merged = applyDeployResults(rawConfig as Record<string, unknown>, platformEntries);\n if (!tsForm) {\n // Legacy JSON-form children keep their local write-back; TS-form keeps\n // pipeline state in FastKV only — a write-back would shadow the\n // authored bos.app.ts descriptor.\n try {\n writeFileSync(join(configDir, \"bos.config.json\"), `${JSON.stringify(merged, null, 2)}\\n`);\n } catch (error) {\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: `Failed to write bundle URLs to bos.config.json: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n publishPayload = merged as BosConfigInput;\n }\n if (isStaging) {\n publishPayload = { ...publishPayload, domain: gateway };\n }\n\n const pinVerification = await verifyRollbackSnapshot(publishPayload);\n if (pinVerification.verifiable && !pinVerification.ok) {\n const failures = pinVerification.slots\n .filter((check) => !check.ok)\n .map((check) => ` ${check.slot}: ${check.reason}`)\n .join(\"\\n\");\n console.error(\n ` ${colors.error(icons.err)} Publish blocked — a pinned slot's bytes do not serve at its production URL:\\n${failures}`,\n );\n return {\n status: \"error\",\n registryUrl,\n built,\n skipped,\n deployResults,\n error: `Publish blocked — pinned slot bytes missing or SRI mismatched:\\n${failures}`,\n };\n }\n\n const registryKey = `apps/${account}/${gateway}/bos.config.json`;\n const publishedAt = new Date().toISOString();\n // version identity printed + returned for every deploy (atomic-deploys 12)\n const fingerprint = pointerFingerprint(publishPayload as never);\n const publishSlotPins = slotPins(publishPayload as never);\n const registryEntries: Record<string, string> = {\n [registryKey]: JSON.stringify(publishPayload),\n };\n const manifestKey = `apps/${account}/${gateway}/manifests/${publishedAt.replace(/[:.]/g, \"-\")}.json`;\n registryEntries[manifestKey] = JSON.stringify({\n account,\n gateway,\n network,\n publishedAt,\n registryUrl,\n });\n\n console.log();\n console.log(\" Publishing to:\");\n console.log(` ${colors.cyan(registryUrl)}`);\n console.log(` ${colors.dim(\"Fingerprint:\")} ${fingerprint}`);\n for (const [slot, pin] of Object.entries(publishSlotPins)) {\n console.log(` ${colors.dim(`${slot}:`)}`);\n console.log(` ${pin}`);\n }\n console.log(\n ` ${colors.dim(`+ per-deploy manifest ${manifestKey.split(\"/\").pop()} (audit trail)`)}`,\n );\n\n // Record the live pins for the next deploy's diff upload — only after the\n // config is confirmed published, so the pointer never claims undeployed state.\n const persistDeployState = () => {\n try {\n const pins = pinsFromPublishedConfig(publishPayload as BosConfigInput, account, gateway);\n if (Object.keys(pins).length > 0) {\n upsertDeployStatePins(configDir, account, gateway, pins);\n }\n } catch (error) {\n console.log(\n colors.dim(\n ` Note: could not update .bos/deploy-state.json — ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n };\n\n try {\n const alreadyPublished = await isConfigAlreadyPublished({\n account,\n gateway,\n publishConfig: publishPayload,\n registry: input.registry,\n });\n if (alreadyPublished) {\n console.log(\" Already up to date — skipping transaction\");\n persistDeployState();\n return {\n status: \"published\",\n registryUrl,\n built,\n skipped,\n deployResults,\n publishConfig: publishPayload,\n };\n }\n\n console.log(` Submitting transaction on ${network}...`);\n\n let result: { success: boolean; txHash?: string };\n if (useCustody) {\n const custodyWallet = readSessionHandle(configDir)?.custodyWallet;\n if (!custodyWallet) {\n return {\n status: \"error\",\n registryUrl,\n error:\n 'the authored config sets publish.auth = \"custody\", but no custody wallet is stored in ' +\n \".bos/. Run `bos login --custody` first.\",\n };\n }\n await ensureCustodyBalance(custodyWallet);\n console.log(\n ` Signing via ${colors.cyan(`OutLayer custody wallet ${custodyWallet.nearAccountId}`)}`,\n );\n result = await submitRegistryWriteCustody({\n contract: registryNamespace,\n args: registryEntries,\n custodyWallet,\n idempotencyKey: `bos-publish-${fingerprint}`,\n });\n } else if (useWallet) {\n const session = readSessionHandle(configDir);\n const credential = session?.credential;\n if (!credential || credential.accountId !== account) {\n return {\n status: \"error\",\n registryUrl,\n error: `--wallet requires a CLI session under ${account}. Run bos login first.`,\n };\n }\n const record = await ensureDelegateKey({\n configDir,\n account,\n contract: registryNamespace,\n network,\n siteUrl: credential.siteUrl,\n });\n result = await submitRegistryWriteDelegated({\n account,\n contract: registryNamespace,\n network,\n args: registryEntries,\n delegatePrivateKey: record.privateKey,\n relayEndpoint: `${credential.siteUrl}/api/auth/near/relay`,\n apiKey: credential.apiKey,\n });\n } else {\n if (!strategy) {\n return {\n status: \"error\",\n registryUrl,\n error: \"non-wallet publish requires a resolved signing strategy\",\n };\n }\n result = await submitRegistryWrite(\n {\n account,\n contract: registryNamespace,\n method: \"__fastdata_kv\",\n args: registryEntries,\n network,\n privateKey: input.privateKey,\n },\n strategy,\n );\n }\n\n if (result.txHash) {\n console.log(` Transaction submitted: ${colors.dim(result.txHash)}`);\n }\n\n console.log(\" Waiting for publish confirmation...\");\n await waitForPublishedConfig({\n account,\n gateway,\n publishConfig: publishPayload,\n registry: input.registry,\n });\n persistDeployState();\n\n return {\n status: \"published\",\n registryUrl,\n txHash: result.txHash,\n fingerprint,\n slotPins: publishSlotPins,\n built,\n skipped,\n deployResults,\n publishConfig: publishPayload,\n };\n } catch (error) {\n return {\n status: \"error\",\n registryUrl,\n error: formatNearError(error),\n built,\n skipped,\n deployResults,\n };\n }\n}\n\nfunction formatNearError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n\n if (message.includes(\"does not have enough allowance\")) {\n return (\n \"The publish access key has insufficient allowance to cover this transaction.\\n\" +\n \" Regenerate your key with a higher allowance:\\n\" +\n \" bos key generate\\n\" +\n ` Original: ${message}`\n );\n }\n\n if (message.includes(\"exceeded gas\") || message.includes(\"GasLimitExceeded\")) {\n return `Transaction exceeded gas limit.\\n Original: ${message}`;\n }\n\n if (message.includes(\"timeout\") || message.includes(\"Timeout\")) {\n return `Transaction timed out. Check NEAR network status.\\n Original: ${message}`;\n }\n\n return message;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAqBA,eAAe,4BAA4B,OAeC;CAC1C,IAAI,CAAC,MAAM,QAAQ,OAAO;CAC1B,MAAM,kBAAkBA,gEAAgC;EACtD,QAAQ,MAAM;EACd,WAAW,MAAM;EACjB,cAAc,MAAM;EACpB,GAAI,MAAM,QAAQ,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;EAC5C,GAAI,MAAM,SAAS,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;EAC/C,GAAI,MAAM,SAAS,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;CACjD,CAAC;CACD,IAAI,CAAC,iBAAiB,OAAO;CAE7B,MAAM,eAAe,YAAY,gBAAgB,QAAQ;C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UAAU;IACV,QAAQ;IACR,MAAM;IACN;IACA,YAAY,MAAM;GACpB,GACA,QACF;EACF;EAEA,IAAI,OAAO,QACT,QAAQ,IAAI,4BAA4BrD,qBAAO,IAAI,OAAO,MAAM,GAAG;EAGrE,QAAQ,IAAI,uCAAuC;EACnD,MAAM,uBAAuB;GAC3B;GACA;GACA,eAAe;GACf,UAAU,MAAM;EAClB,CAAC;EACD,mBAAmB;EAEnB,OAAO;GACL,QAAQ;GACR;GACA,QAAQ,OAAO;GACf;GACA,UAAU;GACV;GACA;GACA;GACA,eAAe;EACjB;CACF,SAAS,OAAO;EACd,OAAO;GACL,QAAQ;GACR;GACA,OAAO,gBAAgB,KAAK;GAC5B;GACA;GACA;EACF;CACF;AACF;AAEA,SAAS,gBAAgB,OAAwB;CAC/C,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAErE,IAAI,QAAQ,SAAS,gCAAgC,GACnD,OACE;;;cAGe;CAInB,IAAI,QAAQ,SAAS,cAAc,KAAK,QAAQ,SAAS,kBAAkB,GACzE,OAAO,gDAAgD;CAGzD,IAAI,QAAQ,SAAS,SAAS,KAAK,QAAQ,SAAS,SAAS,GAC3D,OAAO,kEAAkE;CAG3E,OAAO;AACT"}
|
package/dist/publish.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { buildRegistryConfigUrlForNetwork, fetchBosConfigFromFastKv, fetchPublis
|
|
|
4
4
|
import { getNetworkIdForAccount } from "./network.mjs";
|
|
5
5
|
import { resolveSlotVersion } from "./version-manifest-resolve.mjs";
|
|
6
6
|
import { findConfigPath, isAppDescriptorPath, resolveUiRuntimeName } from "./config.mjs";
|
|
7
|
+
import { run } from "./utils/run.mjs";
|
|
7
8
|
import { colors, icons } from "./utils/theme.mjs";
|
|
8
9
|
import { openResolution } from "./resolution/session.mjs";
|
|
9
10
|
import { pointerFingerprint, slotPins } from "./fingerprint.mjs";
|
|
@@ -14,15 +15,17 @@ import { buildWorkspaceTargets, resolveWorkspaceTarget, selectWorkspaceTargets }
|
|
|
14
15
|
import { generateCodeArtifacts } from "./code-artifacts.mjs";
|
|
15
16
|
import { readSessionHandle } from "./auth-session.mjs";
|
|
16
17
|
import { probeStorageOrigin, resolveCdnDeployInputs } from "./cdn-deploy.mjs";
|
|
18
|
+
import { ensureCustodyBalance, submitRegistryWriteCustody } from "./custody-signer.mjs";
|
|
17
19
|
import { ensureDelegateKey, submitRegistryWriteDelegated } from "./delegate-signer.mjs";
|
|
18
20
|
import { verifyRollbackSnapshot } from "./rollback.mjs";
|
|
19
21
|
import { diffWorkspaceFiles, localSriMap, mergedFileIntegrity, pinsFromDeployState, pinsFromPublishedConfig, upsertDeployStatePins } from "./deploy-diff.mjs";
|
|
20
22
|
import { describeSigningStrategy, resolveSigningStrategy, submitRegistryWrite } from "./near-signer.mjs";
|
|
21
23
|
import { platformUrlDeployEntries, pluginUiUrlDeployEntries } from "./platform-deploy.mjs";
|
|
24
|
+
import { buildSourceArchive, makeSourceArchiveTempDir } from "./source-archive.mjs";
|
|
22
25
|
import { collectDistFiles, uploadBundle, uploadWorkspaceDist } from "./storage-upload.mjs";
|
|
23
26
|
import { composeWorkspaceVersionManifest, readBuildReport } from "./version-manifest-deploy.mjs";
|
|
24
|
-
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
25
|
-
import { join } from "node:path";
|
|
27
|
+
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
28
|
+
import { basename, dirname, join } from "node:path";
|
|
26
29
|
import process from "node:process";
|
|
27
30
|
import { hasFolderFormUi } from "every-plugin/build/ui";
|
|
28
31
|
|
|
@@ -36,7 +39,9 @@ async function pinWorkspaceVersionManifest(input) {
|
|
|
36
39
|
report: input.report,
|
|
37
40
|
ssrReport: input.ssrReport,
|
|
38
41
|
integrityMap: input.integrityMap,
|
|
39
|
-
...input.files ? { files: input.files } : {}
|
|
42
|
+
...input.files ? { files: input.files } : {},
|
|
43
|
+
...input.source ? { source: input.source } : {},
|
|
44
|
+
...input.gitSha ? { gitSha: input.gitSha } : {}
|
|
40
45
|
});
|
|
41
46
|
if (!versionManifest) return void 0;
|
|
42
47
|
const manifestFile = `versions/${versionManifest.version}.json`;
|
|
@@ -61,6 +66,77 @@ async function pinWorkspaceVersionManifest(input) {
|
|
|
61
66
|
};
|
|
62
67
|
}
|
|
63
68
|
/**
|
|
69
|
+
* Best-effort repo HEAD for the version manifest (`gitSha`): non-git
|
|
70
|
+
* contexts (child bundles built outside a repo) omit the field silently —
|
|
71
|
+
* it never fails the deploy.
|
|
72
|
+
*/
|
|
73
|
+
async function resolveGitSha(cwd) {
|
|
74
|
+
try {
|
|
75
|
+
const result = await run("git", ["rev-parse", "HEAD"], {
|
|
76
|
+
cwd,
|
|
77
|
+
capture: true
|
|
78
|
+
});
|
|
79
|
+
const sha = result?.stdout.trim();
|
|
80
|
+
return result && result.exitCode === 0 && sha ? sha : void 0;
|
|
81
|
+
} catch {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The source-archive leg (publish.sourcePublish, #406): tar the workspace
|
|
87
|
+
* subtree, dedupe against the previous pin's manifest by archive SRI (reuse
|
|
88
|
+
* skips the upload), otherwise upload and take the **server-computed** SRI
|
|
89
|
+
* (MAP decision 6). The temp archive dir is cleaned up on every path — the
|
|
90
|
+
* manifest only carries `{ file, integrity }`, not the bytes.
|
|
91
|
+
*/
|
|
92
|
+
async function resolveSourceReference(input) {
|
|
93
|
+
const outDir = makeSourceArchiveTempDir();
|
|
94
|
+
try {
|
|
95
|
+
const archive = await buildSourceArchive({
|
|
96
|
+
repoRoot: input.repoRoot,
|
|
97
|
+
workspace: input.workspaceDir,
|
|
98
|
+
outDir
|
|
99
|
+
});
|
|
100
|
+
if (input.previousPin) try {
|
|
101
|
+
const resolved = await resolveSlotVersion({
|
|
102
|
+
base: input.base,
|
|
103
|
+
pin: input.previousPin
|
|
104
|
+
});
|
|
105
|
+
if (resolved.source?.integrity === archive.integrity) {
|
|
106
|
+
console.log(` ${colors.dim(`${padRight(input.workspace, 28)} source unchanged — reusing ${archive.file}`)}`);
|
|
107
|
+
return { source: {
|
|
108
|
+
file: resolved.source.file,
|
|
109
|
+
integrity: resolved.source.integrity
|
|
110
|
+
} };
|
|
111
|
+
}
|
|
112
|
+
} catch {}
|
|
113
|
+
const upload = await uploadBundle({
|
|
114
|
+
origin: input.origin,
|
|
115
|
+
apiKey: input.apiKey,
|
|
116
|
+
account: input.account,
|
|
117
|
+
gateway: input.gateway,
|
|
118
|
+
workspace: input.workspace,
|
|
119
|
+
files: [{
|
|
120
|
+
path: archive.file,
|
|
121
|
+
bytes: new Uint8Array(readFileSync(archive.path))
|
|
122
|
+
}]
|
|
123
|
+
});
|
|
124
|
+
if (upload.storage === "memory") return { memory: true };
|
|
125
|
+
const integrity = upload.integrity[archive.file];
|
|
126
|
+
if (!integrity) throw new Error(`[publish] source archive upload for ${input.workspace}: missing server SRI for ${archive.file}`);
|
|
127
|
+
console.log(` ${colors.dim(`${padRight(input.workspace, 28)} source archive ${archive.file}`)}`);
|
|
128
|
+
return { source: {
|
|
129
|
+
file: archive.file,
|
|
130
|
+
integrity
|
|
131
|
+
} };
|
|
132
|
+
} finally {
|
|
133
|
+
rmSync(outDir, {
|
|
134
|
+
recursive: true,
|
|
135
|
+
force: true
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
64
140
|
* One workspace's upload leg with skip-unchanged diffing: resolve the previous
|
|
65
141
|
* manifest's `files` map, hash the local dist, upload only new/changed files,
|
|
66
142
|
* and return the merged per-file SRI map for the version manifest. Any failure
|
|
@@ -204,8 +280,12 @@ async function preflightPublish(input) {
|
|
|
204
280
|
if (!session?.credential) return fail((input.wallet ? "--wallet requires" : "the authored config sets publish.auth = \"session\", but") + " no CLI session is stored in .bos/ for this project. Run bos login to create one.");
|
|
205
281
|
if (session.credential.accountId && session.credential.accountId !== account) return fail(`The CLI session was created for ${session.credential.accountId}, but the configured account is ${account}. Gasless wallet publish relays the FastKV write under the session's NEAR account. Run bos login again under the matching account.`);
|
|
206
282
|
}
|
|
207
|
-
|
|
208
|
-
|
|
283
|
+
const useCustody = publishAuth === "custody" && !input.privateKey && !input.wallet;
|
|
284
|
+
if (useCustody) {
|
|
285
|
+
const custodyWallet = readSessionHandle(configDir)?.custodyWallet;
|
|
286
|
+
if (!custodyWallet) return fail("the authored config sets publish.auth = \"custody\", but no custody wallet is stored in .bos/. Run `bos login --custody` first.");
|
|
287
|
+
if (custodyWallet.network !== network) return fail(`The custody wallet was registered on ${custodyWallet.network}, but this project publishes on ${network}. Run \`bos login --custody\` from a ${network} account.`);
|
|
288
|
+
if (custodyWallet.nearAccountId !== account) return fail(`publish.auth = "custody" publishes under the custody wallet's account, but the configured account is ${account} and the custody wallet account is ${custodyWallet.nearAccountId}. Set the authored config's account to the custody wallet account.`);
|
|
209
289
|
}
|
|
210
290
|
if (input.dryRun) return {
|
|
211
291
|
kind: "dry-run",
|
|
@@ -237,6 +317,7 @@ async function preflightPublish(input) {
|
|
|
237
317
|
env: process.env,
|
|
238
318
|
bosConfig,
|
|
239
319
|
session: session?.credential ?? null,
|
|
320
|
+
custodyAccount: useCustody ? session?.custodyWallet?.nearAccountId : void 0,
|
|
240
321
|
account,
|
|
241
322
|
gateway,
|
|
242
323
|
uploadsPlanned: input.build
|
|
@@ -270,6 +351,7 @@ async function preflightPublish(input) {
|
|
|
270
351
|
registryNamespace: getRegistryNamespaceForNetwork(network, input.registry),
|
|
271
352
|
targets: selectWorkspaceTargets(input.packages, bosConfig),
|
|
272
353
|
useWallet,
|
|
354
|
+
useCustody,
|
|
273
355
|
strategy,
|
|
274
356
|
cdnOrigin: cdnDeploy.cdnOrigin,
|
|
275
357
|
storageOrigin: cdnDeploy.storageOrigin,
|
|
@@ -299,7 +381,7 @@ async function publishToFastKv(input) {
|
|
|
299
381
|
registryUrl: preflight.registryUrl
|
|
300
382
|
};
|
|
301
383
|
const plan = preflight.plan;
|
|
302
|
-
const { isStaging, account, gateway, network, registryUrl, registryNamespace, targets, useWallet, strategy } = plan;
|
|
384
|
+
const { isStaging, account, gateway, network, registryUrl, registryNamespace, targets, useWallet, useCustody, strategy } = plan;
|
|
303
385
|
const storageOrigin = plan.storageOrigin;
|
|
304
386
|
const storageApiKey = plan.storageApiKey;
|
|
305
387
|
const { configDir } = input;
|
|
@@ -397,6 +479,16 @@ async function publishToFastKv(input) {
|
|
|
397
479
|
};
|
|
398
480
|
console.log();
|
|
399
481
|
console.log(` CDN deploy — uploading workspace dists to ${storageOrigin}...`);
|
|
482
|
+
const sourcePublish = bosConfig.publish?.sourcePublish === true;
|
|
483
|
+
const gitSha = await resolveGitSha(configDir);
|
|
484
|
+
const memoryBackendAbort = () => ({
|
|
485
|
+
status: "error",
|
|
486
|
+
registryUrl,
|
|
487
|
+
built,
|
|
488
|
+
skipped,
|
|
489
|
+
deployResults,
|
|
490
|
+
error: "The receiving instance is serving bundle storage from memory (BOS_STORAGE_* R2 credentials are not configured there) — uploaded bytes would be lost on restart. Aborting before publish."
|
|
491
|
+
});
|
|
400
492
|
for (const key of deployTargets) {
|
|
401
493
|
const ws = resolveWorkspaceTarget(key, bosConfig, runtimeConfig, configDir);
|
|
402
494
|
if (!ws) continue;
|
|
@@ -429,6 +521,34 @@ async function publishToFastKv(input) {
|
|
|
429
521
|
const ssrReport = readBuildReport(join(ws.path, "dist", "ssr"));
|
|
430
522
|
const integrity = report ? outcome.fileIntegrity[report.entry] : void 0;
|
|
431
523
|
const ssrIntegrity = ssrReport?.entry ? outcome.fileIntegrity[`ssr/${ssrReport.entry}`] : void 0;
|
|
524
|
+
let sourceRef;
|
|
525
|
+
if (sourcePublish) {
|
|
526
|
+
if (outcome.result.storage === "memory") return memoryBackendAbort();
|
|
527
|
+
try {
|
|
528
|
+
const sourceOutcome = await resolveSourceReference({
|
|
529
|
+
origin: storageOrigin,
|
|
530
|
+
apiKey: storageApiKey,
|
|
531
|
+
account,
|
|
532
|
+
gateway,
|
|
533
|
+
workspace: key,
|
|
534
|
+
base: workspaceBase,
|
|
535
|
+
previousPin: prevPins[key],
|
|
536
|
+
repoRoot: dirname(ws.path),
|
|
537
|
+
workspaceDir: basename(ws.path)
|
|
538
|
+
});
|
|
539
|
+
if ("memory" in sourceOutcome) return memoryBackendAbort();
|
|
540
|
+
sourceRef = sourceOutcome.source;
|
|
541
|
+
} catch (error) {
|
|
542
|
+
return {
|
|
543
|
+
status: "error",
|
|
544
|
+
registryUrl,
|
|
545
|
+
built,
|
|
546
|
+
skipped,
|
|
547
|
+
deployResults,
|
|
548
|
+
error: error instanceof Error ? error.message : `[publish] source archive for ${key} failed`
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
}
|
|
432
552
|
const manifestPointer = await pinWorkspaceVersionManifest({
|
|
433
553
|
origin: storageOrigin,
|
|
434
554
|
apiKey: storageApiKey,
|
|
@@ -438,7 +558,9 @@ async function publishToFastKv(input) {
|
|
|
438
558
|
report,
|
|
439
559
|
ssrReport,
|
|
440
560
|
integrityMap: outcome.fileIntegrity,
|
|
441
|
-
files: outcome.fileIntegrity
|
|
561
|
+
files: outcome.fileIntegrity,
|
|
562
|
+
...sourceRef ? { source: sourceRef } : {},
|
|
563
|
+
...gitSha ? { gitSha } : {}
|
|
442
564
|
});
|
|
443
565
|
if (!manifestPointer) return {
|
|
444
566
|
status: "error",
|
|
@@ -448,14 +570,7 @@ async function publishToFastKv(input) {
|
|
|
448
570
|
deployResults,
|
|
449
571
|
error: `bundle upload for ${key}: version manifest missing — the dist predates hashed entry names (rebuild required; atomic-deploys hard break)`
|
|
450
572
|
};
|
|
451
|
-
if (outcome.result.storage === "memory" || manifestPointer.storage === "memory") return
|
|
452
|
-
status: "error",
|
|
453
|
-
registryUrl,
|
|
454
|
-
built,
|
|
455
|
-
skipped,
|
|
456
|
-
deployResults,
|
|
457
|
-
error: "The receiving instance is serving bundle storage from memory (BOS_STORAGE_* R2 credentials are not configured there) — uploaded bytes would be lost on restart. Aborting before publish."
|
|
458
|
-
};
|
|
573
|
+
if (outcome.result.storage === "memory" || manifestPointer.storage === "memory") return memoryBackendAbort();
|
|
459
574
|
console.log(` ${colors.green(icons.ok)} ${padRight(key, 28)} → ${urlOrigin}/bundles/${account}/${gateway}/${key}/ (${outcome.uploaded} uploaded, ${outcome.skipped} skipped, ${formatDuration(Date.now() - startedAt)})`);
|
|
460
575
|
platformEntries.push(...platformUrlDeployEntries({
|
|
461
576
|
origin: urlOrigin,
|
|
@@ -510,14 +625,7 @@ async function publishToFastKv(input) {
|
|
|
510
625
|
deployResults,
|
|
511
626
|
error: `bundle upload for ${key}-ui: version manifest missing — the dist predates hashed entry names (rebuild required; atomic-deploys hard break)`
|
|
512
627
|
};
|
|
513
|
-
if (uiOutcome.result.storage === "memory" || uiManifestPointer.storage === "memory") return
|
|
514
|
-
status: "error",
|
|
515
|
-
registryUrl,
|
|
516
|
-
built,
|
|
517
|
-
skipped,
|
|
518
|
-
deployResults,
|
|
519
|
-
error: "The receiving instance is serving bundle storage from memory (BOS_STORAGE_* R2 credentials are not configured there) — uploaded bytes would be lost on restart. Aborting before publish."
|
|
520
|
-
};
|
|
628
|
+
if (uiOutcome.result.storage === "memory" || uiManifestPointer.storage === "memory") return memoryBackendAbort();
|
|
521
629
|
console.log(` ${colors.green(icons.ok)} ${padRight(`${key}-ui`, 28)} → ${urlOrigin}/bundles/${account}/${gateway}/${key}-ui/ (${uiOutcome.uploaded} uploaded, ${uiOutcome.skipped} skipped, ${formatDuration(Date.now() - uiStartedAt)})`);
|
|
522
630
|
} else console.log(` ${colors.green(icons.ok)} ${padRight(`${key}-ui`, 28)} → ${urlOrigin}/bundles/${account}/${gateway}/${key}-ui/`);
|
|
523
631
|
platformEntries.push(...pluginUiUrlDeployEntries({
|
|
@@ -616,7 +724,22 @@ async function publishToFastKv(input) {
|
|
|
616
724
|
}
|
|
617
725
|
console.log(` Submitting transaction on ${network}...`);
|
|
618
726
|
let result;
|
|
619
|
-
if (
|
|
727
|
+
if (useCustody) {
|
|
728
|
+
const custodyWallet = readSessionHandle(configDir)?.custodyWallet;
|
|
729
|
+
if (!custodyWallet) return {
|
|
730
|
+
status: "error",
|
|
731
|
+
registryUrl,
|
|
732
|
+
error: "the authored config sets publish.auth = \"custody\", but no custody wallet is stored in .bos/. Run `bos login --custody` first."
|
|
733
|
+
};
|
|
734
|
+
await ensureCustodyBalance(custodyWallet);
|
|
735
|
+
console.log(` Signing via ${colors.cyan(`OutLayer custody wallet ${custodyWallet.nearAccountId}`)}`);
|
|
736
|
+
result = await submitRegistryWriteCustody({
|
|
737
|
+
contract: registryNamespace,
|
|
738
|
+
args: registryEntries,
|
|
739
|
+
custodyWallet,
|
|
740
|
+
idempotencyKey: `bos-publish-${fingerprint}`
|
|
741
|
+
});
|
|
742
|
+
} else if (useWallet) {
|
|
620
743
|
const credential = readSessionHandle(configDir)?.credential;
|
|
621
744
|
if (!credential || credential.accountId !== account) return {
|
|
622
745
|
status: "error",
|