everything-dev 2.0.0-rc.6 → 2.0.0-rc.7

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 (116) hide show
  1. package/README.md +2 -2
  2. package/dist/build.cjs +1 -1
  3. package/dist/build.mjs +1 -1
  4. package/dist/bundle-cache.cjs +1 -1
  5. package/dist/bundle-cache.cjs.map +1 -1
  6. package/dist/bundle-cache.mjs +1 -1
  7. package/dist/bundle-cache.mjs.map +1 -1
  8. package/dist/cli.cjs +2 -2
  9. package/dist/cli.cjs.map +1 -1
  10. package/dist/cli.mjs +1 -1
  11. package/dist/cli.mjs.map +1 -1
  12. package/dist/commands/deploy.cjs +111 -1
  13. package/dist/commands/deploy.cjs.map +1 -1
  14. package/dist/commands/deploy.mjs +112 -2
  15. package/dist/commands/deploy.mjs.map +1 -1
  16. package/dist/commands/smoke.cjs +41 -0
  17. package/dist/commands/smoke.cjs.map +1 -0
  18. package/dist/commands/smoke.mjs +41 -0
  19. package/dist/commands/smoke.mjs.map +1 -0
  20. package/dist/commands/upgrade.cjs +2 -2
  21. package/dist/commands/upgrade.cjs.map +1 -1
  22. package/dist/commands/upgrade.mjs +1 -1
  23. package/dist/commands/upgrade.mjs.map +1 -1
  24. package/dist/contract.cjs +27 -1
  25. package/dist/contract.cjs.map +1 -1
  26. package/dist/contract.d.cts +65 -1
  27. package/dist/contract.d.mts +65 -1
  28. package/dist/contract.meta.cjs +13 -1
  29. package/dist/contract.meta.cjs.map +1 -1
  30. package/dist/contract.meta.d.cts +23 -1
  31. package/dist/contract.meta.d.mts +23 -1
  32. package/dist/contract.meta.mjs +13 -1
  33. package/dist/contract.meta.mjs.map +1 -1
  34. package/dist/contract.mjs +26 -2
  35. package/dist/contract.mjs.map +1 -1
  36. package/dist/dev-log-pipeline.cjs +6 -0
  37. package/dist/dev-log-pipeline.cjs.map +1 -1
  38. package/dist/dev-log-pipeline.mjs +6 -0
  39. package/dist/dev-log-pipeline.mjs.map +1 -1
  40. package/dist/dev-program.cjs +20 -3
  41. package/dist/dev-program.cjs.map +1 -1
  42. package/dist/dev-program.mjs +20 -4
  43. package/dist/dev-program.mjs.map +1 -1
  44. package/dist/dev-session.cjs +1 -0
  45. package/dist/dev-session.cjs.map +1 -1
  46. package/dist/dev-session.mjs +1 -0
  47. package/dist/dev-session.mjs.map +1 -1
  48. package/dist/fastkv.cjs +21 -3
  49. package/dist/fastkv.cjs.map +1 -1
  50. package/dist/fastkv.d.cts +14 -1
  51. package/dist/fastkv.d.mts +14 -1
  52. package/dist/fastkv.mjs +21 -5
  53. package/dist/fastkv.mjs.map +1 -1
  54. package/dist/{mf.cjs → federation.cjs} +6 -13
  55. package/dist/federation.cjs.map +1 -0
  56. package/dist/{mf.d.cts → federation.d.cts} +2 -2
  57. package/dist/{mf.d.mts → federation.d.mts} +2 -2
  58. package/dist/{mf.mjs → federation.mjs} +6 -13
  59. package/dist/federation.mjs.map +1 -0
  60. package/dist/http-client.cjs +70 -53
  61. package/dist/http-client.cjs.map +1 -1
  62. package/dist/http-client.mjs +70 -54
  63. package/dist/http-client.mjs.map +1 -1
  64. package/dist/image-deploy.cjs +9 -0
  65. package/dist/image-deploy.cjs.map +1 -1
  66. package/dist/image-deploy.mjs +9 -1
  67. package/dist/image-deploy.mjs.map +1 -1
  68. package/dist/index.cjs +4 -0
  69. package/dist/index.d.cts +3 -3
  70. package/dist/index.d.mts +3 -3
  71. package/dist/index.mjs +3 -3
  72. package/dist/orchestrator.cjs +39 -35
  73. package/dist/orchestrator.cjs.map +1 -1
  74. package/dist/orchestrator.mjs +39 -35
  75. package/dist/orchestrator.mjs.map +1 -1
  76. package/dist/plugin.cjs +2 -0
  77. package/dist/plugin.cjs.map +1 -1
  78. package/dist/plugin.d.cts +24 -0
  79. package/dist/plugin.d.mts +24 -0
  80. package/dist/plugin.mjs +2 -0
  81. package/dist/plugin.mjs.map +1 -1
  82. package/dist/process-registry.cjs +1 -1
  83. package/dist/process-registry.mjs +1 -1
  84. package/dist/publish.cjs +3 -3
  85. package/dist/publish.cjs.map +1 -1
  86. package/dist/publish.mjs +4 -4
  87. package/dist/publish.mjs.map +1 -1
  88. package/dist/resolver.cjs +293 -0
  89. package/dist/resolver.cjs.map +1 -0
  90. package/dist/resolver.d.cts +99 -0
  91. package/dist/resolver.d.mts +99 -0
  92. package/dist/resolver.mjs +284 -0
  93. package/dist/resolver.mjs.map +1 -0
  94. package/dist/smoke.cjs +262 -0
  95. package/dist/smoke.cjs.map +1 -0
  96. package/dist/smoke.mjs +260 -0
  97. package/dist/smoke.mjs.map +1 -0
  98. package/dist/version-manifest-resolve.cjs +3 -3
  99. package/dist/version-manifest-resolve.cjs.map +1 -1
  100. package/dist/version-manifest-resolve.mjs +1 -1
  101. package/dist/version-manifest-resolve.mjs.map +1 -1
  102. package/dist/workspace.cjs +1 -1
  103. package/dist/workspace.mjs +1 -1
  104. package/package.json +9 -9
  105. package/dist/bundle-fs-resolve.cjs +0 -235
  106. package/dist/bundle-fs-resolve.cjs.map +0 -1
  107. package/dist/bundle-fs-resolve.d.cts +0 -82
  108. package/dist/bundle-fs-resolve.d.mts +0 -82
  109. package/dist/bundle-fs-resolve.mjs +0 -228
  110. package/dist/bundle-fs-resolve.mjs.map +0 -1
  111. package/dist/bundle-path.cjs +0 -48
  112. package/dist/bundle-path.cjs.map +0 -1
  113. package/dist/bundle-path.mjs +0 -45
  114. package/dist/bundle-path.mjs.map +0 -1
  115. package/dist/mf.cjs.map +0 -1
  116. package/dist/mf.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"federation.mjs","names":[],"sources":["../src/federation.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { createInstance, getInstance } from \"@module-federation/enhanced/runtime\";\nimport { setGlobalFederationInstance } from \"@module-federation/runtime-core\";\nimport { isEffectCriticalSharedDep } from \"every-plugin/build/rspack\";\nimport { readBundleCache, writeBundleCache } from \"./bundle-cache\";\nimport { fetchRaw } from \"./http-client\";\nimport { computeSriHash, type IntegrityRegistry } from \"./integrity\";\nimport type { BosConfig, BosPluginRef } from \"./types\";\n\ntype FederationInstance = ReturnType<typeof createInstance>;\n\nlet mfInstance: FederationInstance | null = null;\n\nexport function patchManifestFetchForSsrPublicPath(mf: FederationInstance): void {\n if (!mf || !(mf as any).loaderHook?.lifecycle?.fetch?.on) return;\n if ((mf as any).__everythingDevPatchedManifestFetch === true) return;\n (mf as any).__everythingDevPatchedManifestFetch = true;\n\n (mf as any).loaderHook.lifecycle.fetch.on((url: unknown, init: unknown) => {\n if (typeof url !== \"string\" || !url.endsWith(\"/mf-manifest.json\")) {\n return;\n }\n return fetchRaw(url as string, init as RequestInit, \"15 seconds\")\n .then((res) => res.json())\n .then((json: any) => {\n json.metaData = json.metaData ?? {};\n json.metaData.ssrPublicPath =\n json.metaData.ssrPublicPath ?? url.replace(/\\/mf-manifest\\.json$/, \"/\");\n if (json.metaData.publicPath === \"auto\" || json.metaData.publicPath === \"\") {\n json.metaData.publicPath = \"/\";\n }\n return new Response(JSON.stringify(json), {\n headers: { \"content-type\": \"application/json\" },\n });\n });\n });\n}\n\nexport function installIntegrityFetchHook(\n mf: FederationInstance,\n registry: IntegrityRegistry,\n options?: { cacheDir?: string },\n): void {\n if (!mf || !(mf as any).loaderHook?.lifecycle?.fetch?.on) {\n console.warn(\"[SRI] MF lifecycle fetch hook not available, skipping integrity-in-pipeline\");\n return;\n }\n if ((mf as any).__everythingDevIntegrityHook === true) return;\n (mf as any).__everythingDevIntegrityHook = true;\n\n (mf as any).loaderHook.lifecycle.fetch.on((url: unknown, init: unknown) => {\n if (typeof url !== \"string\") return;\n\n const expectedHash = registry.get(url);\n if (!expectedHash) return;\n\n return fetchRaw(url as string, init as RequestInit, \"15 seconds\").then(async (res) => {\n const buffer = Buffer.from(await res.arrayBuffer());\n const computed = computeSriHash(buffer);\n\n if (computed !== expectedHash) {\n // ticket 09 (atomic-deploys): an SRI mismatch is treated like an\n // origin failure — the last-known-good bytes (which satisfied the\n // same pin when cached) serve instead, and the corrupted bytes are\n // never written into the cache.\n const cached = await readBundleCache(url as string, { cacheDir: options?.cacheDir });\n if (cached && computeSriHash(Buffer.from(cached)) === expectedHash) {\n console.warn(\n `[SRI] Origin bytes failed verification for ${url} — serving last-known-good from the bundle cache`,\n );\n return new Response(cached.slice().buffer, {\n status: 200,\n headers: { \"x-bundle-cache\": \"stale\" },\n });\n }\n console.error(\n `[SRI] Integrity check failed in MF fetch pipeline for ${url}\\n Expected: ${expectedHash}\\n Computed: ${computed}`,\n );\n return new Response(`Integrity check failed for ${url}`, {\n status: 500,\n statusText: \"Integrity Check Failed\",\n });\n }\n\n // verified: pin-checked write-through\n await writeBundleCache(url as string, new Uint8Array(buffer), {\n cacheDir: options?.cacheDir,\n }).catch(() => {\n // write-through is best-effort\n });\n\n return new Response(buffer, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n });\n });\n });\n}\n\nexport function getFederationInstance(): FederationInstance {\n if (mfInstance) return mfInstance;\n\n const existing = getInstance();\n if (existing) {\n mfInstance = existing as FederationInstance;\n setGlobalFederationInstance(mfInstance as any);\n patchManifestFetchForSsrPublicPath(mfInstance);\n return mfInstance;\n }\n\n mfInstance = createInstance({\n name: \"host\",\n remotes: [],\n }) as FederationInstance;\n setGlobalFederationInstance(mfInstance as any);\n patchManifestFetchForSsrPublicPath(mfInstance);\n return mfInstance;\n}\n\nexport async function registerRemote(opts: {\n name: string;\n entry: string;\n type?: \"manifest\" | \"script\";\n}): Promise<void> {\n const instance = getFederationInstance();\n\n const inferType = (): \"manifest\" | \"script\" => {\n if (opts.type) return opts.type;\n if (opts.entry.endsWith(\"/mf-manifest.json\")) return \"manifest\";\n if (/\\/remoteEntry(\\.[a-f0-9]{8,})?\\.js$/.test(opts.entry)) return \"script\";\n return typeof window === \"undefined\" ? \"script\" : \"manifest\";\n };\n\n const remoteType = inferType();\n\n instance.registerRemotes([\n {\n name: opts.name,\n entry: opts.entry,\n type: remoteType,\n },\n ]);\n}\n\nexport async function loadRemoteModule<T>(\n specifier: string,\n options?: { loadFactory?: boolean; from?: \"build\" | \"runtime\" },\n): Promise<T> {\n const instance = getFederationInstance();\n\n const isServer = typeof window === \"undefined\";\n if (isServer) {\n await (instance as any).initializeSharing?.(\"default\");\n }\n\n const mod = await instance.loadRemote<T>(specifier, options as any);\n if (!mod) {\n throw new Error(`Failed to load remote module: ${specifier}`);\n }\n return mod;\n}\n\nexport async function ensureNodeRuntimePlugin(): Promise<void> {\n const instance = getFederationInstance();\n if (typeof window !== \"undefined\") return;\n if ((instance as any).__nodeRuntimePluginLoaded) return;\n\n const mod: any = await import(\"@module-federation/node/runtimePlugin\");\n const factory = mod?.default ?? mod;\n const plugin = typeof factory === \"function\" ? factory() : null;\n if (plugin) {\n instance.registerPlugins([plugin]);\n }\n (instance as any).__nodeRuntimePluginLoaded = true;\n}\n\nexport interface FederationCompatRemote {\n role: string;\n url: string;\n reachable: boolean;\n pluginVersion: string | null;\n ok: boolean;\n reason?: string;\n}\n\nexport interface FederationCompatReport {\n ok: boolean;\n hostVersion: string | null;\n hostReachable: boolean;\n hostReason?: string;\n remotes: FederationCompatRemote[];\n}\n\nfunction parseSemver(v: unknown): { major: number; minor: number; patch: number } | null {\n const m = typeof v === \"string\" ? /^(\\d+)\\.(\\d+)\\.(\\d+)/.exec(v) : null;\n return m ? { major: +m[1]!, minor: +m[2]!, patch: +m[3]! } : null;\n}\n\nfunction satisfiesConstraint(version: string, constraint: string): boolean {\n const trimmed = constraint.trim();\n if (!trimmed) return true;\n if (![\"^\", \"~\", \">\", \"<\", \"=\", \"x\"].some((c) => trimmed.startsWith(c))) {\n return version === trimmed;\n }\n const m = /^\\s*\\^\\s*(\\d+)\\.(\\d+)\\.(\\d+)/.exec(trimmed);\n if (!m) return true;\n const v = parseSemver(version);\n if (!v) return false;\n if (v.major !== +m[1]!) return false;\n if (v.minor < +m[2]! || (v.minor === +m[2]! && v.patch < +m[3]!)) return false;\n const constraintPrerelease = trimmed.match(/-([0-9A-Za-z.-]+)/);\n const versionPrerelease = /-([0-9A-Za-z.-]+)\\s*$/.exec(version);\n if (constraintPrerelease) {\n if (!versionPrerelease) return false;\n const cPre = constraintPrerelease[1]!.split(\".\");\n const vPre = versionPrerelease[1]!.split(\".\");\n for (let i = 0; i < Math.max(cPre.length, vPre.length); i += 1) {\n const c = cPre[i] ?? \"0\";\n const p = vPre[i] ?? \"0\";\n if (c === p) continue;\n const cNum = /^\\d+$/.test(c) ? +c : null;\n const pNum = /^\\d+$/.test(p) ? +p : null;\n if (cNum !== null && pNum !== null) return cNum < pNum;\n return cNum === null ? c.localeCompare(p) < 0 : false;\n }\n return true;\n }\n if (versionPrerelease) return false;\n return true;\n}\n\nfunction manifestUrl(remoteUrl: string): string {\n return remoteUrl.endsWith(\"/\") ? `${remoteUrl}mf-manifest.json` : `${remoteUrl}/mf-manifest.json`;\n}\n\nasync function fetchManifest(url: string, timeoutMs: number): Promise<unknown> {\n const res = await fetchRaw(manifestUrl(url), {}, timeoutMs);\n if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);\n return res.json();\n}\n\nfunction listFederationRemotes(bosConfig: BosConfig): Array<{ role: string; url: string }> {\n const out: Array<{ role: string; url: string }> = [];\n for (const role of [\"api\", \"auth\"] as const) {\n const url = readProductionUrl((bosConfig?.app as Record<string, unknown> | undefined)?.[role]);\n if (url) out.push({ role, url });\n }\n for (const [id, slot] of Object.entries(bosConfig?.plugins ?? {})) {\n const url = readProductionUrl(slot);\n if (url) out.push({ role: id, url });\n }\n return out;\n}\n\nfunction readProductionUrl(entry: unknown): string | null {\n if (typeof entry === \"string\") return entry.length > 0 ? entry : null;\n if (entry && typeof (entry as BosPluginRef).production === \"string\") {\n const url = (entry as BosPluginRef).production!;\n return url.length > 0 ? url : null;\n }\n return null;\n}\n\ninterface RemoteManifest {\n metaData?: { pluginVersion?: string };\n shared?: Array<{ name: string; version?: string; requiredVersion?: string | null }>;\n}\n\nexport async function checkFederationCompat(\n bosConfig: BosConfig | null,\n opts: { timeoutMs?: number } = {},\n): Promise<FederationCompatReport> {\n const timeoutMs = opts.timeoutMs ?? 15_000;\n\n if (!bosConfig?.app?.host?.production) {\n return { ok: true, hostVersion: null, hostReachable: false, remotes: [] };\n }\n\n const hostUrl = bosConfig.app.host.production;\n let hostManifest: RemoteManifest | null = null;\n let hostReason: string | undefined;\n try {\n hostManifest = (await fetchManifest(hostUrl, timeoutMs)) as RemoteManifest;\n } catch (e) {\n hostReason = e instanceof Error ? e.message : String(e);\n }\n\n const hostVersion = hostManifest?.metaData?.pluginVersion ?? null;\n const hostShared = (hostManifest?.shared ?? []).filter(\n (s) => typeof s.requiredVersion === \"string\",\n );\n\n const remotes = listFederationRemotes(bosConfig);\n const settled = await Promise.allSettled(\n remotes.map(async ({ role, url }) => {\n let manifest: RemoteManifest | null = null;\n let reason: string | undefined;\n try {\n manifest = (await fetchManifest(url, timeoutMs)) as RemoteManifest;\n } catch (e) {\n reason = e instanceof Error ? e.message : String(e);\n }\n\n const version = manifest?.metaData?.pluginVersion ?? null;\n const versionOk = version !== null && version === hostVersion;\n\n if (!manifest) {\n return {\n role,\n url,\n reachable: false,\n pluginVersion: null,\n ok: false,\n reason: reason ?? \"unreachable\",\n } satisfies FederationCompatRemote;\n }\n\n if (!versionOk) {\n return {\n role,\n url,\n reachable: true,\n pluginVersion: version,\n ok: false,\n reason: hostVersion\n ? `expected pluginVersion=${hostVersion} (host), got ${version ?? \"missing\"} — redeploy this plugin`\n : `host manifest missing pluginVersion`,\n } satisfies FederationCompatRemote;\n }\n\n const missingShared: string[] = [];\n const mismatchedShared: string[] = [];\n for (const hostDep of hostShared) {\n const remDep = manifest.shared?.find((s) => s.name === hostDep.name);\n if (!remDep) {\n missingShared.push(`${hostDep.name}@${hostDep.requiredVersion}`);\n continue;\n }\n if (!satisfiesConstraint(remDep.version ?? \"\", hostDep.requiredVersion!)) {\n mismatchedShared.push(\n `${hostDep.name}: remote=${remDep.version ?? \"?\"} hostReq=${hostDep.requiredVersion}`,\n );\n }\n if (isEffectCriticalSharedDep(hostDep.name)) {\n const hostVersion = hostDep.version ?? \"\";\n const remoteVersion = remDep.version ?? \"\";\n if (remoteVersion && remoteVersion !== hostVersion) {\n mismatchedShared.push(\n `${hostDep.name}: exact-version skew — remote=${remoteVersion} host=${hostVersion} — bundle was built against a different prerelease build; redeploy host and plugin together`,\n );\n }\n const remoteRequired =\n typeof remDep.requiredVersion === \"string\" ? remDep.requiredVersion.trim() : \"\";\n if (\n remoteRequired.length > 0 &&\n remoteRequired[0] !== \"^\" &&\n !satisfiesConstraint(hostVersion, remoteRequired)\n ) {\n mismatchedShared.push(\n `${hostDep.name}: train skew — host=${hostVersion} vs remote requiredVersion=${remoteRequired}`,\n );\n }\n }\n }\n\n const reasons = [\n ...missingShared.map((d) => `missing shared \"${d}\" required by host`),\n ...mismatchedShared,\n ];\n return {\n role,\n url,\n reachable: true,\n pluginVersion: version,\n ok: reasons.length === 0,\n reason: reasons[0],\n } satisfies FederationCompatRemote;\n }),\n );\n\n const remoteReports = settled.map((s, i) => {\n const placeholder = {\n role: remotes[i]!.role,\n url: remotes[i]!.url,\n reachable: false,\n pluginVersion: null,\n ok: false,\n };\n return s.status === \"fulfilled\" ? s.value : { ...placeholder, reason: String(s.reason) };\n });\n\n const ok =\n hostManifest !== null &&\n remoteReports.every((r) => r.ok && r.reachable && r.pluginVersion !== null);\n\n return {\n ok,\n hostVersion,\n hostReachable: hostManifest !== null,\n hostReason,\n remotes: remoteReports,\n };\n}\n\nexport function loadBosConfigForMfCheck(configPath: string): BosConfig {\n return JSON.parse(readFileSync(configPath, \"utf8\")) as BosConfig;\n}\n"],"mappings":";;;;;;;;;AAWA,IAAI,aAAwC;AAE5C,SAAgB,mCAAmC,IAA8B;CAC/E,IAAI,CAAC,MAAM,CAAE,GAAW,YAAY,WAAW,OAAO,IAAI;CAC1D,IAAK,GAAW,wCAAwC,MAAM;CAC9D,AAAC,GAAW,sCAAsC;CAElD,AAAC,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AAc;GAClB,MAAM,QAAQ,EAAE,CAAE;GAClB,KAAK,QAAQ,EAAE,CAAE;GACjB,WAAW;GACX,eAAe;GACf,IAAI;EACN;EACA,OAAO,EAAE,WAAW,cAAc,EAAE,QAAQ;GAAE,GAAG;GAAa,QAAQ,OAAO,EAAE,MAAM;EAAE;CACzF,CAAC;CAMD,OAAO;EACL,IAJA,iBAAiB,QACjB,cAAc,OAAO,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,kBAAkB,IAAI;EAI1E;EACA,eAAe,iBAAiB;EAChC;EACA,SAAS;CACX;AACF;AAEA,SAAgB,wBAAwB,YAA+B;CACrE,OAAO,KAAK,MAAM,aAAa,YAAY,MAAM,CAAC;AACpD"}
