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.
Files changed (115) hide show
  1. package/dist/apps/upload/src/client.cjs +7 -1
  2. package/dist/apps/upload/src/client.cjs.map +1 -1
  3. package/dist/apps/upload/src/client.mjs +7 -1
  4. package/dist/apps/upload/src/client.mjs.map +1 -1
  5. package/dist/auth-login.cjs +24 -1
  6. package/dist/auth-login.cjs.map +1 -1
  7. package/dist/auth-login.mjs +24 -1
  8. package/dist/auth-login.mjs.map +1 -1
  9. package/dist/auth-session.cjs +4 -2
  10. package/dist/auth-session.cjs.map +1 -1
  11. package/dist/auth-session.mjs +4 -2
  12. package/dist/auth-session.mjs.map +1 -1
  13. package/dist/cdn-deploy.cjs +11 -7
  14. package/dist/cdn-deploy.cjs.map +1 -1
  15. package/dist/cdn-deploy.mjs +11 -7
  16. package/dist/cdn-deploy.mjs.map +1 -1
  17. package/dist/cli/import.cjs +1140 -0
  18. package/dist/cli/import.cjs.map +1 -0
  19. package/dist/cli/import.mjs +1126 -0
  20. package/dist/cli/import.mjs.map +1 -0
  21. package/dist/cli/init.cjs +11 -4
  22. package/dist/cli/init.cjs.map +1 -1
  23. package/dist/cli/init.d.cts +8 -2
  24. package/dist/cli/init.d.mts +8 -2
  25. package/dist/cli/init.mjs +11 -5
  26. package/dist/cli/init.mjs.map +1 -1
  27. package/dist/cli.cjs +55 -0
  28. package/dist/cli.cjs.map +1 -1
  29. package/dist/cli.mjs +55 -0
  30. package/dist/cli.mjs.map +1 -1
  31. package/dist/commands/import.cjs +49 -0
  32. package/dist/commands/import.cjs.map +1 -0
  33. package/dist/commands/import.mjs +46 -0
  34. package/dist/commands/import.mjs.map +1 -0
  35. package/dist/commands/keys.cjs +24 -3
  36. package/dist/commands/keys.cjs.map +1 -1
  37. package/dist/commands/keys.mjs +24 -3
  38. package/dist/commands/keys.mjs.map +1 -1
  39. package/dist/config.d.cts +1 -0
  40. package/dist/config.d.mts +1 -0
  41. package/dist/contract.cjs +89 -0
  42. package/dist/contract.cjs.map +1 -1
  43. package/dist/contract.d.cts +190 -1
  44. package/dist/contract.d.mts +190 -1
  45. package/dist/contract.meta.cjs +16 -0
  46. package/dist/contract.meta.cjs.map +1 -1
  47. package/dist/contract.meta.d.cts +26 -0
  48. package/dist/contract.meta.d.mts +26 -0
  49. package/dist/contract.meta.mjs +16 -0
  50. package/dist/contract.meta.mjs.map +1 -1
  51. package/dist/contract.mjs +84 -1
  52. package/dist/contract.mjs.map +1 -1
  53. package/dist/custody-signer.cjs +70 -0
  54. package/dist/custody-signer.cjs.map +1 -0
  55. package/dist/custody-signer.mjs +68 -0
  56. package/dist/custody-signer.mjs.map +1 -0
  57. package/dist/descriptor/schema.cjs +8 -5
  58. package/dist/descriptor/schema.cjs.map +1 -1
  59. package/dist/descriptor/schema.d.cts +1 -0
  60. package/dist/descriptor/schema.d.mts +1 -0
  61. package/dist/descriptor/schema.mjs +8 -5
  62. package/dist/descriptor/schema.mjs.map +1 -1
  63. package/dist/descriptor/serialize.cjs +1 -1
  64. package/dist/descriptor/serialize.cjs.map +1 -1
  65. package/dist/descriptor/serialize.mjs +1 -1
  66. package/dist/descriptor/serialize.mjs.map +1 -1
  67. package/dist/index.cjs +6 -0
  68. package/dist/index.d.cts +2 -2
  69. package/dist/index.d.mts +2 -2
  70. package/dist/index.mjs +2 -2
  71. package/dist/outlayer-login.cjs +54 -0
  72. package/dist/outlayer-login.cjs.map +1 -0
  73. package/dist/outlayer-login.mjs +54 -0
  74. package/dist/outlayer-login.mjs.map +1 -0
  75. package/dist/plugin.cjs +2 -0
  76. package/dist/plugin.cjs.map +1 -1
  77. package/dist/plugin.d.cts +74 -0
  78. package/dist/plugin.d.mts +74 -0
  79. package/dist/plugin.mjs +2 -0
  80. package/dist/plugin.mjs.map +1 -1
  81. package/dist/publish.cjs +145 -22
  82. package/dist/publish.cjs.map +1 -1
  83. package/dist/publish.mjs +147 -24
  84. package/dist/publish.mjs.map +1 -1
  85. package/dist/source-archive.cjs +51 -0
  86. package/dist/source-archive.cjs.map +1 -0
  87. package/dist/source-archive.mjs +50 -0
  88. package/dist/source-archive.mjs.map +1 -0
  89. package/dist/storage-upload.cjs +6 -1
  90. package/dist/storage-upload.cjs.map +1 -1
  91. package/dist/storage-upload.mjs +6 -1
  92. package/dist/storage-upload.mjs.map +1 -1
  93. package/dist/types.cjs +5 -1
  94. package/dist/types.cjs.map +1 -1
  95. package/dist/types.d.cts +2 -0
  96. package/dist/types.d.mts +2 -0
  97. package/dist/types.mjs +5 -1
  98. package/dist/types.mjs.map +1 -1
  99. package/dist/utils/workspace-subtree.cjs +37 -0
  100. package/dist/utils/workspace-subtree.cjs.map +1 -0
  101. package/dist/utils/workspace-subtree.mjs +36 -0
  102. package/dist/utils/workspace-subtree.mjs.map +1 -0
  103. package/dist/version-manifest-deploy.cjs +4 -2
  104. package/dist/version-manifest-deploy.cjs.map +1 -1
  105. package/dist/version-manifest-deploy.mjs +4 -2
  106. package/dist/version-manifest-deploy.mjs.map +1 -1
  107. package/dist/version-manifest-resolve.cjs +2 -1
  108. package/dist/version-manifest-resolve.cjs.map +1 -1
  109. package/dist/version-manifest-resolve.d.cts +3 -0
  110. package/dist/version-manifest-resolve.d.mts +3 -0
  111. package/dist/version-manifest-resolve.mjs +2 -1
  112. package/dist/version-manifest-resolve.mjs.map +1 -1
  113. package/package.json +3 -2
  114. package/skills/cli-reference/SKILL.md +17 -1
  115. package/skills/init-upgrade/SKILL.md +76 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"import.cjs","names":["existsSync","statSync","parseGitHubUrl","parseBosUrl","resolve","isAbsolute","join","readFileSync","lstatSync","computeSnapshotHash","relative","dirname","fetchResponse","WorkspaceVersionManifestSchema","computeSriHash","localConfigEntryPath","walkExtendsChain","resolveExtendsRef","mkdtempSync","tmpdir","tarExtract","downloadTarball","listWorkspaceSubtreeFiles","readSnapshot","mergePackageJson","writeSnapshot","runPnpmInstall","findWorkspaceRoot","runTypesGen"],"sources":["../../src/cli/import.ts"],"sourcesContent":["import {\n copyFileSync,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport { type SourceRef, WorkspaceVersionManifestSchema } from \"every-plugin/version-manifest\";\nimport { glob } from \"glob\";\nimport { extract as tarExtract } from \"tar\";\nimport { localConfigEntryPath } from \"../config\";\nimport type {\n ImportMigrationCollision,\n ImportOptions,\n ImportResult,\n ImportRouteDelta,\n} from \"../contract\";\nimport { parseBosUrl } from \"../fastkv\";\nimport { fetchResponse } from \"../http-client\";\nimport { computeSriHash } from \"../integrity\";\nimport { resolveExtendsRef } from \"../merge\";\nimport type { ResolutionIo } from \"../resolution/session\";\nimport { type WalkLink, walkExtendsChain } from \"../resolution/session\";\nimport type { ExtendsConfig } from \"../types\";\nimport { computeSnapshotHash } from \"../utils/snapshot-hash\";\nimport { listWorkspaceSubtreeFiles } from \"../utils/workspace-subtree\";\nimport { findWorkspaceRoot } from \"../workspace\";\nimport { downloadTarball, parseGitHubUrl, runPnpmInstall, runTypesGen } from \"./init\";\nimport { readSnapshot, writeSnapshot } from \"./snapshot\";\nimport { mergePackageJson } from \"./sync\";\n\nconst IMPORT_SNAPSHOT_FILE = \"import-snapshot.json\";\nconst IMPORT_REPORT_FILE = \"import-report.md\";\n\nexport const IMPORT_REPORT_PATH = `.bos/${IMPORT_REPORT_FILE}`;\n\nexport type ImportFromSpec =\n | { kind: \"github\"; repo: string; ref?: string }\n | { kind: \"archive\"; url: string; integrity: string }\n | { kind: \"bos\"; bosUrl: string; account: string; gateway: string }\n | { kind: \"local\"; dir: string };\n\nexport interface ImportChainProvenance {\n /** the ref the chain was walked from: the bos:// source or the child's resolved extends */\n extendsRef: string;\n /** the runtime whose own config declares the workspace */\n ancestorRef: string;\n /** git ref pinned from the ancestor's published version manifest, when present */\n pinnedSha?: string;\n /** GitHub coordinate resolved rootward, when the chain publishes one */\n repository?: string;\n /** source archive coordinate from the ancestor's version manifest, when published */\n sourceArchive?: { file: string; url: string; integrity: string };\n warnings: string[];\n}\n\nexport type ImportFileClass =\n | { kind: \"added\" }\n | { kind: \"unchanged\" }\n | { kind: \"updated\" }\n | { kind: \"preserved-local\" }\n | { kind: \"preserved-local-edit\" }\n | { kind: \"merged\" }\n | { kind: \"conflict\"; reason: \"no-baseline\" | \"both-changed\" };\n\nexport interface MigrationEntry {\n idx: number;\n tag: string;\n sha: string | null;\n}\n\nexport interface ImportReportAnalysis {\n workspace: string;\n from: string;\n ref: string;\n resolvedSha?: string;\n sourceKind: \"github\" | \"local\" | \"archive\";\n chain?: ImportChainProvenance;\n added: string[];\n updated: string[];\n unchanged: string[];\n preservedLocal: string[];\n preservedLocalEdit: string[];\n merged: string[];\n conflicts: Array<{ path: string; reason: \"no-baseline\" | \"both-changed\"; held: boolean }>;\n routeDelta?: ImportRouteDelta;\n migrationCollisions: ImportMigrationCollision[];\n migrationReconciliation: MigrationReconciliation | null;\n heldBackMigrations: string[];\n}\n\nexport interface ImportDeps {\n confirm?: (info: {\n workspace: string;\n conflictCount: number;\n migrationCollisionCount: number;\n heldCount: number;\n appendedCount: number;\n }) => Promise<boolean>;\n}\n\nfunction isExistingDir(path: string): boolean {\n try {\n return existsSync(path) && statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction normalizeGithubRepo(spec: string): string | null {\n if (parseGitHubUrl(spec)) {\n return spec;\n }\n const match = spec.match(/^([A-Za-z0-9_.-]+)\\/([A-Za-z0-9_.-]+?)(?:\\.git)?\\/?$/);\n if (!match?.[1] || !match[2]) return null;\n if (match[1] === \".\" || match[1] === \"..\" || match[2] === \".\" || match[2] === \"..\") return null;\n return `https://github.com/${match[1]}/${match[2]}`;\n}\n\nexport function parseFromSpec(spec: string): ImportFromSpec {\n const trimmed = spec.trim();\n if (!trimmed) {\n throw new Error(\n \"--from is required: bos://<account>/<gateway>, <owner>/<repo>[@<ref>], a GitHub URL, or a local directory\",\n );\n }\n\n if (trimmed.startsWith(\"bos://\")) {\n const hashIndex = trimmed.indexOf(\"#\");\n const bosPart = hashIndex === -1 ? trimmed : trimmed.slice(0, hashIndex);\n const target = hashIndex === -1 ? undefined : trimmed.slice(hashIndex + 1).trim();\n if (target) {\n throw new Error(\n `Targeted extends refs are not supported for import sources: ${spec}. Omit the #target and pass the workspace as the positional argument.`,\n );\n }\n const parsed = parseBosUrl(bosPart);\n if (parsed.pathSegments.length > 0) {\n throw new Error(`Unsupported bos:// path — expected bos://<account>/<gateway>: ${spec}`);\n }\n return {\n kind: \"bos\",\n bosUrl: `bos://${parsed.accountId}/${parsed.gatewayId}`,\n account: parsed.accountId,\n gateway: parsed.gatewayId,\n };\n }\n\n if (trimmed.startsWith(\"/\") || trimmed.startsWith(\"./\") || trimmed.startsWith(\"../\")) {\n if (!isExistingDir(trimmed)) {\n throw new Error(`Local directory not found: ${trimmed}`);\n }\n return { kind: \"local\", dir: resolve(trimmed) };\n }\n\n const at = trimmed.indexOf(\"@\");\n if (at > 0) {\n const head = trimmed.slice(0, at);\n const ref = trimmed.slice(at + 1);\n const repo = normalizeGithubRepo(head);\n if (repo && ref) {\n return { kind: \"github\", repo, ref };\n }\n }\n\n const repo = normalizeGithubRepo(trimmed);\n if (repo) {\n return { kind: \"github\", repo };\n }\n\n if (isExistingDir(trimmed)) {\n return { kind: \"local\", dir: resolve(trimmed) };\n }\n\n throw new Error(\n `Cannot parse --from source: ${spec}. Expected bos://<account>/<gateway>, <owner>/<repo>[@<ref>], a GitHub URL, or a local directory.`,\n );\n}\n\nexport function normalizeWorkspacePath(input: string): string {\n const trimmed = input.trim().replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").replace(/\\/+$/, \"\");\n if (isAbsolute(input)) {\n throw new Error(`Workspace path must be repo-relative: ${input}`);\n }\n if (!trimmed || trimmed === \".\" || trimmed === \"..\") {\n throw new Error(`Invalid workspace path: ${input}`);\n }\n const segments = trimmed.split(\"/\");\n if (segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\")) {\n throw new Error(`Invalid workspace path: ${input}`);\n }\n return trimmed;\n}\n\nexport function classifyImportFile(input: {\n localHash: string | null;\n upstreamHash: string;\n baselineHash: string | undefined;\n mergeable: boolean;\n}): ImportFileClass {\n const { localHash, upstreamHash, baselineHash, mergeable } = input;\n if (localHash === null) {\n return { kind: \"added\" };\n }\n if (localHash === upstreamHash) {\n return { kind: \"unchanged\" };\n }\n if (baselineHash === undefined) {\n return mergeable ? { kind: \"merged\" } : { kind: \"conflict\", reason: \"no-baseline\" };\n }\n if (localHash === baselineHash) {\n return mergeable ? { kind: \"merged\" } : { kind: \"updated\" };\n }\n if (upstreamHash === baselineHash) {\n return { kind: \"preserved-local-edit\" };\n }\n return mergeable ? { kind: \"merged\" } : { kind: \"conflict\", reason: \"both-changed\" };\n}\n\nexport function extractContractRoutes(source: string): string[] {\n const routes = new Set<string>();\n const marker = \".route(\";\n let cursor = source.indexOf(marker);\n while (cursor !== -1) {\n const open = cursor + marker.length - 1;\n let depth = 0;\n let end = open;\n for (; end < source.length; end++) {\n const char = source[end];\n if (char === \"(\") {\n depth++;\n } else if (char === \")\") {\n depth--;\n if (depth === 0) break;\n }\n }\n const arg = source.slice(open + 1, end);\n const method = arg.match(/\\bmethod:\\s*[\"']([A-Za-z]+)[\"']/)?.[1];\n const path = arg.match(/\\bpath:\\s*[\"']([^\"']+)[\"']/)?.[1];\n if (method && path) {\n routes.add(`${method} ${path}`);\n }\n cursor = source.indexOf(marker, cursor + 1);\n }\n return [...routes].sort();\n}\n\nexport function computeRouteDelta(ours: string[], theirs: string[]): ImportRouteDelta {\n const oursSet = new Set(ours);\n const theirsSet = new Set(theirs);\n return {\n oursOnly: ours.filter((route) => !theirsSet.has(route)),\n theirsOnly: theirs.filter((route) => !oursSet.has(route)),\n };\n}\n\nasync function collectContractRouteSources(\n root: string,\n workspace: string,\n): Promise<string[] | null> {\n const sources: string[] = [];\n const mainPath = join(root, workspace, \"src\", \"contract.ts\");\n if (existsSync(mainPath)) {\n sources.push(readFileSync(mainPath, \"utf-8\"));\n }\n const splitDir = join(root, workspace, \"src\", \"contract\");\n if (existsSync(splitDir) && lstatSync(splitDir).isDirectory()) {\n const matches = await glob(\"**/*.{ts,tsx}\", {\n cwd: splitDir,\n nodir: true,\n absolute: false,\n });\n for (const match of matches.sort()) {\n sources.push(readFileSync(join(splitDir, match), \"utf-8\"));\n }\n }\n return sources.length > 0 ? sources : null;\n}\n\nfunction extractWorkspaceRoutes(sources: string[] | null): string[] | null {\n if (sources === null) {\n return null;\n }\n const routes = new Set<string>();\n for (const source of sources) {\n for (const route of extractContractRoutes(source)) {\n routes.add(route);\n }\n }\n return [...routes].sort();\n}\n\nexport function loadMigrationEntries(root: string, workspace: string): MigrationEntry[] | null {\n const journalPath = journalPathFor(root, workspace);\n if (!existsSync(journalPath)) {\n return null;\n }\n let journal: unknown;\n try {\n journal = JSON.parse(readFileSync(journalPath, \"utf-8\"));\n } catch {\n return null;\n }\n const entries = (journal as { entries?: unknown }).entries;\n if (!Array.isArray(entries)) {\n return null;\n }\n const migrationsDir = join(root, workspace, \"src\", \"db\", \"migrations\");\n const result: MigrationEntry[] = [];\n for (const raw of entries) {\n const entry = raw as { idx?: unknown; tag?: unknown };\n if (typeof entry.idx !== \"number\" || typeof entry.tag !== \"string\") {\n continue;\n }\n const sqlPath = join(migrationsDir, `${entry.tag}.sql`);\n let sha: string | null = null;\n if (existsSync(sqlPath)) {\n try {\n sha = computeSnapshotHash(readFileSync(sqlPath));\n } catch {\n sha = null;\n }\n }\n result.push({ idx: entry.idx, tag: entry.tag, sha });\n }\n return result.sort((a, b) => a.idx - b.idx);\n}\n\ninterface RawMigrationJournal {\n journal: Record<string, unknown>;\n entries: Record<string, unknown>[];\n}\n\nfunction journalPathFor(root: string, workspace: string): string {\n return join(root, workspace, \"src\", \"db\", \"migrations\", \"meta\", \"_journal.json\");\n}\n\nfunction loadRawJournal(root: string, workspace: string): RawMigrationJournal | null {\n const journalPath = journalPathFor(root, workspace);\n if (!existsSync(journalPath)) {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(journalPath, \"utf-8\"));\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return null;\n }\n const entries = (parsed as { entries?: unknown }).entries;\n if (!Array.isArray(entries)) {\n return null;\n }\n return {\n journal: parsed as Record<string, unknown>,\n entries: entries as Record<string, unknown>[],\n };\n}\n\nfunction buildMergedJournal(\n localRoot: string,\n upstreamRoot: string,\n workspace: string,\n appended: MigrationAppend[],\n): string | null {\n const localRaw = loadRawJournal(localRoot, workspace);\n const upstreamRaw = loadRawJournal(upstreamRoot, workspace);\n if (!localRaw || !upstreamRaw) {\n return null;\n }\n const upstreamEntryByTag = new Map<string, Record<string, unknown>>();\n for (const entry of upstreamRaw.entries) {\n if (typeof entry.tag === \"string\") {\n upstreamEntryByTag.set(entry.tag, entry);\n }\n }\n const maxLocalWhen = localRaw.entries.reduce(\n (max, entry) => Math.max(max, typeof entry.when === \"number\" ? entry.when : 0),\n 0,\n );\n let appendedWhen = maxLocalWhen;\n const appendedEntries = appended.map((append) => {\n const raw = upstreamEntryByTag.get(append.fromTag);\n const when =\n typeof raw?.when === \"number\" && raw.when > appendedWhen ? raw.when : ++appendedWhen;\n return { ...(raw ?? {}), idx: append.idx, tag: append.toTag, when };\n });\n const merged = { ...localRaw.journal, entries: [...localRaw.entries, ...appendedEntries] };\n return `${JSON.stringify(merged, null, 2)}\\n`;\n}\n\nexport interface MigrationAppend {\n idx: number;\n fromTag: string;\n toTag: string;\n}\n\nexport interface MigrationReconciliation {\n kept: string[];\n appended: MigrationAppend[];\n contentMatched: string[];\n unresolvable: ImportMigrationCollision[];\n}\n\nconst MIGRATION_TAG_PATTERN = /^(\\d+)_(.+)$/;\n\nfunction migrationTagFor(idx: number, fromTag: string): string {\n const suffix = fromTag.match(MIGRATION_TAG_PATTERN)?.[2];\n return suffix ? `${String(idx).padStart(4, \"0\")}_${suffix}` : fromTag;\n}\n\nfunction snapshotPrefixOf(tag: string): string | null {\n const match = tag.match(MIGRATION_TAG_PATTERN);\n return match?.[1] ? match[1].padStart(4, \"0\") : null;\n}\n\nexport function reconcileMigrationChains(\n local: MigrationEntry[],\n upstream: MigrationEntry[],\n): MigrationReconciliation {\n const localTags = new Set(local.map((entry) => entry.tag));\n const unresolvable: ImportMigrationCollision[] = [];\n const appended: MigrationAppend[] = [];\n const contentMatched: string[] = [];\n let nextIdx = local.reduce((max, entry) => Math.max(max, entry.idx), -1) + 1;\n for (const upstreamEntry of upstream) {\n if (localTags.has(upstreamEntry.tag)) {\n const localEntry = local.find((candidate) => candidate.tag === upstreamEntry.tag);\n if (localEntry?.sha && upstreamEntry.sha && localEntry.sha !== upstreamEntry.sha) {\n unresolvable.push({\n kind: \"tag-mismatch\",\n idx: upstreamEntry.idx,\n localTag: localEntry.tag,\n upstreamTag: upstreamEntry.tag,\n message: `${upstreamEntry.tag} has different content locally than upstream — already-applied hashes would drift`,\n });\n }\n continue;\n }\n if (upstreamEntry.sha && local.some((candidate) => candidate.sha === upstreamEntry.sha)) {\n contentMatched.push(upstreamEntry.tag);\n continue;\n }\n appended.push({\n idx: nextIdx,\n fromTag: upstreamEntry.tag,\n toTag: migrationTagFor(nextIdx, upstreamEntry.tag),\n });\n nextIdx++;\n }\n return { kept: local.map((entry) => entry.tag), appended, contentMatched, unresolvable };\n}\n\nfunction hashFile(root: string, path: string): string | null {\n const fullPath = join(root, path);\n if (!existsSync(fullPath)) {\n return null;\n }\n try {\n return computeSnapshotHash(readFileSync(fullPath));\n } catch {\n return null;\n }\n}\n\nfunction safeProjectPath(projectDir: string, path: string): string {\n const dest = join(projectDir, path);\n const rel = relative(projectDir, dest);\n if (rel.startsWith(\"..\") || isAbsolute(rel)) {\n throw new Error(`Refusing to write outside the project: ${path}`);\n }\n return dest;\n}\n\nfunction readJson(path: string): Record<string, unknown> | null {\n try {\n const parsed: unknown = JSON.parse(readFileSync(path, \"utf-8\"));\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n return null;\n } catch {\n return null;\n }\n}\n\ninterface ImportSnapshot {\n workspaces: Record<\n string,\n { from: string; ref: string; timestamp: string; files: Record<string, string> }\n >;\n}\n\nfunction readImportSnapshot(projectDir: string): ImportSnapshot {\n const path = join(projectDir, \".bos\", IMPORT_SNAPSHOT_FILE);\n if (!existsSync(path)) {\n return { workspaces: {} };\n }\n try {\n const parsed: unknown = JSON.parse(readFileSync(path, \"utf-8\"));\n const workspaces = (parsed as { workspaces?: unknown }).workspaces;\n if (workspaces && typeof workspaces === \"object\" && !Array.isArray(workspaces)) {\n return { workspaces: workspaces as ImportSnapshot[\"workspaces\"] };\n }\n return { workspaces: {} };\n } catch {\n return { workspaces: {} };\n }\n}\n\nfunction writeImportSnapshot(projectDir: string, snapshot: ImportSnapshot): void {\n const dir = join(projectDir, \".bos\");\n mkdirSync(dir, { recursive: true });\n writeFileSync(join(dir, IMPORT_SNAPSHOT_FILE), `${JSON.stringify(snapshot, null, 2)}\\n`);\n}\n\nfunction writeImportReport(projectDir: string, content: string): string {\n const dir = join(projectDir, \".bos\");\n mkdirSync(dir, { recursive: true });\n writeFileSync(join(dir, IMPORT_REPORT_FILE), content);\n return IMPORT_REPORT_PATH;\n}\n\nfunction backupImportFiles(projectDir: string, paths: string[]): string | undefined {\n const existing = paths.filter((path) => existsSync(join(projectDir, path)));\n if (existing.length === 0) {\n return undefined;\n }\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const backupDir = join(projectDir, \".bos\", \"import-backup\", stamp);\n for (const path of existing) {\n const dest = safeProjectPath(backupDir, path);\n mkdirSync(dirname(dest), { recursive: true });\n copyFileSync(join(projectDir, path), dest);\n }\n return backupDir;\n}\n\nfunction listSection(title: string, items: string[], held?: ReadonlySet<string>): string[] {\n if (items.length === 0) {\n return [`## ${title}`, \"\", \"(none)\", \"\"];\n }\n return [\n `## ${title}`,\n \"\",\n ...items.map((item) => (held?.has(item) ? `- \\`${item}\\` (held)` : `- \\`${item}\\``)),\n \"\",\n ];\n}\n\nexport function buildImportReport(\n analysis: ImportReportAnalysis,\n outcome: { mode: \"dry-run\" | \"applied\" | \"refused\"; backupDir?: string },\n): string {\n const lines: string[] = [];\n lines.push(`# bos import report — \\`${analysis.workspace}\\``);\n lines.push(\"\");\n if (analysis.chain) {\n lines.push(`- **Source:** \\`${analysis.chain.extendsRef}\\` (extends chain)`);\n if (analysis.chain.sourceArchive) {\n lines.push(`- **Source archive:** \\`${analysis.chain.sourceArchive.url}\\``);\n }\n if (analysis.chain.repository) {\n lines.push(\n `- **Upstream:** \\`${analysis.chain.repository}\\` @ \\`${analysis.ref}\\`${analysis.chain.pinnedSha ? ` (pinned git sha \\`${analysis.chain.pinnedSha}\\`)` : \"\"}`,\n );\n }\n for (const warning of analysis.chain.warnings) {\n lines.push(`- **Note:** ${warning}`);\n }\n } else {\n const source =\n analysis.sourceKind === \"local\"\n ? `\\`${analysis.from}\\` (local directory)`\n : `\\`${analysis.from}\\`${analysis.ref ? ` @ \\`${analysis.ref}\\`` : \"\"}`;\n lines.push(`- **Source:** ${source}`);\n }\n if (analysis.resolvedSha) {\n lines.push(`- **Resolved commit:** \\`${analysis.resolvedSha}\\``);\n }\n const modeLabel =\n outcome.mode === \"dry-run\"\n ? \"Dry run — no files written\"\n : outcome.mode === \"applied\"\n ? \"Applied — upstream written over shared files\"\n : \"Refused — unresolvable conflicts exist, nothing was written\";\n lines.push(`- **Mode:** ${modeLabel}`);\n lines.push(`- **Generated:** ${new Date().toISOString()}`);\n lines.push(\"\");\n\n lines.push(\"## Summary\");\n lines.push(\"\");\n lines.push(\"| bucket | count |\");\n lines.push(\"| --- | --- |\");\n lines.push(`| added (upstream-only) | ${analysis.added.length} |`);\n lines.push(`| updated (local unchanged, upstream changed) | ${analysis.updated.length} |`);\n lines.push(`| merged (structured package.json merge) | ${analysis.merged.length} |`);\n lines.push(`| conflicts (unresolvable) | ${analysis.conflicts.length} |`);\n lines.push(`| migration collisions (unresolvable) | ${analysis.migrationCollisions.length} |`);\n lines.push(\n `| migrations appended (renumbered from upstream) | ${analysis.migrationReconciliation?.appended.length ?? 0} |`,\n );\n lines.push(`| migration chain held back | ${analysis.heldBackMigrations.length} |`);\n lines.push(`| local-only (preserved) | ${analysis.preservedLocal.length} |`);\n lines.push(\n `| local edits preserved (upstream unchanged) | ${analysis.preservedLocalEdit.length} |`,\n );\n lines.push(`| unchanged | ${analysis.unchanged.length} |`);\n lines.push(\"\");\n\n if (analysis.conflicts.length > 0) {\n lines.push(\"## Conflicts — manual-port checklist\");\n lines.push(\"\");\n lines.push(\"| file | reason |\");\n lines.push(\"| --- | --- |\");\n for (const conflict of analysis.conflicts) {\n const reason =\n conflict.reason === \"no-baseline\"\n ? \"no import baseline (first import or snapshot gap)\"\n : \"local and upstream both changed since the baseline\";\n lines.push(\n `| \\`${conflict.path}\\` | ${reason}${conflict.held ? \" — held (migration chain)\" : \"\"} |`,\n );\n }\n lines.push(\"\");\n const appliedConflicts = analysis.conflicts.filter((conflict) => !conflict.held);\n if (outcome.mode === \"refused\") {\n lines.push(\n \"Nothing was written. Re-run with `--yes` to apply upstream over these files (local copies are backed up first), then port local-only content back onto the new upstream versions.\",\n );\n } else if (outcome.mode === \"applied\") {\n if (appliedConflicts.length > 0) {\n lines.push(\n `Upstream was applied over ${appliedConflicts.length} of these file(s)${\n outcome.backupDir ? ` — local copies backed up at \\`${outcome.backupDir}\\`` : \"\"\n }. Port local-only content back onto the new upstream versions.`,\n );\n }\n if (analysis.heldBackMigrations.length > 0) {\n lines.push(\n \"Migration-chain conflicts were held back and NOT written — see the held-back section below.\",\n );\n }\n } else {\n lines.push(\n \"A real run with `--yes` would overwrite these with upstream (backing up local copies first); migration-chain files would be held back.\",\n );\n }\n lines.push(\"\");\n }\n\n if (analysis.migrationReconciliation) {\n const reconciliation = analysis.migrationReconciliation;\n lines.push(\"## Migration chain reconciliation\");\n lines.push(\"\");\n lines.push(\"Applied locally — kept verbatim, never renumbered or rehashed:\");\n lines.push(\"\");\n if (reconciliation.kept.length === 0) {\n lines.push(\"(no local journal entries)\");\n lines.push(\"\");\n } else {\n for (const tag of reconciliation.kept) lines.push(`- \\`${tag}\\``);\n lines.push(\"\");\n }\n if (reconciliation.appended.length > 0) {\n lines.push(\"Appended — colliding upstream migrations renumbered after the local tail:\");\n lines.push(\"\");\n lines.push(\"| upstream tag | new tag | new idx |\");\n lines.push(\"| --- | --- | --- |\");\n for (const append of reconciliation.appended) {\n lines.push(`| \\`${append.fromTag}\\` | \\`${append.toTag}\\` | ${append.idx} |`);\n }\n lines.push(\"\");\n lines.push(\n `Next boot will apply the ${reconciliation.appended.length} appended migration(s) above; the kept set is already applied to the database.`,\n );\n lines.push(\"\");\n } else {\n lines.push(\n \"Nothing to append: every upstream migration is already applied (by tag or by content).\",\n );\n lines.push(\"\");\n }\n if (reconciliation.contentMatched.length > 0) {\n lines.push(\"Already imported under another tag (matched by SQL content hash):\");\n lines.push(\"\");\n for (const tag of reconciliation.contentMatched) lines.push(`- \\`${tag}\\``);\n lines.push(\"\");\n }\n if (reconciliation.appended.length > 0) {\n lines.push(\n \"Snapshot-chain note: renamed snapshot files record upstream intermediate schema states; review `drizzle-kit generate` output against the merged chain before generating new migrations.\",\n );\n lines.push(\"\");\n }\n }\n\n if (analysis.migrationCollisions.length > 0) {\n lines.push(\"## Migration chain collisions — unresolvable\");\n lines.push(\"\");\n lines.push(\"| kind | idx | local | upstream | detail |\");\n lines.push(\"| --- | --- | --- | --- | --- |\");\n for (const collision of analysis.migrationCollisions) {\n lines.push(\n `| ${collision.kind} | ${collision.idx} | \\`${collision.localTag ?? \"—\"}\\` | \\`${collision.upstreamTag ?? \"—\"}\\` | ${collision.message} |`,\n );\n }\n lines.push(\"\");\n }\n\n if (analysis.heldBackMigrations.length > 0) {\n lines.push(\"## Migration chain held back\");\n lines.push(\"\");\n for (const path of analysis.heldBackMigrations) lines.push(`- \\`${path}\\``);\n lines.push(\"\");\n lines.push(\n \"`src/db/migrations/**` was not modified: reconciliation could not produce a safe merged chain (content drift on an already-applied migration, or an unreadable journal). Resolve the collisions above, then re-import. The rest of the workspace imported normally.\",\n );\n lines.push(\"\");\n }\n\n if (analysis.routeDelta) {\n lines.push(\"## Contract route-set delta\");\n lines.push(\"\");\n if (analysis.routeDelta.oursOnly.length === 0 && analysis.routeDelta.theirsOnly.length === 0) {\n lines.push(\"Route sets are identical.\");\n lines.push(\"\");\n } else {\n lines.push(\n `Ours-only: ${analysis.routeDelta.oursOnly.length}, theirs-only: ${analysis.routeDelta.theirsOnly.length}.`,\n );\n lines.push(\"\");\n for (const route of analysis.routeDelta.oursOnly) lines.push(`- ours only: \\`${route}\\``);\n for (const route of analysis.routeDelta.theirsOnly) lines.push(`- theirs only: \\`${route}\\``);\n lines.push(\"\");\n }\n }\n\n const heldSet = new Set(analysis.heldBackMigrations);\n lines.push(...listSection(\"Added (upstream-only)\", analysis.added, heldSet));\n lines.push(\n ...listSection(\"Updated (would be overwritten with upstream)\", analysis.updated, heldSet),\n );\n lines.push(\n ...listSection(\"Merged (package.json — local-only keys preserved)\", analysis.merged, heldSet),\n );\n lines.push(...listSection(\"Local-only (preserved, never deleted)\", analysis.preservedLocal));\n lines.push(\n ...listSection(\"Local edits preserved (upstream unchanged)\", analysis.preservedLocalEdit),\n );\n lines.push(\n `## Unchanged`,\n \"\",\n `${analysis.unchanged.length} file(s) identical on both sides.`,\n \"\",\n );\n\n lines.push(\"## Next steps\");\n lines.push(\"\");\n lines.push(\n \"- `bos types gen` (and a build) regenerates `*.gen.ts` and `types/contract.d.ts` against the imported contract.\",\n );\n lines.push(\n \"- If preserved local changes should live upstream, open a PR against the source repo rather than keeping them only locally.\",\n );\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\nconst LOCAL_PREFIX = \"local:\";\n\nexport interface LocalWorkspaceSlot {\n /** config address of the declaring entry, e.g. `app.auth` or `plugins.ai` */\n slot: string;\n}\n\nexport function localWorkspaceSlotOf(\n config: unknown,\n workspace: string,\n): LocalWorkspaceSlot | null {\n if (!config || typeof config !== \"object\" || Array.isArray(config)) {\n return null;\n }\n const node = config as Record<string, unknown>;\n const matches = (ref: unknown): boolean =>\n typeof ref === \"string\" &&\n ref.startsWith(LOCAL_PREFIX) &&\n ref.slice(LOCAL_PREFIX.length) === workspace;\n\n const app = node.app as Record<string, unknown> | undefined;\n if (app && typeof app === \"object\") {\n for (const key of [\"host\", \"ui\", \"api\", \"auth\"]) {\n const entry = app[key] as Record<string, unknown> | undefined;\n if (entry && typeof entry === \"object\" && matches(entry.development)) {\n return { slot: `app.${key}` };\n }\n }\n }\n const plugins = node.plugins as Record<string, unknown> | undefined;\n if (plugins && typeof plugins === \"object\") {\n for (const key of Object.keys(plugins)) {\n const entry = plugins[key] as Record<string, unknown> | undefined;\n if (\n entry &&\n typeof entry === \"object\" &&\n !Array.isArray(entry) &&\n matches(entry.development)\n ) {\n return { slot: `plugins.${key}` };\n }\n }\n }\n return null;\n}\n\nexport function configEntryAt(config: unknown, slot: string): Record<string, unknown> | null {\n if (!config || typeof config !== \"object\") {\n return null;\n }\n const dot = slot.indexOf(\".\");\n if (dot === -1) {\n return null;\n }\n const container = (config as Record<string, unknown>)[slot.slice(0, dot)];\n const key = slot.slice(dot + 1);\n const entry =\n typeof container === \"object\" && container !== null && !Array.isArray(container)\n ? (container as Record<string, unknown>)[key]\n : undefined;\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n return null;\n }\n return entry as Record<string, unknown>;\n}\n\nconst HEAD_FALLBACK_NOTE = \"importing the default branch (HEAD)\";\n\nexport type VersionManifestFetcher = (url: string) => Promise<{\n bytes: Uint8Array;\n manifest: Record<string, unknown>;\n}>;\n\nasync function defaultVersionManifestFetch(\n url: string,\n): Promise<{ bytes: Uint8Array; manifest: Record<string, unknown> }> {\n const response = await fetchResponse(url, { headers: { accept: \"application/json\" } });\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n const bytes = new Uint8Array(await response.arrayBuffer());\n const manifest = JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>;\n return { bytes, manifest };\n}\n\nfunction manifestSourceOf(manifest: Record<string, unknown>): SourceRef | null {\n const parsed = WorkspaceVersionManifestSchema.pick({ source: true }).safeParse(manifest);\n return parsed.success ? (parsed.data.source ?? null) : null;\n}\n\nexport async function resolvePinnedSource(\n entry: Record<string, unknown> | null,\n fetchManifest: VersionManifestFetcher = defaultVersionManifestFetch,\n): Promise<{ sha?: string; source?: SourceRef; warning?: string }> {\n if (!entry) {\n return { warning: `no config entry found for the pinned slot — ${HEAD_FALLBACK_NOTE}` };\n }\n const pin = entry.pin as { manifest?: unknown; integrity?: unknown } | undefined;\n const manifest = typeof pin?.manifest === \"string\" ? pin.manifest : undefined;\n const production = typeof entry.production === \"string\" ? entry.production : undefined;\n if (!manifest || !production) {\n return {\n warning: `no pinned version manifest on the published config — ${HEAD_FALLBACK_NOTE}`,\n };\n }\n const url = `${production.replace(/\\/+$/, \"\")}/${manifest}`;\n let body: { bytes: Uint8Array; manifest: Record<string, unknown> };\n try {\n body = await fetchManifest(url);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { warning: `could not read the version manifest (${message}) — ${HEAD_FALLBACK_NOTE}` };\n }\n const pinIntegrity = typeof pin?.integrity === \"string\" ? pin.integrity : undefined;\n if (pinIntegrity) {\n const computed = computeSriHash(Buffer.from(body.bytes));\n if (computed !== pinIntegrity) {\n throw new Error(\n `Version manifest integrity mismatch for ${url} — expected ${pinIntegrity}, computed ${computed}. Refusing to fall back to GitHub.`,\n );\n }\n }\n const source = manifestSourceOf(body.manifest);\n if (typeof body.manifest.gitSha !== \"string\" || body.manifest.gitSha.length === 0) {\n return {\n warning: `the version manifest records no git sha (it pins content hashes only) — ${HEAD_FALLBACK_NOTE}; future deploys pin the exact commit`,\n ...(source ? { source } : {}),\n };\n }\n return { sha: body.manifest.gitSha, ...(source ? { source } : {}) };\n}\n\nconst FROM_REMEDIES =\n \"Pass the upstream explicitly: --from bos://<account>/<gateway> or --from <owner>/<repo>\";\n\nexport async function resolveImportChain(input: {\n workspace: string;\n projectDir: string;\n entrySpec?: { bosUrl: string; account: string; gateway: string };\n io?: ResolutionIo;\n fetchVersionManifest?: VersionManifestFetcher;\n}): Promise<{\n spec:\n | { kind: \"github\"; repo: string; ref?: string }\n | { kind: \"archive\"; url: string; integrity: string };\n provenance: ImportChainProvenance;\n}> {\n const fromBosSpec = input.entrySpec !== undefined;\n const entry = fromBosSpec\n ? `bos://${input.entrySpec!.account}/${input.entrySpec!.gateway}`\n : (localConfigEntryPath(input.projectDir) ?? null);\n if (!entry) {\n throw new Error(`No authored config (bos.app.ts) found — ${FROM_REMEDIES}`);\n }\n\n const links: WalkLink[] = [];\n await walkExtendsChain(entry, {\n env: \"production\",\n io: input.io,\n visit: async (link) => {\n links.push(link);\n },\n });\n links.reverse();\n\n if (links.length === 0) {\n throw new Error(`Empty extends chain from ${entry}`);\n }\n\n const declaredIndex = links.findIndex(\n (link) => localWorkspaceSlotOf(link.config, input.workspace) !== null,\n );\n if (declaredIndex === -1) {\n const chainRefs = links.map((link) => link.ref).join(\" -> \");\n throw new Error(\n `No runtime in the extends chain declares workspace \"${input.workspace}\" (${chainRefs}). ${FROM_REMEDIES}.`,\n );\n }\n if (!fromBosSpec && declaredIndex === 0) {\n throw new Error(\n `Workspace \"${input.workspace}\" is declared locally in your authored config — bos import targets an upstream ancestor`,\n );\n }\n\n const ancestor = links[declaredIndex];\n const ancestorRef = ancestor.ref.startsWith(\"bos://\")\n ? ancestor.ref\n : `authored config at ${ancestor.ref}`;\n\n let repository: string | undefined;\n for (let i = declaredIndex; i < links.length && repository === undefined; i++) {\n const value = (links[i].config as Record<string, unknown> | undefined)?.repository;\n if (typeof value === \"string\" && value.trim().length > 0) {\n repository = value;\n }\n }\n\n const warnings: string[] = [];\n const slot = localWorkspaceSlotOf(ancestor.config, input.workspace)!.slot;\n const ancestorEntry = configEntryAt(ancestor.config, slot);\n const pin = await resolvePinnedSource(ancestorEntry, input.fetchVersionManifest);\n if (pin.warning) warnings.push(pin.warning);\n\n const production =\n typeof ancestorEntry?.production === \"string\" ? ancestorEntry.production : undefined;\n const sourceArchive =\n pin.source && production\n ? {\n file: pin.source.file,\n url: `${production.replace(/\\/+$/, \"\")}/${pin.source.file}`,\n integrity: pin.source.integrity,\n }\n : undefined;\n if (!sourceArchive && !repository) {\n throw new Error(\n `No repository found along the extends chain above ${ancestorRef} — the declaring runtime must publish its source (repository field in bos.app.ts)`,\n );\n }\n\n const extendsRef = fromBosSpec\n ? entry\n : (() => {\n const selfConfig = links[0].config;\n const extendsValue = (selfConfig as Record<string, unknown> | undefined)?.extends;\n if (extendsValue === undefined) return \"authored config\";\n try {\n return (\n resolveExtendsRef(extendsValue as string | ExtendsConfig, \"production\") ??\n \"authored config\"\n );\n } catch {\n return \"authored config\";\n }\n })();\n\n if (sourceArchive) {\n return {\n spec: { kind: \"archive\", url: sourceArchive.url, integrity: sourceArchive.integrity },\n provenance: {\n extendsRef,\n ancestorRef,\n ...(repository ? { repository } : {}),\n ...(pin.sha ? { pinnedSha: pin.sha } : {}),\n sourceArchive,\n warnings,\n },\n };\n }\n\n return {\n spec: { kind: \"github\", repo: repository!, ...(pin.sha ? { ref: pin.sha } : {}) },\n provenance: {\n extendsRef,\n ancestorRef,\n ...(pin.sha ? { pinnedSha: pin.sha } : {}),\n repository: repository!,\n warnings,\n },\n };\n}\n\ninterface ImportPlan {\n fromLabel: string;\n spec: ImportFromSpec & { kind: \"github\" | \"local\" | \"archive\" };\n chain?: ImportChainProvenance;\n}\n\nasync function resolveImportPlan(input: {\n workspace: string;\n from?: string;\n projectDir: string;\n}): Promise<ImportPlan> {\n const from = input.from;\n if (!from) {\n const resolved = await resolveImportChain({\n workspace: input.workspace,\n projectDir: input.projectDir,\n });\n return {\n fromLabel: resolved.provenance.extendsRef,\n spec: resolved.spec,\n chain: resolved.provenance,\n };\n }\n const spec = parseFromSpec(from);\n if (spec.kind === \"bos\") {\n const resolved = await resolveImportChain({\n workspace: input.workspace,\n projectDir: input.projectDir,\n entrySpec: spec,\n });\n return { fromLabel: spec.bosUrl, spec: resolved.spec, chain: resolved.provenance };\n }\n return { fromLabel: from, spec };\n}\n\ntype TarballDownloader = (\n repo: string,\n ref?: string,\n) => Promise<{\n dir: string;\n cleanup: () => Promise<void>;\n resolvedRef?: string;\n resolvedSha?: string;\n}>;\n\ntype ArchiveFetcher = (url: string) => Promise<Uint8Array>;\n\nasync function defaultArchiveFetch(url: string): Promise<Uint8Array> {\n const response = await fetchResponse(url, { redirect: \"follow\", timeout: \"60 seconds\" });\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n return new Uint8Array(await response.arrayBuffer());\n}\n\nasync function extractArchive(bytes: Uint8Array): Promise<{\n root: string;\n cleanup: () => Promise<void>;\n}> {\n const tmpDir = mkdtempSync(join(tmpdir(), \"bos-import-archive-\"));\n const archivePath = join(tmpDir, \"source.tar.gz\");\n const extractDir = mkdtempSync(join(tmpdir(), \"bos-import-archive-src-\"));\n try {\n writeFileSync(archivePath, bytes);\n await tarExtract({ cwd: extractDir, file: archivePath, strip: 0 });\n } finally {\n rmSync(tmpDir, { recursive: true, force: true });\n }\n return {\n root: extractDir,\n cleanup: async () => {\n rmSync(extractDir, { recursive: true, force: true });\n },\n };\n}\n\nasync function fetchGithubSource(input: {\n repo: string;\n ref?: string;\n pinnedSha?: string;\n download: TarballDownloader;\n}): Promise<{\n source: { root: string; cleanup: () => Promise<void>; ref: string; resolvedSha?: string };\n fallbackWarning?: string;\n}> {\n const pinned = input.pinnedSha !== undefined && input.ref === input.pinnedSha;\n try {\n const tarball = await input.download(input.repo, input.ref);\n return {\n source: {\n root: tarball.dir,\n cleanup: tarball.cleanup,\n ref: input.ref ?? tarball.resolvedRef ?? \"main\",\n resolvedSha: tarball.resolvedSha,\n },\n };\n } catch (error) {\n if (!pinned) throw error;\n const message = error instanceof Error ? error.message : String(error);\n const tarball = await input.download(input.repo, undefined);\n return {\n source: {\n root: tarball.dir,\n cleanup: tarball.cleanup,\n ref: tarball.resolvedRef ?? \"main\",\n resolvedSha: tarball.resolvedSha,\n },\n fallbackWarning: `could not fetch the pinned commit ${input.pinnedSha} (${message}) — importing the default branch`,\n };\n }\n}\n\nexport async function fetchSourceWithPinFallback(input: {\n spec: ImportFromSpec & { kind: \"github\" | \"local\" | \"archive\" };\n pinnedSha?: string;\n download?: TarballDownloader;\n fetchArchive?: ArchiveFetcher;\n fallback?: { repo: string; ref?: string };\n}): Promise<{\n source: { root: string; cleanup: () => Promise<void>; ref: string; resolvedSha?: string };\n fallbackWarning?: string;\n}> {\n if (input.spec.kind === \"local\") {\n return { source: { root: input.spec.dir, cleanup: async () => {}, ref: \"local\" } };\n }\n const download = input.download ?? downloadTarball;\n if (input.spec.kind === \"archive\") {\n const fetchArchive = input.fetchArchive ?? defaultArchiveFetch;\n try {\n const bytes = await fetchArchive(input.spec.url);\n const computed = computeSriHash(Buffer.from(bytes));\n if (computed !== input.spec.integrity) {\n throw new Error(\n `integrity mismatch for ${input.spec.url} — expected ${input.spec.integrity}, computed ${computed}`,\n );\n }\n const extracted = await extractArchive(bytes);\n return { source: { ...extracted, ref: \"source archive\" } };\n } catch (error) {\n if (!input.fallback) throw error;\n const message = error instanceof Error ? error.message : String(error);\n const gh = await fetchGithubSource({\n repo: input.fallback.repo,\n ref: input.fallback.ref,\n pinnedSha: input.pinnedSha,\n download,\n });\n return {\n ...gh,\n fallbackWarning: `could not fetch the source archive (${message}) — importing from ${input.fallback.repo} instead`,\n };\n }\n }\n return fetchGithubSource({\n repo: input.spec.repo,\n ref: input.spec.ref,\n pinnedSha: input.pinnedSha,\n download,\n });\n}\n\nasync function resolveImportSource(\n spec: ImportPlan[\"spec\"],\n chain?: ImportChainProvenance,\n): Promise<{\n root: string;\n cleanup: () => Promise<void>;\n ref: string;\n resolvedSha?: string;\n fallbackWarning?: string;\n}> {\n const { source, fallbackWarning } = await fetchSourceWithPinFallback({\n spec,\n pinnedSha: chain?.pinnedSha,\n fallback: chain?.repository\n ? {\n repo: chain.repository,\n ...(chain.pinnedSha ? { ref: chain.pinnedSha } : {}),\n }\n : undefined,\n });\n return { ...source, fallbackWarning };\n}\n\nexport async function importWorkspace(\n projectDir: string,\n options: ImportOptions,\n deps?: ImportDeps,\n): Promise<ImportResult> {\n const errorResult = (workspace: string, ref: string, message: string): ImportResult => ({\n status: \"error\",\n workspace,\n from: options.from ?? \"\",\n ref,\n added: [],\n updated: [],\n unchanged: [],\n preservedLocal: [],\n merged: [],\n conflicts: [],\n heldBackMigrations: [],\n migrationCollisions: [],\n warnings: [],\n error: message,\n });\n\n const errorMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n let workspace = options.workspace;\n let fromLabel = options.from ?? \"\";\n let ref = \"\";\n let chain: ImportChainProvenance | undefined;\n try {\n workspace = normalizeWorkspacePath(options.workspace);\n const plan = await resolveImportPlan({\n workspace,\n from: options.from,\n projectDir,\n });\n fromLabel = plan.fromLabel;\n chain = plan.chain;\n const spec = plan.spec;\n const source = await resolveImportSource(spec, chain);\n if (source.fallbackWarning && chain) {\n const { sourceArchive: _dropped, ...rest } = chain;\n chain = {\n ...rest,\n pinnedSha: undefined,\n warnings: [...chain.warnings, source.fallbackWarning],\n };\n }\n ref = source.ref;\n\n try {\n const upstreamWorkspaceDir = join(source.root, workspace);\n if (!existsSync(upstreamWorkspaceDir) || !lstatSync(upstreamWorkspaceDir).isDirectory()) {\n throw new Error(\n `Workspace \"${workspace}\" not found in ${fromLabel}${\n source.ref !== \"local\" ? ` at ref ${source.ref}` : \"\"\n }`,\n );\n }\n\n const upstreamFiles = await listWorkspaceSubtreeFiles(source.root, workspace);\n const localWorkspaceDir = join(projectDir, workspace);\n const localFiles = existsSync(localWorkspaceDir)\n ? await listWorkspaceSubtreeFiles(projectDir, workspace)\n : [];\n\n const upstreamSet = new Set(upstreamFiles);\n const localSet = new Set(localFiles);\n\n const importSnapshot = readImportSnapshot(projectDir);\n const workspaceSnapshot = importSnapshot.workspaces[workspace];\n const syncSnapshot = await readSnapshot(projectDir);\n const baselineFor = (path: string): string | undefined =>\n workspaceSnapshot?.files[path] ?? syncSnapshot?.files[path];\n\n const packageJsonPath = `${workspace}/package.json`;\n const mergeablePackageJson = (() => {\n if (!localSet.has(packageJsonPath) || !upstreamSet.has(packageJsonPath)) return false;\n return (\n readJson(join(projectDir, packageJsonPath)) !== null &&\n readJson(join(source.root, packageJsonPath)) !== null\n );\n })();\n\n const chainPrefix = `${workspace}/src/db/migrations/`;\n const chainJournalPath = `${chainPrefix}meta/_journal.json`;\n const localMigrations = loadMigrationEntries(projectDir, workspace);\n const upstreamMigrations = loadMigrationEntries(source.root, workspace);\n const localJournalExists = existsSync(join(projectDir, chainJournalPath));\n const reconciliation =\n localMigrations && upstreamMigrations\n ? reconcileMigrationChains(localMigrations, upstreamMigrations)\n : null;\n\n let chainUnsafe: boolean;\n if (reconciliation) {\n chainUnsafe = reconciliation.unresolvable.length > 0;\n } else if (localMigrations === null && localJournalExists) {\n chainUnsafe = true;\n } else if (localMigrations !== null && upstreamMigrations === null) {\n chainUnsafe = true;\n } else {\n chainUnsafe = false;\n }\n\n const migrationRemap = new Map<string, string>();\n const migrationSkipped = new Set<string>();\n if (reconciliation && !chainUnsafe) {\n const appendedByFromTag = new Map(\n reconciliation.appended.map((append) => [append.fromTag, append]),\n );\n const contentMatchedTags = new Set(reconciliation.contentMatched);\n const upstreamTagBySnapshotPrefix = new Map<string, string>();\n for (const entry of upstreamMigrations ?? []) {\n const prefix = snapshotPrefixOf(entry.tag);\n if (prefix) upstreamTagBySnapshotPrefix.set(prefix, entry.tag);\n }\n for (const path of upstreamFiles) {\n if (!path.startsWith(chainPrefix) || path === chainJournalPath) continue;\n const relInMigrations = path.slice(chainPrefix.length);\n if (relInMigrations.endsWith(\".sql\")) {\n const tag = relInMigrations.slice(0, -\".sql\".length);\n const append = appendedByFromTag.get(tag);\n if (append) {\n migrationRemap.set(path, `${chainPrefix}${append.toTag}.sql`);\n } else if (contentMatchedTags.has(tag)) {\n migrationSkipped.add(path);\n }\n } else if (\n relInMigrations.startsWith(\"meta/\") &&\n relInMigrations.endsWith(\"_snapshot.json\")\n ) {\n const prefix = relInMigrations.slice(\n \"meta/\".length,\n relInMigrations.length - \"_snapshot.json\".length,\n );\n const tag = upstreamTagBySnapshotPrefix.get(prefix);\n const append = tag ? appendedByFromTag.get(tag) : undefined;\n if (append) {\n migrationRemap.set(\n path,\n `${chainPrefix}meta/${String(append.idx).padStart(4, \"0\")}_snapshot.json`,\n );\n } else if (tag && contentMatchedTags.has(tag)) {\n migrationSkipped.add(path);\n }\n }\n }\n }\n\n const added: string[] = [];\n const updated: string[] = [];\n const unchanged: string[] = [];\n const preservedLocal: string[] = [];\n const preservedLocalEdit: string[] = [];\n const merged: string[] = [];\n const conflicts: Array<{\n path: string;\n reason: \"no-baseline\" | \"both-changed\";\n held: boolean;\n }> = [];\n const upstreamHashByPath = new Map<string, string>();\n\n const allPaths = [...new Set([...localFiles, ...upstreamFiles])].sort();\n for (const path of allPaths) {\n if (!upstreamSet.has(path)) {\n preservedLocal.push(path);\n continue;\n }\n if (reconciliation && path === chainJournalPath) continue;\n if (migrationRemap.has(path) || migrationSkipped.has(path)) continue;\n const localHash = localSet.has(path) ? hashFile(projectDir, path) : null;\n const upstreamHash = hashFile(source.root, path);\n if (upstreamHash === null) {\n throw new Error(`Failed to read upstream file: ${path}`);\n }\n upstreamHashByPath.set(path, upstreamHash);\n const classification = classifyImportFile({\n localHash,\n upstreamHash,\n baselineHash: baselineFor(path),\n mergeable: path === packageJsonPath && mergeablePackageJson,\n });\n switch (classification.kind) {\n case \"added\":\n added.push(path);\n break;\n case \"unchanged\":\n unchanged.push(path);\n break;\n case \"updated\":\n updated.push(path);\n break;\n case \"preserved-local\":\n preservedLocal.push(path);\n break;\n case \"preserved-local-edit\":\n preservedLocalEdit.push(path);\n break;\n case \"merged\":\n merged.push(path);\n break;\n case \"conflict\":\n conflicts.push({ path, reason: classification.reason, held: false });\n break;\n }\n }\n\n let routeDelta: ImportRouteDelta | undefined;\n const localRoutes = extractWorkspaceRoutes(\n await collectContractRouteSources(projectDir, workspace),\n );\n const upstreamRoutes = extractWorkspaceRoutes(\n await collectContractRouteSources(source.root, workspace),\n );\n if (localRoutes !== null || upstreamRoutes !== null) {\n routeDelta = computeRouteDelta(localRoutes ?? [], upstreamRoutes ?? []);\n }\n\n const migrationCollisions = reconciliation?.unresolvable ?? [];\n\n const writeCandidates = new Set([\n ...added,\n ...updated,\n ...merged,\n ...conflicts.map((conflict) => conflict.path),\n ]);\n const heldSet = new Set(\n chainUnsafe ? [...writeCandidates].filter((path) => path.startsWith(chainPrefix)) : [],\n );\n if (chainUnsafe && reconciliation) {\n heldSet.add(chainJournalPath);\n }\n const heldBackMigrations = [...heldSet].sort();\n for (const conflict of conflicts) {\n conflict.held = heldSet.has(conflict.path);\n }\n\n const analysis: ImportReportAnalysis = {\n workspace,\n from: fromLabel,\n ref: source.ref,\n resolvedSha: source.resolvedSha,\n sourceKind: spec.kind,\n chain,\n added,\n updated,\n unchanged,\n preservedLocal,\n preservedLocalEdit,\n merged,\n conflicts,\n routeDelta,\n migrationCollisions,\n migrationReconciliation: reconciliation,\n heldBackMigrations,\n };\n\n const resultBase = {\n workspace,\n from: fromLabel,\n ref: source.ref,\n resolvedSha: source.resolvedSha,\n sourceRepository: chain?.repository,\n warnings: chain ? chain.warnings : [],\n added,\n updated,\n unchanged,\n preservedLocal,\n merged,\n conflicts: conflicts.map((conflict) => conflict.path),\n heldBackMigrations,\n routeDelta,\n migrationCollisions,\n migrationReconciliation: reconciliation ?? undefined,\n };\n\n if (options.dryRun) {\n const reportPath = writeImportReport(\n projectDir,\n buildImportReport(analysis, { mode: \"dry-run\" }),\n );\n return { status: \"dry-run\", ...resultBase, reportPath };\n }\n\n const appendedCount = reconciliation?.appended.length ?? 0;\n const gated = conflicts.length > 0 || heldBackMigrations.length > 0 || appendedCount > 0;\n if (gated && !options.yes) {\n let approved = false;\n if (deps?.confirm) {\n approved = await deps.confirm({\n workspace,\n conflictCount: conflicts.length,\n migrationCollisionCount: migrationCollisions.length,\n heldCount: heldBackMigrations.length,\n appendedCount,\n });\n }\n if (!approved) {\n const reportPath = writeImportReport(\n projectDir,\n buildImportReport(analysis, { mode: \"refused\" }),\n );\n return { status: \"conflicts\", ...resultBase, reportPath };\n }\n }\n\n const isHeld = (path: string): boolean => heldSet.has(path);\n\n const mergeContents = new Map<string, string>();\n for (const path of merged) {\n const local = readJson(join(projectDir, path));\n const upstream = readJson(join(source.root, path));\n if (!local || !upstream) {\n throw new Error(`Failed to merge ${path}: unreadable package.json`);\n }\n mergeContents.set(\n path,\n `${JSON.stringify(mergePackageJson(path, local, upstream), null, 2)}\\n`,\n );\n }\n\n const reconciliationActive = reconciliation !== null && !chainUnsafe;\n const journalRebuildContent =\n reconciliationActive && reconciliation.appended.length > 0\n ? buildMergedJournal(projectDir, source.root, workspace, reconciliation.appended)\n : null;\n const journalChanged =\n journalRebuildContent !== null &&\n journalRebuildContent !== readFileSync(join(projectDir, chainJournalPath), \"utf-8\");\n\n const reconciliationOverwrites: Array<{ upstreamPath: string; localPath: string }> = [];\n if (reconciliationActive) {\n for (const [upstreamPath, localPath] of migrationRemap) {\n const upstreamContent = readFileSync(join(source.root, upstreamPath), \"utf-8\");\n if (\n !existsSync(join(projectDir, localPath)) ||\n readFileSync(join(projectDir, localPath), \"utf-8\") !== upstreamContent\n ) {\n reconciliationOverwrites.push({ upstreamPath, localPath });\n }\n }\n }\n\n const overwritePaths = [\n ...updated.filter((path) => !isHeld(path)),\n ...conflicts.map((conflict) => conflict.path).filter((path) => !isHeld(path)),\n ...merged.filter(\n (path) => mergeContents.get(path) !== readFileSync(join(projectDir, path), \"utf-8\"),\n ),\n ...(journalChanged ? [chainJournalPath] : []),\n ...reconciliationOverwrites.map((write) => write.localPath),\n ];\n const backupDir = backupImportFiles(projectDir, overwritePaths);\n\n const writeUpstream = (path: string) => {\n const dest = safeProjectPath(projectDir, path);\n mkdirSync(dirname(dest), { recursive: true });\n copyFileSync(join(source.root, path), dest);\n };\n\n for (const path of added) {\n if (!isHeld(path)) writeUpstream(path);\n }\n for (const path of updated) {\n if (!isHeld(path)) writeUpstream(path);\n }\n for (const conflict of conflicts) {\n if (!isHeld(conflict.path)) writeUpstream(conflict.path);\n }\n for (const path of merged) {\n const content = mergeContents.get(path);\n if (content === undefined || isHeld(path)) continue;\n if (content === readFileSync(join(projectDir, path), \"utf-8\")) continue;\n const dest = safeProjectPath(projectDir, path);\n mkdirSync(dirname(dest), { recursive: true });\n writeFileSync(dest, content);\n }\n for (const { upstreamPath, localPath } of reconciliationOverwrites) {\n const dest = safeProjectPath(projectDir, localPath);\n mkdirSync(dirname(dest), { recursive: true });\n copyFileSync(join(source.root, upstreamPath), dest);\n }\n if (journalChanged && journalRebuildContent) {\n const dest = safeProjectPath(projectDir, chainJournalPath);\n mkdirSync(dirname(dest), { recursive: true });\n writeFileSync(dest, journalRebuildContent);\n }\n\n const writtenPaths = [\n ...added,\n ...updated,\n ...merged,\n ...conflicts.map((conflict) => conflict.path),\n ].filter((path) => !isHeld(path));\n const recorded: Record<string, string> = {};\n for (const path of writtenPaths) {\n const hash = hashFile(projectDir, path);\n if (hash) {\n recorded[path] = hash;\n }\n }\n if (journalChanged && journalRebuildContent) {\n recorded[chainJournalPath] = computeSnapshotHash(journalRebuildContent);\n }\n for (const { localPath } of reconciliationOverwrites) {\n const hash = hashFile(projectDir, localPath);\n if (hash) {\n recorded[localPath] = hash;\n }\n }\n for (const path of [...unchanged, ...preservedLocalEdit]) {\n const hash = upstreamHashByPath.get(path);\n if (hash) {\n recorded[path] = hash;\n }\n }\n\n writeImportSnapshot(projectDir, {\n workspaces: {\n ...importSnapshot.workspaces,\n [workspace]: {\n from: fromLabel,\n ref: source.ref,\n timestamp: new Date().toISOString(),\n files: recorded,\n },\n },\n });\n\n if (syncSnapshot) {\n await writeSnapshot(projectDir, {\n parentRef: syncSnapshot.parentRef,\n files: { ...syncSnapshot.files, ...recorded },\n starter: syncSnapshot.starter,\n });\n }\n\n const reportPath = writeImportReport(\n projectDir,\n buildImportReport(analysis, { mode: \"applied\", backupDir }),\n );\n\n if (!options.noInstall) {\n try {\n await runPnpmInstall(findWorkspaceRoot(projectDir)?.dir ?? projectDir);\n await runTypesGen(projectDir);\n } catch (error) {\n return {\n status: \"error\",\n ...resultBase,\n backupDir,\n reportPath,\n error: `Import applied, but the post-install step failed: ${errorMessage(error)}`,\n };\n }\n }\n\n return { status: \"imported\", ...resultBase, backupDir, reportPath };\n } finally {\n await source.cleanup();\n }\n } catch (error) {\n return errorResult(workspace, ref, errorMessage(error));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAE3B,MAAa,qBAAqB,QAAQ;AAmE1C,SAAS,cAAc,MAAuB;CAC5C,IAAI;EACF,WAAOA,oBAAW,IAAI,SAAKC,kBAAS,IAAI,CAAC,CAAC,YAAY;CACxD,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,oBAAoB,MAA6B;CACxD,IAAIC,gCAAe,IAAI,GACrB,OAAO;CAET,MAAM,QAAQ,KAAK,MAAM,sDAAsD;CAC/E,IAAI,CAAC,QAAQ,MAAM,CAAC,MAAM,IAAI,OAAO;CACrC,IAAI,MAAM,OAAO,OAAO,MAAM,OAAO,QAAQ,MAAM,OAAO,OAAO,MAAM,OAAO,MAAM,OAAO;CAC3F,OAAO,sBAAsB,MAAM,GAAG,GAAG,MAAM;AACjD;AAEA,SAAgB,cAAc,MAA8B;CAC1D,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,CAAC,SACH,MAA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