@@ -14,54 +14,61 @@ const isRetryable = (error) => {
14
14
  if (error instanceof FetchHttpError) return error.status >= 500;
15
15
  return false;
16
16
  };
17
- const runFetch = (url, init) => fetch(url, init);
18
- const fetchRawEff = (url, options) => effect.Effect.tryPromise({
19
- try: async () => {
17
+ const makeHttpFetch = (base) => {
18
+ const urlOf = (input) => typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
19
+ const attempt = (input, init) => effect.Effect.tryPromise({
20
+ try: (signal) => base(input, {
21
+ ...init,
22
+ signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal
23
+ }),
24
+ catch: (cause) => new FetchNetworkError({
25
+ url: urlOf(input),
26
+ cause
27
+ })
28
+ });
29
+ const get = (url, options) => {
20
30
  const timeoutMs = effect.Duration.toMillis(options?.timeout ?? DEFAULT_TIMEOUT);
21
- try {
22
- return await runFetch(url, {
23
- method: options?.method ?? "GET",
24
- headers: options?.headers,
25
- body: options?.body,
26
- redirect: options?.redirect,
27
- signal: AbortSignal.timeout(timeoutMs)
28
- });
29
- } catch (error) {
30
- if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) throw new FetchTimeoutError({ url });
31
- throw new FetchNetworkError({
32
- url,
33
- cause: error
34
- });
35
- }
36
- },
37
- catch: (error) => {
38
- if (error instanceof FetchNetworkError || error instanceof FetchTimeoutError) return error;
39
- return new FetchNetworkError({
31
+ const retries = options?.retries ?? DEFAULT_RETRIES;
32
+ const once = attempt(url, {
33
+ method: options?.method ?? "GET",
34
+ headers: options?.headers,
35
+ body: options?.body,
36
+ redirect: options?.redirect
37
+ }).pipe(effect.Effect.timeoutOrElse({
38
+ duration: timeoutMs,
39
+ orElse: () => effect.Effect.fail(new FetchTimeoutError({ url }))
40
+ }), effect.Effect.filterOrFail((response) => response.ok, (response) => new FetchHttpError({
40
41
  url,
41
- cause: error
42
- });
42
+ status: response.status,
43
+ statusText: response.statusText
44
+ })));
45
+ if (retries <= 0) return once;
46
+ return once.pipe(effect.Effect.retry({
47
+ schedule: effect.Schedule.exponential(EXPONENTIAL_BASE).pipe(effect.Schedule.upTo({
48
+ duration: EXPONENTIAL_CAP,
49
+ times: retries
50
+ }), effect.Schedule.jittered),
51
+ while: isRetryable
52
+ }));
53
+ };
54
+ return {
55
+ attempt,
56
+ get
57
+ };
58
+ };
59
+ const defaultHttpFetch = makeHttpFetch((url, init) => globalThis.fetch(url, init));
60
+ /**
61
+ * The HTTP seam for boot-path consumers (bundle resolution, federation
62
+ * loading, orchestrator deadlines): one resilience policy — interruption-
63
+ * backed deadlines, capped exponential jittered retry, typed errors — with
64
+ * the base fetch injectable so the bundle fetch interceptor can point it at
65
+ * the pre-patch `fetch` and not re-enter itself.
66
+ */
67
+ var HttpFetch = class HttpFetch extends effect.Context.Service()("everything-dev/http-client/HttpFetch") {
68
+ static layerWith(options) {
69
+ return effect.Layer.succeed(HttpFetch, makeHttpFetch(options.fetchImpl));
43
70
  }
44
- });
45
- const fetchEff = (url, options) => fetchRawEff(url, options).pipe(effect.Effect.filterOrFail((response) => response.ok, (response) => new FetchHttpError({
46
- url,
47
- status: response.status,
48
- statusText: response.statusText
49
- })));
50
- const retrySchedule = effect.Schedule.exponential(EXPONENTIAL_BASE).pipe(effect.Schedule.upTo({
51
- duration: EXPONENTIAL_CAP,
52
- times: DEFAULT_RETRIES
53
- }));
54
- const fetchWithRetryEff = (url, options) => {
55
- const retries = options?.retries ?? DEFAULT_RETRIES;
56
- if (retries <= 0) return fetchEff(url, options);
57
- const schedule = options?.retries !== void 0 ? effect.Schedule.exponential(EXPONENTIAL_BASE).pipe(effect.Schedule.upTo({
58
- duration: EXPONENTIAL_CAP,
59
- times: retries
60
- })) : retrySchedule;
61
- return fetchEff(url, options).pipe(effect.Effect.retry({
62
- schedule,
63
- while: isRetryable
64
- }));
71
+ static layer = effect.Layer.succeed(HttpFetch, defaultHttpFetch);
65
72
  };
66
73
  const getCache = /* @__PURE__ */ new Map();
67
74
  const GET_CACHE_TTL_MS = 3e4;
@@ -70,19 +77,28 @@ function isCacheable(_url, options) {
70
77
  if (options?.body) return false;
71
78
  return true;
72
79
  }
73
- const fetchResponse = (url, options) => effect.Effect.runPromise(fetchRawEff(url, options));
80
+ /** One raw fetch attempt with a deadline: returns the Response regardless of
81
+ * status; rejects on network failure or deadline expiry. */
82
+ const fetchRaw = (url, init, timeout = DEFAULT_TIMEOUT) => effect.Effect.runPromise(defaultHttpFetch.attempt(url, init).pipe(effect.Effect.timeoutOrElse({
83
+ duration: timeout,
84
+ orElse: () => effect.Effect.fail(new FetchTimeoutError({ url }))
85
+ })));
86
+ const fetchResponse = (url, options) => effect.Effect.runPromise(defaultHttpFetch.attempt(url, {
87
+ method: options?.method,
88
+ headers: options?.headers,
89
+ body: options?.body,
90
+ redirect: options?.redirect
91
+ }).pipe(effect.Effect.timeoutOrElse({
92
+ duration: options?.timeout ?? DEFAULT_TIMEOUT,
93
+ orElse: () => effect.Effect.fail(new FetchTimeoutError({ url }))
94
+ })));
74
95
  const fetchJsonOrNull = async (url, options) => {
75
96
  if (isCacheable(url, options)) {
76
97
  const cached = getCache.get(url);
77
98
  if (cached && cached.expiresAt > Date.now()) return cached.data;
78
99
  }
79
- const retries = options?.retries ?? DEFAULT_RETRIES;
80
- const eff = retries > 0 ? fetchWithRetryEff(url, {
81
- ...options,
82
- retries
83
- }) : fetchEff(url, options);
84
100
  try {
85
- const data = await (await effect.Effect.runPromise(eff)).json();
101
+ const data = await (await effect.Effect.runPromise(defaultHttpFetch.get(url, options))).json();
86
102
  if (isCacheable(url, options)) getCache.set(url, {
87
103
  data,
88
104
  expiresAt: Date.now() + GET_CACHE_TTL_MS
@@ -99,7 +115,8 @@ const fetchJsonOrNull = async (url, options) => {
99
115
  exports.FetchHttpError = FetchHttpError;
100
116
  exports.FetchNetworkError = FetchNetworkError;
101
117
  exports.FetchTimeoutError = FetchTimeoutError;
118
+ exports.HttpFetch = HttpFetch;
102
119
  exports.fetchJsonOrNull = fetchJsonOrNull;
120
+ exports.fetchRaw = fetchRaw;
103
121
  exports.fetchResponse = fetchResponse;
104
- exports.fetchWithRetryEff = fetchWithRetryEff;
105
122
  //# sourceMappingURL=http-client.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"http-client.cjs","names":["Data","Duration","Effect","Schedule"],"sources":["../src/http-client.ts"],"sourcesContent":["import { Data, Duration, Effect, Schedule } from \"effect\";\n\n// --- Tagged errors ---\n\nexport class FetchNetworkError extends Data.TaggedError(\"FetchNetworkError\")<{\n url: string;\n cause: unknown;\n}> {}\n\nexport class FetchTimeoutError extends Data.TaggedError(\"FetchTimeoutError\")<{\n url: string;\n}> {}\n\nexport class FetchHttpError extends Data.TaggedError(\"FetchHttpError\")<{\n url: string;\n status: number;\n statusText: string;\n}> {}\n\nexport type FetchError = FetchNetworkError | FetchTimeoutError | FetchHttpError;\n\n// --- Options ---\n\nexport interface FetchOptions {\n method?: string;\n headers?: Record<string, string>;\n body?: BodyInit;\n redirect?: RequestRedirect;\n timeout?: Duration.Input;\n}\n\nexport interface FetchWithRetryOptions extends FetchOptions {\n retries?: number;\n}\n\n// --- Defaults ---\n\nconst DEFAULT_TIMEOUT = \"10 seconds\";\nconst DEFAULT_RETRIES = 3;\n\nconst EXPONENTIAL_BASE = Duration.seconds(1);\nconst EXPONENTIAL_CAP = Duration.seconds(15);\n\n// --- Helpers ---\n\nconst isRetryable = (error: FetchError): boolean => {\n if (error instanceof FetchNetworkError) return true;\n if (error instanceof FetchTimeoutError) return true;\n if (error instanceof FetchHttpError) return error.status >= 500;\n return false;\n};\n\n// --- Low-level: just timeout + error classification, returns Response regardless of HTTP status ---\n\nconst runFetch = (url: string, init?: RequestInit): Promise<Response> => fetch(url, init);\n\nconst fetchRawEff = (\n url: string,\n options?: FetchOptions,\n): Effect.Effect<Response, FetchNetworkError | FetchTimeoutError> =>\n Effect.tryPromise({\n try: async () => {\n const timeoutMs = Duration.toMillis(options?.timeout ?? DEFAULT_TIMEOUT);\n try {\n return await runFetch(url, {\n method: options?.method ?? \"GET\",\n headers: options?.headers,\n body: options?.body,\n redirect: options?.redirect,\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n if (\n error instanceof Error &&\n (error.name === \"AbortError\" || error.name === \"TimeoutError\")\n ) {\n throw new FetchTimeoutError({ url });\n }\n throw new FetchNetworkError({ url, cause: error });\n }\n },\n catch: (error) => {\n if (error instanceof FetchNetworkError || error instanceof FetchTimeoutError) {\n return error;\n }\n return new FetchNetworkError({ url, cause: error });\n },\n });\n\n// --- Adds HTTP status checking: non-2xx becomes FetchHttpError ---\n\nconst fetchEff = (url: string, options?: FetchOptions): Effect.Effect<Response, FetchError> =>\n fetchRawEff(url, options).pipe(\n Effect.filterOrFail(\n (response) => response.ok,\n (response) =>\n new FetchHttpError({ url, status: response.status, statusText: response.statusText }),\n ),\n );\n\n// --- With retry ---\n\nconst retrySchedule = Schedule.exponential(EXPONENTIAL_BASE).pipe(\n Schedule.upTo({ duration: EXPONENTIAL_CAP, times: DEFAULT_RETRIES }),\n);\n\nexport const fetchWithRetryEff = (\n url: string,\n options?: FetchWithRetryOptions,\n): Effect.Effect<Response, FetchError> => {\n const retries = options?.retries ?? DEFAULT_RETRIES;\n\n if (retries <= 0) return fetchEff(url, options);\n\n const schedule =\n options?.retries !== undefined\n ? Schedule.exponential(EXPONENTIAL_BASE).pipe(\n Schedule.upTo({ duration: EXPONENTIAL_CAP, times: retries }),\n )\n : retrySchedule;\n\n return fetchEff(url, options).pipe(\n Effect.retry({\n schedule,\n while: isRetryable,\n }),\n );\n};\n\n// --- In-memory GET cache (per-process, prevents duplicate round trips) ---\n\nconst getCache = new Map<string, { data: unknown; expiresAt: number }>();\nconst GET_CACHE_TTL_MS = 30_000;\n\nexport function clearHttpCache(): void {\n getCache.clear();\n}\n\nfunction isCacheable(_url: string, options?: FetchWithRetryOptions): boolean {\n if (options?.method && options.method !== \"GET\") return false;\n if (options?.body) return false;\n return true;\n}\n\n// --- Promise wrappers (bridge for non-Effect code) ---\n\nexport const fetchResponse = (url: string, options?: FetchOptions): Promise<Response> =>\n Effect.runPromise(fetchRawEff(url, options));\n\nexport const fetchJsonOrNull = async <T>(\n url: string,\n options?: FetchWithRetryOptions,\n): Promise<T | null> => {\n if (isCacheable(url, options)) {\n const cached = getCache.get(url);\n if (cached && cached.expiresAt > Date.now()) {\n return cached.data as T;\n }\n }\n\n const retries = options?.retries ?? DEFAULT_RETRIES;\n const eff =\n retries > 0 ? fetchWithRetryEff(url, { ...options, retries }) : fetchEff(url, options);\n\n try {\n const res = await Effect.runPromise(eff);\n const data = (await res.json()) as T;\n if (isCacheable(url, options)) {\n getCache.set(url, { data, expiresAt: Date.now() + GET_CACHE_TTL_MS });\n }\n return data;\n } catch (error) {\n const msg =\n error instanceof FetchNetworkError\n ? `[http] Network error: ${error.url} — ${String(error.cause)}`\n : error instanceof FetchTimeoutError\n ? `[http] Timeout: ${error.url}`\n : error instanceof FetchHttpError\n ? `[http] HTTP ${error.status}: ${error.url}`\n : `[http] Unknown error while fetching ${url}`;\n console.error(msg);\n return null;\n }\n};\n"],"mappings":";;;AAIA,IAAa,oBAAb,cAAuCA,YAAK,YAAY,mBAAmB,CAAC,CAGzE,CAAC;AAEJ,IAAa,oBAAb,cAAuCA,YAAK,YAAY,mBAAmB,CAAC,CAE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AM,MACJ,iBAAiB,oBACb,yBAAyB,MAAM,IAAI,KAAK,OAAO,MAAM,KAAK,MAC1D,iBAAiB,oBACf,mBAAmB,MAAM,QACzB,iBAAiB,iBACf,eAAe,MAAM,OAAO,IAAI,MAAM,QACtC,uCAAuC;EACjD,QAAQ,MAAM,GAAG;EACjB,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"http-client.cjs","names":["Data","Duration","Effect","Schedule","Context","Layer"],"sources":["../src/http-client.ts"],"sourcesContent":["import { Context, Data, Duration, Effect, Layer, Schedule } from \"effect\";\n\n// --- Tagged errors ---\n\nexport class FetchNetworkError extends Data.TaggedError(\"FetchNetworkError\")<{\n url: string;\n cause: unknown;\n}> {}\n\nexport class FetchTimeoutError extends Data.TaggedError(\"FetchTimeoutError\")<{\n url: string;\n}> {}\n\nexport class FetchHttpError extends Data.TaggedError(\"FetchHttpError\")<{\n url: string;\n status: number;\n statusText: string;\n}> {}\n\nexport type FetchError = FetchNetworkError | FetchTimeoutError | FetchHttpError;\n\n// --- Options ---\n\nexport interface FetchOptions {\n method?: string;\n headers?: Record<string, string>;\n body?: BodyInit;\n redirect?: RequestRedirect;\n timeout?: Duration.Input;\n}\n\nexport interface FetchWithRetryOptions extends FetchOptions {\n retries?: number;\n}\n\n// --- Defaults ---\n\nconst DEFAULT_TIMEOUT = \"10 seconds\";\nconst DEFAULT_RETRIES = 3;\n\nconst EXPONENTIAL_BASE = Duration.seconds(1);\nconst EXPONENTIAL_CAP = Duration.seconds(15);\n\ntype FetchImpl = typeof globalThis.fetch;\n\n// --- Helpers ---\n\nconst isRetryable = (error: FetchError): boolean => {\n if (error instanceof FetchNetworkError) return true;\n if (error instanceof FetchTimeoutError) return true;\n if (error instanceof FetchHttpError) return error.status >= 500;\n return false;\n};\n\nexport interface HttpFetchShape {\n /** One network attempt: no status assertion, no internal deadline. The\n * fiber's signal is composed with any caller-provided signal, so an\n * `Effect.timeout` around the call aborts the in-flight request, and a\n * caller-initiated cancellation still wins. */\n readonly attempt: (\n input: string | URL | Request,\n init?: RequestInit,\n ) => Effect.Effect<Response, FetchNetworkError>;\n /** attempt + deadline + ok assertion (non-2xx → `FetchHttpError`) + capped\n * exponential jittered retry (5xx/network/timeout retried, 4xx not). */\n readonly get: (\n url: string,\n options?: FetchWithRetryOptions,\n ) => Effect.Effect<Response, FetchError>;\n}\n\nconst makeHttpFetch = (\n base: (input: string | URL | Request, init?: RequestInit) => Promise<Response>,\n): HttpFetchShape => {\n const urlOf = (input: string | URL | Request): string =>\n typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n\n const attempt = (\n input: string | URL | Request,\n init?: RequestInit,\n ): Effect.Effect<Response, FetchNetworkError> =>\n Effect.tryPromise({\n try: (signal) =>\n base(input, {\n ...init,\n signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal,\n }),\n catch: (cause) => new FetchNetworkError({ url: urlOf(input), cause }),\n });\n\n const get = (\n url: string,\n options?: FetchWithRetryOptions,\n ): Effect.Effect<Response, FetchError> => {\n const timeoutMs = Duration.toMillis(options?.timeout ?? DEFAULT_TIMEOUT);\n const retries = options?.retries ?? DEFAULT_RETRIES;\n const once = attempt(url, {\n method: options?.method ?? \"GET\",\n headers: options?.headers,\n body: options?.body,\n redirect: options?.redirect,\n }).pipe(\n Effect.timeoutOrElse({\n duration: timeoutMs,\n orElse: () => Effect.fail(new FetchTimeoutError({ url })),\n }),\n Effect.filterOrFail(\n (response) => response.ok,\n (response) =>\n new FetchHttpError({ url, status: response.status, statusText: response.statusText }),\n ),\n );\n if (retries <= 0) return once;\n return once.pipe(\n Effect.retry({\n schedule: Schedule.exponential(EXPONENTIAL_BASE).pipe(\n Schedule.upTo({ duration: EXPONENTIAL_CAP, times: retries }),\n Schedule.jittered,\n ),\n while: isRetryable,\n }),\n );\n };\n\n return { attempt, get };\n};\n\nconst defaultHttpFetch = makeHttpFetch((url, init) => globalThis.fetch(url, init));\n\n/**\n * The HTTP seam for boot-path consumers (bundle resolution, federation\n * loading, orchestrator deadlines): one resilience policy — interruption-\n * backed deadlines, capped exponential jittered retry, typed errors — with\n * the base fetch injectable so the bundle fetch interceptor can point it at\n * the pre-patch `fetch` and not re-enter itself.\n */\nexport class HttpFetch extends Context.Service<HttpFetch, HttpFetchShape>()(\n \"everything-dev/http-client/HttpFetch\",\n) {\n static layerWith(options: { fetchImpl: FetchImpl }): Layer.Layer<HttpFetch> {\n return Layer.succeed(HttpFetch, makeHttpFetch(options.fetchImpl));\n }\n\n static readonly layer: Layer.Layer<HttpFetch> = Layer.succeed(HttpFetch, defaultHttpFetch);\n}\n\n// --- In-memory GET cache (per-process, prevents duplicate round trips) ---\n\nconst getCache = new Map<string, { data: unknown; expiresAt: number }>();\nconst GET_CACHE_TTL_MS = 30_000;\n\nexport function clearHttpCache(): void {\n getCache.clear();\n}\n\nfunction isCacheable(_url: string, options?: FetchWithRetryOptions): boolean {\n if (options?.method && options.method !== \"GET\") return false;\n if (options?.body) return false;\n return true;\n}\n\n// --- Promise wrappers (bridge for non-Effect code) — the ambient call-time\n// lookup means a boot fetch crossing the bundle interceptor still gains its\n// retry/deadline policy; the fiber-signal composition aborts the in-flight\n// request at the deadline. ---\n\n/** One raw fetch attempt with a deadline: returns the Response regardless of\n * status; rejects on network failure or deadline expiry. */\nexport const fetchRaw = (\n url: string,\n init?: RequestInit,\n timeout: Duration.Input = DEFAULT_TIMEOUT,\n): Promise<Response> =>\n Effect.runPromise(\n defaultHttpFetch.attempt(url, init).pipe(\n Effect.timeoutOrElse({\n duration: timeout,\n orElse: () => Effect.fail(new FetchTimeoutError({ url })),\n }),\n ),\n );\n\nexport const fetchResponse = (url: string, options?: FetchOptions): Promise<Response> =>\n Effect.runPromise(\n defaultHttpFetch\n .attempt(url, {\n method: options?.method,\n headers: options?.headers,\n body: options?.body,\n redirect: options?.redirect,\n })\n .pipe(\n Effect.timeoutOrElse({\n duration: options?.timeout ?? DEFAULT_TIMEOUT,\n orElse: () => Effect.fail(new FetchTimeoutError({ url })),\n }),\n ),\n );\n\nexport const fetchJsonOrNull = async <T>(\n url: string,\n options?: FetchWithRetryOptions,\n): Promise<T | null> => {\n if (isCacheable(url, options)) {\n const cached = getCache.get(url);\n if (cached && cached.expiresAt > Date.now()) {\n return cached.data as T;\n }\n }\n\n try {\n const res = await Effect.runPromise(defaultHttpFetch.get(url, options));\n const data = (await res.json()) as T;\n if (isCacheable(url, options)) {\n getCache.set(url, { data, expiresAt: Date.now() + GET_CACHE_TTL_MS });\n }\n return data;\n } catch (error) {\n const msg =\n error instanceof FetchNetworkError\n ? `[http] Network error: ${error.url} — ${String(error.cause)}`\n : error instanceof FetchTimeoutError\n ? `[http] Timeout: ${error.url}`\n : error instanceof FetchHttpError\n ? `[http] HTTP ${error.status}: ${error.url}`\n : `[http] Unknown error while fetching ${url}`;\n console.error(msg);\n return null;\n }\n};\n\nexport const fetchWithRetryEff = (\n url: string,\n options?: FetchWithRetryOptions,\n): Effect.Effect<Response, FetchError> => defaultHttpFetch.get(url, options);\n"],"mappings":";;;AAIA,IAAa,oBAAb,cAAuCA,YAAK,YAAY,mBAAmB,CAAC,CAGzE,CAAC;AAEJ,IAAa,oBAAb,cAAuCA,YAAK,YAAY,mBAAmB,CAAC,CAEzE,CAAC;AAEJ,IAAa,iBAAb,cAAoCA,YAAK,YAAY,gBAAgB,CAAC,CAInE,CAAC;AAoBJ,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AAExB,MAAM,mBAAmBC,gBAAS,QAAQ,CAAC;AAC3C,MAAM,kBAAkBA,gBAAS,QAAQ,EAAE;AAM3C,MAAM,eAAe,UAA+B;CAClD,IAAI,iBAAiB,mBAAmB,OAAO;CAC/C,IAAI,iBAAiB,mBAAmB,OAAO;CAC/C,IAAI,iBAAiB,gBAAgB,OAAO,MAAM,UAAU;CAC5D,OAAO;AACT;AAmBA,MAAM,iBACJ,SACmB;CACnB,MAAM,SAAS,UACb,OAAO,UAAU,WAAW,QAAQ,iBAAiB,MAAM,MAAM,OAAO,MAAM;CAEh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,MAC1D,iBAAiB,oBACf,mBAAmB,MAAM,QACzB,iBAAiB,iBACf,eAAe,MAAM,OAAO,IAAI,MAAM,QACtC,uCAAuC;EACjD,QAAQ,MAAM,GAAG;EACjB,OAAO;CACT;AACF"}
@@ -1,4 +1,4 @@
1
- import { Data, Duration, Effect, Schedule } from "effect";
1
+ import { Context, Data, Duration, Effect, Layer, Schedule } from "effect";
2
2
 
3
3
  //#region src/http-client.ts
4
4
  var FetchNetworkError = class extends Data.TaggedError("FetchNetworkError") {};
@@ -14,54 +14,61 @@ const isRetryable = (error) => {
14
14
  if (error instanceof FetchHttpError) return error.status >= 500;
15
15
  return false;
16
16
  };
17
- const runFetch = (url, init) => fetch(url, init);
18
- const fetchRawEff = (url, options) => Effect.tryPromise({
19
- try: async () => {
17
+ const makeHttpFetch = (base) => {
18
+ const urlOf = (input) => typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
19
+ const attempt = (input, init) => Effect.tryPromise({
20
+ try: (signal) => base(input, {
21
+ ...init,
22
+ signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal
23
+ }),
24
+ catch: (cause) => new FetchNetworkError({
25
+ url: urlOf(input),
26
+ cause
27
+ })
28
+ });
29
+ const get = (url, options) => {
20
30
  const timeoutMs = Duration.toMillis(options?.timeout ?? DEFAULT_TIMEOUT);
21
- try {
22
- return await runFetch(url, {
23
- method: options?.method ?? "GET",
24
- headers: options?.headers,
25
- body: options?.body,
26
- redirect: options?.redirect,
27
- signal: AbortSignal.timeout(timeoutMs)
28
- });
29
- } catch (error) {
30
- if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) throw new FetchTimeoutError({ url });
31
- throw new FetchNetworkError({
32
- url,
33
- cause: error
34
- });
35
- }
36
- },
37
- catch: (error) => {
38
- if (error instanceof FetchNetworkError || error instanceof FetchTimeoutError) return error;
39
- return new FetchNetworkError({
31
+ const retries = options?.retries ?? DEFAULT_RETRIES;
32
+ const once = attempt(url, {
33
+ method: options?.method ?? "GET",
34
+ headers: options?.headers,
35
+ body: options?.body,
36
+ redirect: options?.redirect
37
+ }).pipe(Effect.timeoutOrElse({
38
+ duration: timeoutMs,
39
+ orElse: () => Effect.fail(new FetchTimeoutError({ url }))
40
+ }), Effect.filterOrFail((response) => response.ok, (response) => new FetchHttpError({
40
41
  url,
41
- cause: error
42
- });
42
+ status: response.status,
43
+ statusText: response.statusText
44
+ })));
45
+ if (retries <= 0) return once;
46
+ return once.pipe(Effect.retry({
47
+ schedule: Schedule.exponential(EXPONENTIAL_BASE).pipe(Schedule.upTo({
48
+ duration: EXPONENTIAL_CAP,
49
+ times: retries
50
+ }), Schedule.jittered),
51
+ while: isRetryable
52
+ }));
53
+ };
54
+ return {
55
+ attempt,
56
+ get
57
+ };
58
+ };
59
+ const defaultHttpFetch = makeHttpFetch((url, init) => globalThis.fetch(url, init));
60
+ /**
61
+ * The HTTP seam for boot-path consumers (bundle resolution, federation
62
+ * loading, orchestrator deadlines): one resilience policy — interruption-
63
+ * backed deadlines, capped exponential jittered retry, typed errors — with
64
+ * the base fetch injectable so the bundle fetch interceptor can point it at
65
+ * the pre-patch `fetch` and not re-enter itself.
66
+ */
67
+ var HttpFetch = class HttpFetch extends Context.Service()("everything-dev/http-client/HttpFetch") {
68
+ static layerWith(options) {
69
+ return Layer.succeed(HttpFetch, makeHttpFetch(options.fetchImpl));
43
70
  }
44
- });
45
- const fetchEff = (url, options) => fetchRawEff(url, options).pipe(Effect.filterOrFail((response) => response.ok, (response) => new FetchHttpError({
46
- url,
47
- status: response.status,
48
- statusText: response.statusText
49
- })));
50
- const retrySchedule = Schedule.exponential(EXPONENTIAL_BASE).pipe(Schedule.upTo({
51
- duration: EXPONENTIAL_CAP,
52
- times: DEFAULT_RETRIES
53
- }));
54
- const fetchWithRetryEff = (url, options) => {
55
- const retries = options?.retries ?? DEFAULT_RETRIES;
56
- if (retries <= 0) return fetchEff(url, options);
57
- const schedule = options?.retries !== void 0 ? Schedule.exponential(EXPONENTIAL_BASE).pipe(Schedule.upTo({
58
- duration: EXPONENTIAL_CAP,
59
- times: retries
60
- })) : retrySchedule;
61
- return fetchEff(url, options).pipe(Effect.retry({
62
- schedule,
63
- while: isRetryable
64
- }));
71
+ static layer = Layer.succeed(HttpFetch, defaultHttpFetch);
65
72
  };
66
73
  const getCache = /* @__PURE__ */ new Map();
67
74
  const GET_CACHE_TTL_MS = 3e4;
@@ -70,19 +77,28 @@ function isCacheable(_url, options) {
70
77
  if (options?.body) return false;
71
78
  return true;
72
79
  }
73
- const fetchResponse = (url, options) => Effect.runPromise(fetchRawEff(url, options));
80
+ /** One raw fetch attempt with a deadline: returns the Response regardless of
81
+ * status; rejects on network failure or deadline expiry. */
82
+ const fetchRaw = (url, init, timeout = DEFAULT_TIMEOUT) => Effect.runPromise(defaultHttpFetch.attempt(url, init).pipe(Effect.timeoutOrElse({
83
+ duration: timeout,
84
+ orElse: () => Effect.fail(new FetchTimeoutError({ url }))
85
+ })));
86
+ const fetchResponse = (url, options) => Effect.runPromise(defaultHttpFetch.attempt(url, {
87
+ method: options?.method,
88
+ headers: options?.headers,
89
+ body: options?.body,
90
+ redirect: options?.redirect
91
+ }).pipe(Effect.timeoutOrElse({
92
+ duration: options?.timeout ?? DEFAULT_TIMEOUT,
93
+ orElse: () => Effect.fail(new FetchTimeoutError({ url }))
94
+ })));
74
95
  const fetchJsonOrNull = async (url, options) => {
75
96
  if (isCacheable(url, options)) {
76
97
  const cached = getCache.get(url);
77
98
  if (cached && cached.expiresAt > Date.now()) return cached.data;
78
99
  }
79
- const retries = options?.retries ?? DEFAULT_RETRIES;
80
- const eff = retries > 0 ? fetchWithRetryEff(url, {
81
- ...options,
82
- retries
83
- }) : fetchEff(url, options);
84
100
  try {
85
- const data = await (await Effect.runPromise(eff)).json();
101
+ const data = await (await Effect.runPromise(defaultHttpFetch.get(url, options))).json();
86
102
  if (isCacheable(url, options)) getCache.set(url, {
87
103
  data,
88
104
  expiresAt: Date.now() + GET_CACHE_TTL_MS
@@ -96,5 +112,5 @@ const fetchJsonOrNull = async (url, options) => {
96
112
  };
97
113
 
98
114
  //#endregion
99
- export { FetchHttpError, FetchNetworkError, FetchTimeoutError, fetchJsonOrNull, fetchResponse, fetchWithRetryEff };
115
+ export { FetchHttpError, FetchNetworkError, FetchTimeoutError, HttpFetch, fetchJsonOrNull, fetchRaw, fetchResponse };
100
116
  //# sourceMappingURL=http-client.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"http-client.mjs","names":[],"sources":["../src/http-client.ts"],"sourcesContent":["import { Data, Duration, Effect, Schedule } from \"effect\";\n\n// --- Tagged errors ---\n\nexport class FetchNetworkError extends Data.TaggedError(\"FetchNetworkError\")<{\n url: string;\n cause: unknown;\n}> {}\n\nexport class FetchTimeoutError extends Data.TaggedError(\"FetchTimeoutError\")<{\n url: string;\n}> {}\n\nexport class FetchHttpError extends Data.TaggedError(\"FetchHttpError\")<{\n url: string;\n status: number;\n statusText: string;\n}> {}\n\nexport type FetchError = FetchNetworkError | FetchTimeoutError | FetchHttpError;\n\n// --- Options ---\n\nexport interface FetchOptions {\n method?: string;\n headers?: Record<string, string>;\n body?: BodyInit;\n redirect?: RequestRedirect;\n timeout?: Duration.Input;\n}\n\nexport interface FetchWithRetryOptions extends FetchOptions {\n retries?: number;\n}\n\n// --- Defaults ---\n\nconst DEFAULT_TIMEOUT = \"10 seconds\";\nconst DEFAULT_RETRIES = 3;\n\nconst EXPONENTIAL_BASE = Duration.seconds(1);\nconst EXPONENTIAL_CAP = Duration.seconds(15);\n\n// --- Helpers ---\n\nconst isRetryable = (error: FetchError): boolean => {\n if (error instanceof FetchNetworkError) return true;\n if (error instanceof FetchTimeoutError) return true;\n if (error instanceof FetchHttpError) return error.status >= 500;\n return false;\n};\n\n// --- Low-level: just timeout + error classification, returns Response regardless of HTTP status ---\n\nconst runFetch = (url: string, init?: RequestInit): Promise<Response> => fetch(url, init);\n\nconst fetchRawEff = (\n url: string,\n options?: FetchOptions,\n): Effect.Effect<Response, FetchNetworkError | FetchTimeoutError> =>\n Effect.tryPromise({\n try: async () => {\n const timeoutMs = Duration.toMillis(options?.timeout ?? DEFAULT_TIMEOUT);\n try {\n return await runFetch(url, {\n method: options?.method ?? \"GET\",\n headers: options?.headers,\n body: options?.body,\n redirect: options?.redirect,\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n if (\n error instanceof Error &&\n (error.name === \"AbortError\" || error.name === \"TimeoutError\")\n ) {\n throw new FetchTimeoutError({ url });\n }\n throw new FetchNetworkError({ url, cause: error });\n }\n },\n catch: (error) => {\n if (error instanceof FetchNetworkError || error instanceof FetchTimeoutError) {\n return error;\n }\n return new FetchNetworkError({ url, cause: error });\n },\n });\n\n// --- Adds HTTP status checking: non-2xx becomes FetchHttpError ---\n\nconst fetchEff = (url: string, options?: FetchOptions): Effect.Effect<Response, FetchError> =>\n fetchRawEff(url, options).pipe(\n Effect.filterOrFail(\n (response) => response.ok,\n (response) =>\n new FetchHttpError({ url, status: response.status, statusText: response.statusText }),\n ),\n );\n\n// --- With retry ---\n\nconst retrySchedule = Schedule.exponential(EXPONENTIAL_BASE).pipe(\n Schedule.upTo({ duration: EXPONENTIAL_CAP, times: DEFAULT_RETRIES }),\n);\n\nexport const fetchWithRetryEff = (\n url: string,\n options?: FetchWithRetryOptions,\n): Effect.Effect<Response, FetchError> => {\n const retries = options?.retries ?? DEFAULT_RETRIES;\n\n if (retries <= 0) return fetchEff(url, options);\n\n const schedule =\n options?.retries !== undefined\n ? Schedule.exponential(EXPONENTIAL_BASE).pipe(\n Schedule.upTo({ duration: EXPONENTIAL_CAP, times: retries }),\n )\n : retrySchedule;\n\n return fetchEff(url, options).pipe(\n Effect.retry({\n schedule,\n while: isRetryable,\n }),\n );\n};\n\n// --- In-memory GET cache (per-process, prevents duplicate round trips) ---\n\nconst getCache = new Map<string, { data: unknown; expiresAt: number }>();\nconst GET_CACHE_TTL_MS = 30_000;\n\nexport function clearHttpCache(): void {\n getCache.clear();\n}\n\nfunction isCacheable(_url: string, options?: FetchWithRetryOptions): boolean {\n if (options?.method && options.method !== \"GET\") return false;\n if (options?.body) return false;\n return true;\n}\n\n// --- Promise wrappers (bridge for non-Effect code) ---\n\nexport const fetchResponse = (url: string, options?: FetchOptions): Promise<Response> =>\n Effect.runPromise(fetchRawEff(url, options));\n\nexport const fetchJsonOrNull = async <T>(\n url: string,\n options?: FetchWithRetryOptions,\n): Promise<T | null> => {\n if (isCacheable(url, options)) {\n const cached = getCache.get(url);\n if (cached && cached.expiresAt > Date.now()) {\n return cached.data as T;\n }\n }\n\n const retries = options?.retries ?? DEFAULT_RETRIES;\n const eff =\n retries > 0 ? fetchWithRetryEff(url, { ...options, retries }) : fetchEff(url, options);\n\n try {\n const res = await Effect.runPromise(eff);\n const data = (await res.json()) as T;\n if (isCacheable(url, options)) {\n getCache.set(url, { data, expiresAt: Date.now() + GET_CACHE_TTL_MS });\n }\n return data;\n } catch (error) {\n const msg =\n error instanceof FetchNetworkError\n ? `[http] Network error: ${error.url} — ${String(error.cause)}`\n : error instanceof FetchTimeoutError\n ? `[http] Timeout: ${error.url}`\n : error instanceof FetchHttpError\n ? `[http] HTTP ${error.status}: ${error.url}`\n : `[http] Unknown error while fetching ${url}`;\n console.error(msg);\n return null;\n }\n};\n"],"mappings":";;;AAIA,IAAa,oBAAb,cAAuC,KAAK,YAAY,mBAAmB,CAAC,CAGzE,CAAC;AAEJ,IAAa,oBAAb,cAAuC,KAAK,YAAY,mBAAmB,CAAC,CAEzE,CAAC;AAEJ,IAAa,iBAAb,cAAoC,KAAK,YAAY,gBAAgB,CAAC,CAInE,CAAC;AAoBJ,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AAExB,MAAM,mBAAmB,SAAS,QAAQ,CAAC;AAC3C,MAAM,kBAAkB,SAAS,QAAQ,EAAE;AAI3C,MAAM,eAAe,UAA+B;CAClD,IAAI,iBAAiB,mBAAmB,OAAO;CAC/C,IAAI,iBAAiB,mBAAmB,OAAO;CAC/C,IAAI,iBAAiB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D,IACA;CAEN,OAAO,SAAS,KAAK,OAAO,CAAC,CAAC,KAC5B,OAAO,MAAM;EACX;EACA,OAAO;CACT,CAAC,CACH;AACF;AAIA,MAAM,2BAAW,IAAI,IAAkD;AACvE,MAAM,mBAAmB;AAMzB,SAAS,YAAY,MAAc,SAA0C;CAC3E,IAAI,SAAS,UAAU,QAAQ,WAAW,OAAO,OAAO;CACxD,IAAI,SAAS,MAAM,OAAO;CAC1B,OAAO;AACT;AAIA,MAAa,iBAAiB,KAAa,YACzC,OAAO,WAAW,YAAY,KAAK,OAAO,CAAC;AAE7C,MAAa,kBAAkB,OAC7B,KACA,YACsB;CACtB,IAAI,YAAY,KAAK,OAAO,GAAG;EAC7B,MAAM,SAAS,SAAS,IAAI,GAAG;EAC/B,IAAI,UAAU,OAAO,YAAY,KAAK,IAAI,GACxC,OAAO,OAAO;CAElB;CAEA,MAAM,UAAU,SAAS,WAAW;CACpC,MAAM,MACJ,UAAU,IAAI,kBAAkB,KAAK;EAAE,GAAG;EAAS;CAAQ,CAAC,IAAI,SAAS,KAAK,OAAO;CAEvF,IAAI;EAEF,MAAM,OAAQ,OAAM,MADF,OAAO,WAAW,GAAG,EAChB,CAAC,KAAK;EAC7B,IAAI,YAAY,KAAK,OAAO,GAC1B,SAAS,IAAI,KAAK;GAAE;GAAM,WAAW,KAAK,IAAI,IAAI;EAAiB,CAAC;EAEtE,OAAO;CACT,SAAS,OAAO;EACd,MAAM,MACJ,iBAAiB,oBACb,yBAAyB,MAAM,IAAI,KAAK,OAAO,MAAM,KAAK,MAC1D,iBAAiB,oBACf,mBAAmB,MAAM,QACzB,iBAAiB,iBACf,eAAe,MAAM,OAAO,IAAI,MAAM,QACtC,uCAAuC;EACjD,QAAQ,MAAM,GAAG;EACjB,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"http-client.mjs","names":[],"sources":["../src/http-client.ts"],"sourcesContent":["import { Context, Data, Duration, Effect, Layer, Schedule } from \"effect\";\n\n// --- Tagged errors ---\n\nexport class FetchNetworkError extends Data.TaggedError(\"FetchNetworkError\")<{\n url: string;\n cause: unknown;\n}> {}\n\nexport class FetchTimeoutError extends Data.TaggedError(\"FetchTimeoutError\")<{\n url: string;\n}> {}\n\nexport class FetchHttpError extends Data.TaggedError(\"FetchHttpError\")<{\n url: string;\n status: number;\n statusText: string;\n}> {}\n\nexport type FetchError = FetchNetworkError | FetchTimeoutError | FetchHttpError;\n\n// --- Options ---\n\nexport interface FetchOptions {\n method?: string;\n headers?: Record<string, string>;\n body?: BodyInit;\n redirect?: RequestRedirect;\n timeout?: Duration.Input;\n}\n\nexport interface FetchWithRetryOptions extends FetchOptions {\n retries?: number;\n}\n\n// --- Defaults ---\n\nconst DEFAULT_TIMEOUT = \"10 seconds\";\nconst DEFAULT_RETRIES = 3;\n\nconst EXPONENTIAL_BASE = Duration.seconds(1);\nconst EXPONENTIAL_CAP = Duration.seconds(15);\n\ntype FetchImpl = typeof globalThis.fetch;\n\n// --- Helpers ---\n\nconst isRetryable = (error: FetchError): boolean => {\n if (error instanceof FetchNetworkError) return true;\n if (error instanceof FetchTimeoutError) return true;\n if (error instanceof FetchHttpError) return error.status >= 500;\n return false;\n};\n\nexport interface HttpFetchShape {\n /** One network attempt: no status assertion, no internal deadline. The\n * fiber's signal is composed with any caller-provided signal, so an\n * `Effect.timeout` around the call aborts the in-flight request, and a\n * caller-initiated cancellation still wins. */\n readonly attempt: (\n input: string | URL | Request,\n init?: RequestInit,\n ) => Effect.Effect<Response, FetchNetworkError>;\n /** attempt + deadline + ok assertion (non-2xx → `FetchHttpError`) + capped\n * exponential jittered retry (5xx/network/timeout retried, 4xx not). */\n readonly get: (\n url: string,\n options?: FetchWithRetryOptions,\n ) => Effect.Effect<Response, FetchError>;\n}\n\nconst makeHttpFetch = (\n base: (input: string | URL | Request, init?: RequestInit) => Promise<Response>,\n): HttpFetchShape => {\n const urlOf = (input: string | URL | Request): string =>\n typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n\n const attempt = (\n input: string | URL | Request,\n init?: RequestInit,\n ): Effect.Effect<Response, FetchNetworkError> =>\n Effect.tryPromise({\n try: (signal) =>\n base(input, {\n ...init,\n signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal,\n }),\n catch: (cause) => new FetchNetworkError({ url: urlOf(input), cause }),\n });\n\n const get = (\n url: string,\n options?: FetchWithRetryOptions,\n ): Effect.Effect<Response, FetchError> => {\n const timeoutMs = Duration.toMillis(options?.timeout ?? DEFAULT_TIMEOUT);\n const retries = options?.retries ?? DEFAULT_RETRIES;\n const once = attempt(url, {\n method: options?.method ?? \"GET\",\n headers: options?.headers,\n body: options?.body,\n redirect: options?.redirect,\n }).pipe(\n Effect.timeoutOrElse({\n duration: timeoutMs,\n orElse: () => Effect.fail(new FetchTimeoutError({ url })),\n }),\n Effect.filterOrFail(\n (response) => response.ok,\n (response) =>\n new FetchHttpError({ url, status: response.status, statusText: response.statusText }),\n ),\n );\n if (retries <= 0) return once;\n return once.pipe(\n Effect.retry({\n schedule: Schedule.exponential(EXPONENTIAL_BASE).pipe(\n Schedule.upTo({ duration: EXPONENTIAL_CAP, times: retries }),\n Schedule.jittered,\n ),\n while: isRetryable,\n }),\n );\n };\n\n return { attempt, get };\n};\n\nconst defaultHttpFetch = makeHttpFetch((url, init) => globalThis.fetch(url, init));\n\n/**\n * The HTTP seam for boot-path consumers (bundle resolution, federation\n * loading, orchestrator deadlines): one resilience policy — interruption-\n * backed deadlines, capped exponential jittered retry, typed errors — with\n * the base fetch injectable so the bundle fetch interceptor can point it at\n * the pre-patch `fetch` and not re-enter itself.\n */\nexport class HttpFetch extends Context.Service<HttpFetch, HttpFetchShape>()(\n \"everything-dev/http-client/HttpFetch\",\n) {\n static layerWith(options: { fetchImpl: FetchImpl }): Layer.Layer<HttpFetch> {\n return Layer.succeed(HttpFetch, makeHttpFetch(options.fetchImpl));\n }\n\n static readonly layer: Layer.Layer<HttpFetch> = Layer.succeed(HttpFetch, defaultHttpFetch);\n}\n\n// --- In-memory GET cache (per-process, prevents duplicate round trips) ---\n\nconst getCache = new Map<string, { data: unknown; expiresAt: number }>();\nconst GET_CACHE_TTL_MS = 30_000;\n\nexport function clearHttpCache(): void {\n getCache.clear();\n}\n\nfunction isCacheable(_url: string, options?: FetchWithRetryOptions): boolean {\n if (options?.method && options.method !== \"GET\") return false;\n if (options?.body) return false;\n return true;\n}\n\n// --- Promise wrappers (bridge for non-Effect code) — the ambient call-time\n// lookup means a boot fetch crossing the bundle interceptor still gains its\n// retry/deadline policy; the fiber-signal composition aborts the in-flight\n// request at the deadline. ---\n\n/** One raw fetch attempt with a deadline: returns the Response regardless of\n * status; rejects on network failure or deadline expiry. */\nexport const fetchRaw = (\n url: string,\n init?: RequestInit,\n timeout: Duration.Input = DEFAULT_TIMEOUT,\n): Promise<Response> =>\n Effect.runPromise(\n defaultHttpFetch.attempt(url, init).pipe(\n Effect.timeoutOrElse({\n duration: timeout,\n orElse: () => Effect.fail(new FetchTimeoutError({ url })),\n }),\n ),\n );\n\nexport const fetchResponse = (url: string, options?: FetchOptions): Promise<Response> =>\n Effect.runPromise(\n defaultHttpFetch\n .attempt(url, {\n method: options?.method,\n headers: options?.headers,\n body: options?.body,\n redirect: options?.redirect,\n })\n .pipe(\n Effect.timeoutOrElse({\n duration: options?.timeout ?? DEFAULT_TIMEOUT,\n orElse: () => Effect.fail(new FetchTimeoutError({ url })),\n }),\n ),\n );\n\nexport const fetchJsonOrNull = async <T>(\n url: string,\n options?: FetchWithRetryOptions,\n): Promise<T | null> => {\n if (isCacheable(url, options)) {\n const cached = getCache.get(url);\n if (cached && cached.expiresAt > Date.now()) {\n return cached.data as T;\n }\n }\n\n try {\n const res = await Effect.runPromise(defaultHttpFetch.get(url, options));\n const data = (await res.json()) as T;\n if (isCacheable(url, options)) {\n getCache.set(url, { data, expiresAt: Date.now() + GET_CACHE_TTL_MS });\n }\n return data;\n } catch (error) {\n const msg =\n error instanceof FetchNetworkError\n ? `[http] Network error: ${error.url} — ${String(error.cause)}`\n : error instanceof FetchTimeoutError\n ? `[http] Timeout: ${error.url}`\n : error instanceof FetchHttpError\n ? `[http] HTTP ${error.status}: ${error.url}`\n : `[http] Unknown error while fetching ${url}`;\n console.error(msg);\n return null;\n }\n};\n\nexport const fetchWithRetryEff = (\n url: string,\n options?: FetchWithRetryOptions,\n): Effect.Effect<Response, FetchError> => defaultHttpFetch.get(url, options);\n"],"mappings":";;;AAIA,IAAa,oBAAb,cAAuC,KAAK,YAAY,mBAAmB,CAAC,CAGzE,CAAC;AAEJ,IAAa,oBAAb,cAAuC,KAAK,YAAY,mBAAmB,CAAC,CAEzE,CAAC;AAEJ,IAAa,iBAAb,cAAoC,KAAK,YAAY,gBAAgB,CAAC,CAInE,CAAC;AAoBJ,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AAExB,MAAM,mBAAmB,SAAS,QAAQ,CAAC;AAC3C,MAAM,kBAAkB,SAAS,QAAQ,EAAE;AAM3C,MAAM,eAAe,UAA+B;CAClD,IAAI,iBAAiB,mBAAmB,OAAO;CAC/C,IAAI,iBAAiB,mBAAmB,OAAO;CAC/C,IAAI,iBAAiB,gBAAgB,OAAO,MAAM,UAAU;CAC5D,OAAO;AACT;AAmBA,MAAM,iBACJ,SACmB;CACnB,MAAM,SAAS,UACb,OAAO,UAAU,WAAW,QAAQ,iBAAiB,MAAM,MAAM,OAAO,MAAM;CAEhF,MAAM,WACJ,OACA,SAEA,OAAO,WAAW;EAChB,MAAM,WACJ,KAAK,OAAO;GACV,GAAG;GACH,QAAQ,MAAM,SAAS,YAAY,IAAI,CAAC,KAAK,QAAQ,MAAM,CAAC,IAAI;EAClE,CAAC;EACH,QAAQ,UAAU,IAAI,kBAAkB;GAAE,KAAK,MAAM,KAAK;GAAG;EAAM,CAAC;CACtE,CAAC;CAEH,MAAM,OACJ,KACA,YACwC;EACxC,MAAM,YAAY,SAAS,SAAS,SAAS,WAAW,eAAe;EACvE,MAAM,UAAU,SAAS,WAAW;EACpC,MAAM,OAAO,QA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AE,IAAI,CAAC,CAAC;AAC1D,CAAC,CACH,CACF;AAEF,MAAa,iBAAiB,KAAa,YACzC,OAAO,WACL,iBACG,QAAQ,KAAK;CACZ,QAAQ,SAAS;CACjB,SAAS,SAAS;CAClB,MAAM,SAAS;CACf,UAAU,SAAS;AACrB,CAAC,CAAC,CACD,KACC,OAAO,cAAc;CACnB,UAAU,SAAS,WAAW;CAC9B,cAAc,OAAO,KAAK,IAAI,kBAAkB,EAAE,IAAI,CAAC,CAAC;AAC1D,CAAC,CACH,CACJ;AAEF,MAAa,kBAAkB,OAC7B,KACA,YACsB;CACtB,IAAI,YAAY,KAAK,OAAO,GAAG;EAC7B,MAAM,SAAS,SAAS,IAAI,GAAG;EAC/B,IAAI,UAAU,OAAO,YAAY,KAAK,IAAI,GACxC,OAAO,OAAO;CAElB;CAEA,IAAI;EAEF,MAAM,OAAQ,OAAM,MADF,OAAO,WAAW,iBAAiB,IAAI,KAAK,OAAO,CAAC,EAC/C,CAAC,KAAK;EAC7B,IAAI,YAAY,KAAK,OAAO,GAC1B,SAAS,IAAI,KAAK;GAAE;GAAM,WAAW,KAAK,IAAI,IAAI;EAAiB,CAAC;EAEtE,OAAO;CACT,SAAS,OAAO;EACd,MAAM,MACJ,iBAAiB,oBACb,yBAAyB,MAAM,IAAI,KAAK,OAAO,MAAM,KAAK,MAC1D,iBAAiB,oBACf,mBAAmB,MAAM,QACzB,iBAAiB,iBACf,eAAe,MAAM,OAAO,IAAI,MAAM,QACtC,uCAAuC;EACjD,QAAQ,MAAM,GAAG;EACjB,OAAO;CACT;AACF"}
@@ -25,6 +25,14 @@ function resolveImageRef(input) {
25
25
  source: "repository"
26
26
  };
27
27
  }
28
+ /** Compose the runnable image ref: `image@sha256:…` when a digest exists,
29
+ * `image` alone otherwise. Never docker-run the bare ref in a deploy flow —
30
+ * the implicit `:latest` is held to the last stable release during
31
+ * prereleases (ADR 0021), which boots a different framework build than the
32
+ * one this train pinned. */
33
+ function imageRefWithDigest(image, digest) {
34
+ return digest ? `${image}@${digest}` : image;
35
+ }
28
36
  async function hasDocker() {
29
37
  try {
30
38
  return (await require_run.run("docker", [
@@ -252,6 +260,7 @@ exports.buildAndPushImage = buildAndPushImage;
252
260
  exports.computeImageTags = computeImageTags;
253
261
  exports.deployImageToRailway = deployImageToRailway;
254
262
  exports.hasDocker = hasDocker;
263
+ exports.imageRefWithDigest = imageRefWithDigest;
255
264
  exports.isValidImageDigest = isValidImageDigest;
256
265
  exports.resolveDeployImagePlan = resolveDeployImagePlan;
257
266
  exports.resolveImageRef = resolveImageRef;
@@ -1 +1 @@
1
- {"version":3,"file":"image-deploy.cjs","names":["run","readFileSync","join","colors","icons"],"sources":["../src/image-deploy.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { run } from \"./utils/run\";\nimport { colors, icons } from \"./utils/theme\";\n\nexport interface ResolvedImageRef {\n image: string;\n source: \"ci\" | \"env\" | \"repository\";\n}\n\n/**\n * Image reference resolution precedence (ADR 0021): `ci.image` in\n * bos.config.json → `BOS_IMAGE` env → derived from `repository`.\n */\nexport function resolveImageRef(input: {\n ciImage?: string;\n repository?: string;\n env?: Record<string, string | undefined>;\n}): ResolvedImageRef | undefined {\n const envImage = input.env?.BOS_IMAGE;\n if (input.ciImage) return { image: input.ciImage, source: \"ci\" };\n if (envImage) return { image: envImage, source: \"env\" };\n\n const repo = input.repository\n ?.replace(/^https?:\\/\\/(www\\.)?github\\.com\\//i, \"\")\n .replace(/\\.git$/i, \"\")\n .replace(/\\/+$/, \"\")\n .toLowerCase();\n if (!repo?.includes(\"/\") || repo.split(\"/\").length !== 2) return undefined;\n return { image: `ghcr.io/${repo}`, source: \"repository\" };\n}\n\nexport async function hasDocker(): Promise<boolean> {\n try {\n const result = await run(\"docker\", [\"info\", \"--format\", \"{{.ServerVersion}}\"], {\n capture: true,\n });\n return result?.exitCode === 0;\n } catch {\n return false;\n }\n}\n\nfunction parseDigest(pushOutput: string): string | undefined {\n const match = pushOutput.match(/digest:\\s*(sha256:[a-f0-9]+)/i);\n return match?.[1];\n}\n\nconst SEMVER_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?$/;\n\n/**\n * The runtime framework version baked into the image is the workspace source's\n * `everything-dev` package version — the image builds from `configDir`, so that\n * file is the truth. Missing (child repos without the workspace) → undefined.\n */\nfunction readFrameworkVersion(configDir: string): string | undefined {\n try {\n const raw = readFileSync(\n join(configDir, \"packages\", \"everything-dev\", \"package.json\"),\n \"utf-8\",\n );\n const pkg = JSON.parse(raw) as { version?: unknown };\n return typeof pkg.version === \"string\" && SEMVER_PATTERN.test(pkg.version)\n ? pkg.version\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface ImageTags {\n /** Exact refs to build and push, in push order (latest excluded). */\n tags: string[];\n /** Push `:latest` after the pinned tags. */\n pushLatest: boolean;\n /** Human-readable reason when `latest` is held. */\n latestHoldReason?: string;\n /** Push `:rc` after the pinned tags — the floating prerelease-train ref. */\n pushRc: boolean;\n}\n\n/**\n * Tag scheme (ADR 0021): `sha-<short>` always; the exact `v<version>` tag; a\n * floating major tag (`v2`) on stable releases only. `latest` is held during\n * prereleases (npm's `rc` dist-tag analog) so existing deployments pinned to\n * `:latest` keep serving the last stable image — and `:rc` is the floating\n * ref for the prerelease train (npm's `rc` dist-tag mirror): it moves on\n * every prerelease deploy and freezes at the last rc-train build once the\n * workspace releases a stable version.\n */\nexport function computeImageTags(input: { shortSha: string; version?: string }): ImageTags {\n const tags = [`sha-${input.shortSha}`];\n const match = input.version?.trim().match(SEMVER_PATTERN);\n if (!match) {\n return { tags, pushLatest: true, pushRc: false };\n }\n const [, major, minor, patch, prerelease] = match;\n const exact = prerelease\n ? `v${major}.${minor}.${patch}-${prerelease}`\n : `v${major}.${minor}.${patch}`;\n if (prerelease) {\n return {\n tags: [...tags, exact],\n pushLatest: false,\n latestHoldReason: `${exact} is a prerelease — :latest still serves the last stable image`,\n pushRc: true,\n };\n }\n return { tags: [...tags, exact, `v${major}`], pushLatest: true, pushRc: false };\n}\n\nexport interface ImageDeployResult {\n image: string;\n /** Primary pinned tag (the sha tag). */\n tag: string;\n /** All tags pushed, including the primary. */\n tags: string[];\n latestPushed: boolean;\n /** Whether the floating `:rc` prerelease-train ref was pushed. */\n rcPushed: boolean;\n digest?: string;\n}\n\nexport type DeployImagePlan =\n | { kind: \"prebuilt\"; image: string; digest: string }\n | { kind: \"build\"; image: string }\n | { kind: \"skip\"; reason: string };\n\nconst DIGEST_PATTERN = /^sha256:[a-f0-9]{64}$/;\n\n/** A Railway pin is `FROM image@<digest>` — anything else cannot resolve. */\nexport function isValidImageDigest(digest: string): boolean {\n return DIGEST_PATTERN.test(digest);\n}\n\n/**\n * Decide the image leg's source: a digest handed over from a pre-pushed image\n * (the CI image job) wins; otherwise the local docker build runs when the\n * toolchain and Dockerfile are present (ADR 0021, as amended).\n */\nexport function resolveDeployImagePlan(input: {\n imageRef: ResolvedImageRef | undefined;\n imageDigest?: string;\n hasDocker: boolean;\n hasDockerfile: boolean;\n}): DeployImagePlan {\n if (!input.imageRef) {\n return {\n kind: \"skip\",\n reason: \"set ci.image in bos.config.json (or BOS_IMAGE) to build and push the runtime image\",\n };\n }\n if (input.imageDigest) {\n return { kind: \"prebuilt\", image: input.imageRef.image, digest: input.imageDigest };\n }\n if (!input.hasDocker) {\n return { kind: \"skip\", reason: \"docker is not available\" };\n }\n if (!input.hasDockerfile) {\n return { kind: \"skip\", reason: \"no Dockerfile at the config root\" };\n }\n return { kind: \"build\", image: input.imageRef.image };\n}\n\n/**\n * Image leg (ADR 0021): build the runtime stage, tag `sha-<short>` + version\n * tags, push them, capture the digest, then push the floating refs — `:latest`\n * unless the version is a prerelease, and `:rc` when it is. Callers skip the\n * leg with a notice when no image is configured (child repos get\n * build+upload+publish only).\n */\nexport async function buildAndPushImage(input: {\n image: string;\n configDir: string;\n verbose?: boolean;\n}): Promise<ImageDeployResult> {\n const shaResult = await run(\"git\", [\"rev-parse\", \"--short=7\", \"HEAD\"], {\n cwd: input.configDir,\n capture: true,\n });\n const shortSha = shaResult?.stdout.trim();\n if (!shaResult || shaResult.exitCode !== 0 || !shortSha) {\n const detail = shaResult?.stderr.trim();\n throw new Error(\n `Failed to resolve the current git SHA in ${input.configDir} (exit code ${shaResult?.exitCode ?? \"unknown\"}${detail ? `: ${detail}` : \"\"})`,\n );\n }\n\n const version = readFrameworkVersion(input.configDir);\n const { tags, pushLatest, latestHoldReason, pushRc } = computeImageTags({\n shortSha,\n version,\n });\n const refs = tags.map((tag) => `${input.image}:${tag}`);\n const latestRef = `${input.image}:latest`;\n const rcRef = `${input.image}:rc`;\n const buildRefs = pushLatest ? [...refs, latestRef] : [...refs];\n if (pushRc) buildRefs.push(rcRef);\n\n console.log(\n ` Building runtime image ${colors.cyan(buildRefs.join(\", \"))}${pushLatest ? \"\" : colors.yellow(\" (latest held)\")}`,\n );\n await run(\n \"docker\",\n [\"build\", \"--target\", \"runtime\", ...buildRefs.flatMap((ref) => [\"-t\", ref]), \".\"],\n { cwd: input.configDir },\n );\n\n console.log(` Pushing ${colors.cyan(refs.join(\", \"))}...`);\n let digest: string | undefined;\n for (const ref of refs) {\n const push = await run(\"docker\", [\"push\", ref], {\n cwd: input.configDir,\n capture: true,\n });\n if (!push || push.exitCode !== 0) {\n throw new Error(`docker push ${ref} failed with exit code ${push?.exitCode ?? \"unknown\"}`);\n }\n digest ??= parseDigest(push.stdout);\n if (input.verbose && push.stdout.trim()) {\n console.log(colors.dim(push.stdout.trim()));\n }\n }\n\n const pushFloating = async (ref: string): Promise<boolean> => {\n const push = await run(\"docker\", [\"push\", ref], {\n cwd: input.configDir,\n capture: true,\n });\n if (!push || push.exitCode !== 0) {\n throw new Error(`docker push ${ref} failed with exit code ${push?.exitCode ?? \"unknown\"}`);\n }\n digest ??= parseDigest(push.stdout);\n if (input.verbose && push.stdout.trim()) {\n console.log(colors.dim(push.stdout.trim()));\n }\n return true;\n };\n\n let latestPushed = false;\n if (pushLatest) {\n latestPushed = await pushFloating(latestRef);\n } else {\n console.log(colors.yellow(` latest held: ${latestHoldReason}`));\n }\n const rcPushed = pushRc ? await pushFloating(rcRef) : false;\n\n if (!digest) {\n console.log(colors.yellow(\" Could not capture the image digest from push output\"));\n }\n\n return { image: input.image, tag: tags[0]!, tags, latestPushed, rcPushed, digest };\n}\n\n/**\n * Railway leg (ADR 0021, amended): image-backed deploy. The service's source\n * is a Docker image ref (connected once in the dashboard — `:rc` during the\n * prerelease train), and `redeploy --from-source` pulls and deploys whatever\n * that ref points at. The image leg pushes `:rc` (and the `sha-<short>` /\n * version tags) immediately before this step, so the pulled bytes are exactly\n * what this train validated. Railway skips the build entirely for\n * Docker-image sources — nothing is uploaded, nothing is built on Railway,\n * and the digest-pin Dockerfile mechanism this replaces is gone (the CLI v5\n * dropped RAILWAY_DOCKERFILE_PATH, its snapshot respects .gitignore so\n * generated Dockerfiles never shipped, and its Metal builder rejected the\n * repo Dockerfile's cache-mount ids).\n */\nexport async function deployImageToRailway(input: {\n service: string;\n configDir: string;\n}): Promise<void> {\n console.log(` Deploying to Railway service ${colors.cyan(input.service)} (image-backed)...`);\n // The probe is authoritative: runners don't ship the CLI, and a spawn\n // failure resolves (reject:false) as exitCode 1 with empty output — the\n // 2026-10-13 deploy surfaced exactly that as a silent instant failure.\n let version: string | undefined;\n try {\n version = (await run(\"railway\", [\"--version\"], { cwd: input.configDir, capture: true }))\n ?.stdout;\n } catch {\n version = undefined;\n }\n if (!version?.trim()) {\n throw new Error(\"Railway CLI not found. Install it: npm i -g @railway/cli\");\n }\n console.log(` ${colors.dim(`railway ${version.trim()}`)}`);\n\n // Stream the CLI's output live — a silent exit (empty stdout+stderr, seen\n // on the 2026-10-13 deploy) must still be diagnosable from the workflow log.\n const collected = { stdout: \"\", stderr: \"\" };\n const result = await run(\n \"railway\",\n [\"redeploy\", \"--service\", input.service, \"--from-source\", \"--yes\"],\n {\n cwd: input.configDir,\n capture: true,\n onChunk: (stream, chunk) => {\n collected[stream] += chunk.toString(\"utf-8\");\n for (const line of chunk.toString(\"utf-8\").split(\"\\n\")) {\n if (line.trim()) console.log(` ${colors.dim(line.trim())}`);\n }\n },\n },\n );\n if (!result || result.exitCode !== 0) {\n const exitCode = result?.exitCode ?? \"unknown\";\n const tail = (stream: string, text: string) =>\n text.trim()\n ? `\\nrailway ${stream} (tail):\\n${text.trim().split(\"\\n\").slice(-20).join(\"\\n\")}`\n : \"\";\n throw new Error(\n `railway redeploy failed with exit code ${exitCode}` +\n tail(\"stdout\", collected.stdout) +\n tail(\"stderr\", collected.stderr),\n );\n }\n console.log(colors.green(` ${icons.ok} Railway deploy complete`));\n}\n"],"mappings":";;;;;;;;;;AAcA,SAAgB,gBAAgB,OAIC;CAC/B,MAAM,WAAW,MAAM,KAAK;CAC5B,IAAI,MAAM,SAAS,OAAO;EAAE,OAAO,MAAM;EAAS,QAAQ;CAAK;CAC/D,IAAI,UAAU,OAAO;EAAE,OAAO;EAAU,QAAQ;CAAM;CAEtD,MAAM,OAAO,MAAM,YACf,QAAQ,sCAAsC,EAAE,CAAC,CAClD,QAAQ,WAAW,EAAE,CAAC,CACtB,QAAQ,QAAQ,EAAE,CAAC,CACnB,YAAY;CACf,IAAI,CAAC,MAAM,SAAS,GAAG,KAAK,KAAK,MAAM,GAAG,CAAC,CAAC,WAAW,GAAG,OAAO;CACjE,OAAO;EAAE,OAAO,WAAW;EAAQ,QAAQ;CAAa;AAC1D;AAEA,eAAsB,YAA8B;CAClD,IAAI;EAIF,QAAO,MAHcA,gBAAI,UAAU;GAAC;GAAQ;GAAY;EAAoB,GAAG,EAC7E,SAAS,KACX,CAAC,EACY,EAAE,aAAa;CAC9B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,YAAY,YAAwC;CAE3D,OADc,WAAW,MAAM,+BACpB,CAAC,GAAG;AACjB;AAEA,MAAM,iBAAiB;;;;;;AAOvB,SAAS,qBAAqB,WAAuC;CACnE,IAAI;EACF,M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IAAI,CAAC,SAAS,KAAK,GACjB,MAAM,IAAI,MAAM,0DAA0D;CAE5E,QAAQ,IAAI,KAAKG,qBAAO,IAAI,WAAW,QAAQ,KAAK,GAAG,GAAG;CAI1D,MAAM,YAAY;EAAE,QAAQ;EAAI,QAAQ;CAAG;CAC3C,MAAM,SAAS,MAAMH,gBACnB,WACA;EAAC;EAAY;EAAa,MAAM;EAAS;EAAiB;CAAO,GACjE;EACE,KAAK,MAAM;EACX,SAAS;EACT,UAAU,QAAQ,UAAU;GAC1B,UAAU,WAAW,MAAM,SAAS,OAAO;GAC3C,KAAK,MAAM,QAAQ,MAAM,SAAS,OAAO,CAAC,CAAC,MAAM,IAAI,GACnD,IAAI,KAAK,KAAK,GAAG,QAAQ,IAAI,KAAKG,qBAAO,IAAI,KAAK,KAAK,CAAC,GAAG;EAE/D;CACF,CACF;CACA,IAAI,CAAC,UAAU,OAAO,aAAa,GAAG;EACpC,MAAM,WAAW,QAAQ,YAAY;EACrC,MAAM,QAAQ,QAAgB,SAC5B,KAAK,KAAK,IACN,aAAa,OAAO,YAAY,KAAK,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,IAAI,MAC5E;EACN,MAAM,IAAI,MACR,0CAA0C,aACxC,KAAK,UAAU,UAAU,MAAM,IAC/B,KAAK,UAAU,UAAU,MAAM,CACnC;CACF;CACA,QAAQ,IAAIA,qBAAO,MAAM,KAAKC,oBAAM,GAAG,yBAAyB,CAAC;AACnE"}
1
+ {"version":3,"file":"image-deploy.cjs","names":["run","readFileSync","join","colors","icons"],"sources":["../src/image-deploy.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { run } from \"./utils/run\";\nimport { colors, icons } from \"./utils/theme\";\n\nexport interface ResolvedImageRef {\n image: string;\n source: \"ci\" | \"env\" | \"repository\";\n}\n\n/**\n * Image reference resolution precedence (ADR 0021): `ci.image` in\n * bos.config.json → `BOS_IMAGE` env → derived from `repository`.\n */\nexport function resolveImageRef(input: {\n ciImage?: string;\n repository?: string;\n env?: Record<string, string | undefined>;\n}): ResolvedImageRef | undefined {\n const envImage = input.env?.BOS_IMAGE;\n if (input.ciImage) return { image: input.ciImage, source: \"ci\" };\n if (envImage) return { image: envImage, source: \"env\" };\n\n const repo = input.repository\n ?.replace(/^https?:\\/\\/(www\\.)?github\\.com\\//i, \"\")\n .replace(/\\.git$/i, \"\")\n .replace(/\\/+$/, \"\")\n .toLowerCase();\n if (!repo?.includes(\"/\") || repo.split(\"/\").length !== 2) return undefined;\n return { image: `ghcr.io/${repo}`, source: \"repository\" };\n}\n\n/** Compose the runnable image ref: `image@sha256:…` when a digest exists,\n * `image` alone otherwise. Never docker-run the bare ref in a deploy flow —\n * the implicit `:latest` is held to the last stable release during\n * prereleases (ADR 0021), which boots a different framework build than the\n * one this train pinned. */\nexport function imageRefWithDigest(image: string, digest?: string): string {\n return digest ? `${image}@${digest}` : image;\n}\n\nexport async function hasDocker(): Promise<boolean> {\n try {\n const result = await run(\"docker\", [\"info\", \"--format\", \"{{.ServerVersion}}\"], {\n capture: true,\n });\n return result?.exitCode === 0;\n } catch {\n return false;\n }\n}\n\nfunction parseDigest(pushOutput: string): string | undefined {\n const match = pushOutput.match(/digest:\\s*(sha256:[a-f0-9]+)/i);\n return match?.[1];\n}\n\nconst SEMVER_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?$/;\n\n/**\n * The runtime framework version baked into the image is the workspace source's\n * `everything-dev` package version — the image builds from `configDir`, so that\n * file is the truth. Missing (child repos without the workspace) → undefined.\n */\nfunction readFrameworkVersion(configDir: string): string | undefined {\n try {\n const raw = readFileSync(\n join(configDir, \"packages\", \"everything-dev\", \"package.json\"),\n \"utf-8\",\n );\n const pkg = JSON.parse(raw) as { version?: unknown };\n return typeof pkg.version === \"string\" && SEMVER_PATTERN.test(pkg.version)\n ? pkg.version\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface ImageTags {\n /** Exact refs to build and push, in push order (latest excluded). */\n tags: string[];\n /** Push `:latest` after the pinned tags. */\n pushLatest: boolean;\n /** Human-readable reason when `latest` is held. */\n latestHoldReason?: string;\n /** Push `:rc` after the pinned tags — the floating prerelease-train ref. */\n pushRc: boolean;\n}\n\n/**\n * Tag scheme (ADR 0021): `sha-<short>` always; the exact `v<version>` tag; a\n * floating major tag (`v2`) on stable releases only. `latest` is held during\n * prereleases (npm's `rc` dist-tag analog) so existing deployments pinned to\n * `:latest` keep serving the last stable image — and `:rc` is the floating\n * ref for the prerelease train (npm's `rc` dist-tag mirror): it moves on\n * every prerelease deploy and freezes at the last rc-train build once the\n * workspace releases a stable version.\n */\nexport function computeImageTags(input: { shortSha: string; version?: string }): ImageTags {\n const tags = [`sha-${input.shortSha}`];\n const match = input.version?.trim().match(SEMVER_PATTERN);\n if (!match) {\n return { tags, pushLatest: true, pushRc: false };\n }\n const [, major, minor, patch, prerelease] = match;\n const exact = prerelease\n ? `v${major}.${minor}.${patch}-${prerelease}`\n : `v${major}.${minor}.${patch}`;\n if (prerelease) {\n return {\n tags: [...tags, exact],\n pushLatest: false,\n latestHoldReason: `${exact} is a prerelease — :latest still serves the last stable image`,\n pushRc: true,\n };\n }\n return { tags: [...tags, exact, `v${major}`], pushLatest: true, pushRc: false };\n}\n\nexport interface ImageDeployResult {\n image: string;\n /** Primary pinned tag (the sha tag). */\n tag: string;\n /** All tags pushed, including the primary. */\n tags: string[];\n latestPushed: boolean;\n /** Whether the floating `:rc` prerelease-train ref was pushed. */\n rcPushed: boolean;\n digest?: string;\n}\n\nexport type DeployImagePlan =\n | { kind: \"prebuilt\"; image: string; digest: string }\n | { kind: \"build\"; image: string }\n | { kind: \"skip\"; reason: string };\n\nconst DIGEST_PATTERN = /^sha256:[a-f0-9]{64}$/;\n\n/** A Railway pin is `FROM image@<digest>` — anything else cannot resolve. */\nexport function isValidImageDigest(digest: string): boolean {\n return DIGEST_PATTERN.test(digest);\n}\n\n/**\n * Decide the image leg's source: a digest handed over from a pre-pushed image\n * (the CI image job) wins; otherwise the local docker build runs when the\n * toolchain and Dockerfile are present (ADR 0021, as amended).\n */\nexport function resolveDeployImagePlan(input: {\n imageRef: ResolvedImageRef | undefined;\n imageDigest?: string;\n hasDocker: boolean;\n hasDockerfile: boolean;\n}): DeployImagePlan {\n if (!input.imageRef) {\n return {\n kind: \"skip\",\n reason: \"set ci.image in bos.config.json (or BOS_IMAGE) to build and push the runtime image\",\n };\n }\n if (input.imageDigest) {\n return { kind: \"prebuilt\", image: input.imageRef.image, digest: input.imageDigest };\n }\n if (!input.hasDocker) {\n return { kind: \"skip\", reason: \"docker is not available\" };\n }\n if (!input.hasDockerfile) {\n return { kind: \"skip\", reason: \"no Dockerfile at the config root\" };\n }\n return { kind: \"build\", image: input.imageRef.image };\n}\n\n/**\n * Image leg (ADR 0021): build the runtime stage, tag `sha-<short>` + version\n * tags, push them, capture the digest, then push the floating refs — `:latest`\n * unless the version is a prerelease, and `:rc` when it is. Callers skip the\n * leg with a notice when no image is configured (child repos get\n * build+upload+publish only).\n */\nexport async function buildAndPushImage(input: {\n image: string;\n configDir: string;\n verbose?: boolean;\n}): Promise<ImageDeployResult> {\n const shaResult = await run(\"git\", [\"rev-parse\", \"--short=7\", \"HEAD\"], {\n cwd: input.configDir,\n capture: true,\n });\n const shortSha = shaResult?.stdout.trim();\n if (!shaResult || shaResult.exitCode !== 0 || !shortSha) {\n const detail = shaResult?.stderr.trim();\n throw new Error(\n `Failed to resolve the current git SHA in ${input.configDir} (exit code ${shaResult?.exitCode ?? \"unknown\"}${detail ? `: ${detail}` : \"\"})`,\n );\n }\n\n const version = readFrameworkVersion(input.configDir);\n const { tags, pushLatest, latestHoldReason, pushRc } = computeImageTags({\n shortSha,\n version,\n });\n const refs = tags.map((tag) => `${input.image}:${tag}`);\n const latestRef = `${input.image}:latest`;\n const rcRef = `${input.image}:rc`;\n const buildRefs = pushLatest ? [...refs, latestRef] : [...refs];\n if (pushRc) buildRefs.push(rcRef);\n\n console.log(\n ` Building runtime image ${colors.cyan(buildRefs.join(\", \"))}${pushLatest ? \"\" : colors.yellow(\" (latest held)\")}`,\n );\n await run(\n \"docker\",\n [\"build\", \"--target\", \"runtime\", ...buildRefs.flatMap((ref) => [\"-t\", ref]), \".\"],\n { cwd: input.configDir },\n );\n\n console.log(` Pushing ${colors.cyan(refs.join(\", \"))}...`);\n let digest: string | undefined;\n for (const ref of refs) {\n const push = await run(\"docker\", [\"push\", ref], {\n cwd: input.configDir,\n capture: true,\n });\n if (!push || push.exitCode !== 0) {\n throw new Error(`docker push ${ref} failed with exit code ${push?.exitCode ?? \"unknown\"}`);\n }\n digest ??= parseDigest(push.stdout);\n if (input.verbose && push.stdout.trim()) {\n console.log(colors.dim(push.stdout.trim()));\n }\n }\n\n const pushFloating = async (ref: string): Promise<boolean> => {\n const push = await run(\"docker\", [\"push\", ref], {\n cwd: input.configDir,\n capture: true,\n });\n if (!push || push.exitCode !== 0) {\n throw new Error(`docker push ${ref} failed with exit code ${push?.exitCode ?? \"unknown\"}`);\n }\n digest ??= parseDigest(push.stdout);\n if (input.verbose && push.stdout.trim()) {\n console.log(colors.dim(push.stdout.trim()));\n }\n return true;\n };\n\n let latestPushed = false;\n if (pushLatest) {\n latestPushed = await pushFloating(latestRef);\n } else {\n console.log(colors.yellow(` latest held: ${latestHoldReason}`));\n }\n const rcPushed = pushRc ? await pushFloating(rcRef) : false;\n\n if (!digest) {\n console.log(colors.yellow(\" Could not capture the image digest from push output\"));\n }\n\n return { image: input.image, tag: tags[0]!, tags, latestPushed, rcPushed, digest };\n}\n\n/**\n * Railway leg (ADR 0021, amended): image-backed deploy. The service's source\n * is a Docker image ref (connected once in the dashboard — `:rc` during the\n * prerelease train), and `redeploy --from-source` pulls and deploys whatever\n * that ref points at. The image leg pushes `:rc` (and the `sha-<short>` /\n * version tags) immediately before this step, so the pulled bytes are exactly\n * what this train validated. Railway skips the build entirely for\n * Docker-image sources — nothing is uploaded, nothing is built on Railway,\n * and the digest-pin Dockerfile mechanism this replaces is gone (the CLI v5\n * dropped RAILWAY_DOCKERFILE_PATH, its snapshot respects .gitignore so\n * generated Dockerfiles never shipped, and its Metal builder rejected the\n * repo Dockerfile's cache-mount ids).\n */\nexport async function deployImageToRailway(input: {\n service: string;\n configDir: string;\n}): Promise<void> {\n console.log(` Deploying to Railway service ${colors.cyan(input.service)} (image-backed)...`);\n // The probe is authoritative: runners don't ship the CLI, and a spawn\n // failure resolves (reject:false) as exitCode 1 with empty output — the\n // 2026-10-13 deploy surfaced exactly that as a silent instant failure.\n let version: string | undefined;\n try {\n version = (await run(\"railway\", [\"--version\"], { cwd: input.configDir, capture: true }))\n ?.stdout;\n } catch {\n version = undefined;\n }\n if (!version?.trim()) {\n throw new Error(\"Railway CLI not found. Install it: npm i -g @railway/cli\");\n }\n console.log(` ${colors.dim(`railway ${version.trim()}`)}`);\n\n // Stream the CLI's output live — a silent exit (empty stdout+stderr, seen\n // on the 2026-10-13 deploy) must still be diagnosable from the workflow log.\n const collected = { stdout: \"\", stderr: \"\" };\n const result = await run(\n \"railway\",\n [\"redeploy\", \"--service\", input.service, \"--from-source\", \"--yes\"],\n {\n cwd: input.configDir,\n capture: true,\n onChunk: (stream, chunk) => {\n collected[stream] += chunk.toString(\"utf-8\");\n for (const line of chunk.toString(\"utf-8\").split(\"\\n\")) {\n if (line.trim()) console.log(` ${colors.dim(line.trim())}`);\n }\n },\n },\n );\n if (!result || result.exitCode !== 0) {\n const exitCode = result?.exitCode ?? \"unknown\";\n const tail = (stream: string, text: string) =>\n text.trim()\n ? `\\nrailway ${stream} (tail):\\n${text.trim().split(\"\\n\").slice(-20).join(\"\\n\")}`\n : \"\";\n throw new Error(\n `railway redeploy failed with exit code ${exitCode}` +\n tail(\"stdout\", collected.stdout) +\n tail(\"stderr\", collected.stderr),\n );\n }\n console.log(colors.green(` ${icons.ok} Railway deploy complete`));\n}\n"],"mappings":";;;;;;;;;;AAcA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C,KAAK,MAAM,QAAQ,MAAM,SAAS,OAAO,CAAC,CAAC,MAAM,IAAI,GACnD,IAAI,KAAK,KAAK,GAAG,QAAQ,IAAI,KAAKG,qBAAO,IAAI,KAAK,KAAK,CAAC,GAAG;EAE/D;CACF,CACF;CACA,IAAI,CAAC,UAAU,OAAO,aAAa,GAAG;EACpC,MAAM,WAAW,QAAQ,YAAY;EACrC,MAAM,QAAQ,QAAgB,SAC5B,KAAK,KAAK,IACN,aAAa,OAAO,YAAY,KAAK,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,IAAI,MAC5E;EACN,MAAM,IAAI,MACR,0CAA0C,aACxC,KAAK,UAAU,UAAU,MAAM,IAC/B,KAAK,UAAU,UAAU,MAAM,CACnC;CACF;CACA,QAAQ,IAAIA,qBAAO,MAAM,KAAKC,oBAAM,GAAG,yBAAyB,CAAC;AACnE"}
@@ -25,6 +25,14 @@ function resolveImageRef(input) {
25
25
  source: "repository"
26
26
  };
27
27
  }
28
+ /** Compose the runnable image ref: `image@sha256:…` when a digest exists,
29
+ * `image` alone otherwise. Never docker-run the bare ref in a deploy flow —
30
+ * the implicit `:latest` is held to the last stable release during
31
+ * prereleases (ADR 0021), which boots a different framework build than the
32
+ * one this train pinned. */
33
+ function imageRefWithDigest(image, digest) {
34
+ return digest ? `${image}@${digest}` : image;
35
+ }
28
36
  async function hasDocker() {
29
37
  try {
30
38
  return (await run("docker", [
@@ -248,5 +256,5 @@ async function deployImageToRailway(input) {
248
256
  }
249
257
 
250
258
  //#endregion
251
- export { buildAndPushImage, computeImageTags, deployImageToRailway, hasDocker, isValidImageDigest, resolveDeployImagePlan, resolveImageRef };
259
+ export { buildAndPushImage, computeImageTags, deployImageToRailway, hasDocker, imageRefWithDigest, isValidImageDigest, resolveDeployImagePlan, resolveImageRef };
252
260
  //# sourceMappingURL=image-deploy.mjs.map