@kodycodes/cli 1.26.2 → 1.27.0

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 (296) hide show
  1. package/README.md +175 -167
  2. package/dist/add-mcp-install.d.ts +1 -1
  3. package/dist/api-token.d.ts +1 -1
  4. package/dist/auth-6ZE6QQXA.js +31 -0
  5. package/dist/auth-6ZE6QQXA.js.map +6 -0
  6. package/dist/auth-bootstrap.d.ts +1 -1
  7. package/dist/auth.d.ts +27 -3
  8. package/dist/bin.js +27 -3
  9. package/dist/bin.js.map +6 -1
  10. package/dist/capability-proxy.d.ts +1 -1
  11. package/dist/chunk-2IHISXHN.js +1413 -0
  12. package/dist/chunk-2IHISXHN.js.map +6 -0
  13. package/dist/chunk-2XPH7L2P.js +23 -0
  14. package/dist/chunk-2XPH7L2P.js.map +6 -0
  15. package/dist/chunk-3H72XY5R.js +535 -0
  16. package/dist/chunk-3H72XY5R.js.map +6 -0
  17. package/dist/chunk-46IJPEID.js +30 -0
  18. package/dist/chunk-46IJPEID.js.map +6 -0
  19. package/dist/chunk-4GIFJVGT.js +14 -0
  20. package/dist/chunk-4GIFJVGT.js.map +6 -0
  21. package/dist/chunk-5JIRHJQP.js +1016 -0
  22. package/dist/chunk-5JIRHJQP.js.map +6 -0
  23. package/dist/chunk-5ZBJAP6G.js +2005 -0
  24. package/dist/chunk-5ZBJAP6G.js.map +6 -0
  25. package/dist/chunk-6ZYUGXVW.js +26 -0
  26. package/dist/chunk-6ZYUGXVW.js.map +6 -0
  27. package/dist/chunk-7PRJ36I5.js +23 -0
  28. package/dist/chunk-7PRJ36I5.js.map +6 -0
  29. package/dist/chunk-BTL3PJ2H.js +38 -0
  30. package/dist/chunk-BTL3PJ2H.js.map +6 -0
  31. package/dist/chunk-CASGRYOF.js +21 -0
  32. package/dist/chunk-CASGRYOF.js.map +6 -0
  33. package/dist/chunk-CPS7HW4T.js +56 -0
  34. package/dist/chunk-CPS7HW4T.js.map +6 -0
  35. package/dist/chunk-CWWHR4FH.js +19 -0
  36. package/dist/chunk-CWWHR4FH.js.map +6 -0
  37. package/dist/chunk-D366STO5.js +2051 -0
  38. package/dist/chunk-D366STO5.js.map +6 -0
  39. package/dist/chunk-DW5UTJ6T.js +115 -0
  40. package/dist/chunk-DW5UTJ6T.js.map +6 -0
  41. package/dist/chunk-EJXEVGWF.js +47 -0
  42. package/dist/chunk-EJXEVGWF.js.map +6 -0
  43. package/dist/chunk-FBEZ6PZ7.js +746 -0
  44. package/dist/chunk-FBEZ6PZ7.js.map +6 -0
  45. package/dist/chunk-JOMBXQOS.js +435 -0
  46. package/dist/chunk-JOMBXQOS.js.map +6 -0
  47. package/dist/{package-local-runtime-source.js → chunk-LU7I7CQ4.js} +395 -52
  48. package/dist/chunk-LU7I7CQ4.js.map +6 -0
  49. package/dist/chunk-OZDWOZLV.js +964 -0
  50. package/dist/chunk-OZDWOZLV.js.map +6 -0
  51. package/dist/chunk-SLNAWWQK.js +64 -0
  52. package/dist/chunk-SLNAWWQK.js.map +6 -0
  53. package/dist/chunk-TUUFQYWP.js +348 -0
  54. package/dist/chunk-TUUFQYWP.js.map +6 -0
  55. package/dist/chunk-UW6AWLXX.js +43 -0
  56. package/dist/chunk-UW6AWLXX.js.map +6 -0
  57. package/dist/chunk-W2SAFAT4.js +1563 -0
  58. package/dist/chunk-W2SAFAT4.js.map +6 -0
  59. package/dist/chunk-XV6D6HSG.js +57 -0
  60. package/dist/chunk-XV6D6HSG.js.map +6 -0
  61. package/dist/chunk-Y4FOJETX.js +616 -0
  62. package/dist/chunk-Y4FOJETX.js.map +6 -0
  63. package/dist/chunk-YDWTXEKQ.js +469 -0
  64. package/dist/chunk-YDWTXEKQ.js.map +6 -0
  65. package/dist/chunk-ZILB2HWE.js +24 -0
  66. package/dist/chunk-ZILB2HWE.js.map +6 -0
  67. package/dist/cli.js +74 -1500
  68. package/dist/cli.js.map +6 -1
  69. package/dist/defaults.d.ts +1 -1
  70. package/dist/detect-running-hosts.d.ts +1 -1
  71. package/dist/dev/dev-assets.d.ts +1 -1
  72. package/dist/dev/dev-registry.d.ts +1 -1
  73. package/dist/dev/error-page.d.ts +1 -1
  74. package/dist/dev/live-reload.d.ts +2 -2
  75. package/dist/dev-command-5PDEIWOC.js +5025 -0
  76. package/dist/dev-command-5PDEIWOC.js.map +6 -0
  77. package/dist/dev-command.d.ts +1 -1
  78. package/dist/discover-login-identity.d.ts +6 -7
  79. package/dist/discover-org.d.ts +2 -3
  80. package/dist/generated/openapi-routes.d.ts +6 -0
  81. package/dist/git-credential-INB2UV4C.js +170 -0
  82. package/dist/git-credential-INB2UV4C.js.map +6 -0
  83. package/dist/install-ONEJRYZ3.js +10728 -0
  84. package/dist/install-ONEJRYZ3.js.map +6 -0
  85. package/dist/install.d.ts +1 -1
  86. package/dist/local-execute-I3BP5NEQ.js +395 -0
  87. package/dist/local-execute-I3BP5NEQ.js.map +6 -0
  88. package/dist/local-execute-auth.d.ts +2 -2
  89. package/dist/local-execute.d.ts +1 -1
  90. package/dist/local-gateway-fetch-forward.d.ts +2 -2
  91. package/dist/local-package-run-JFKNSNWM.js +23 -0
  92. package/dist/local-package-run-JFKNSNWM.js.map +6 -0
  93. package/dist/local-package-run.d.ts +2 -2
  94. package/dist/mock/mock-fetch-gateway.d.ts +2 -2
  95. package/dist/mock/mock-supported.d.ts +1 -1
  96. package/dist/mock-dep-resolve-B5ZH4U3H.js +60 -0
  97. package/dist/mock-dep-resolve-B5ZH4U3H.js.map +6 -0
  98. package/dist/mock-fetch-gateway-S2ULVFAI.js +35 -0
  99. package/dist/mock-fetch-gateway-S2ULVFAI.js.map +6 -0
  100. package/dist/mock-local-deps-2VVNJLFF.js +200 -0
  101. package/dist/mock-local-deps-2VVNJLFF.js.map +6 -0
  102. package/dist/mock-local-deps.d.ts +1 -1
  103. package/dist/mock-server-TFO7Q26H.js +22 -0
  104. package/dist/mock-server-TFO7Q26H.js.map +6 -0
  105. package/dist/oauth-browser.d.ts +42 -0
  106. package/dist/oauth-provider.d.ts +14 -19
  107. package/dist/open-api-client-SR4B7265.js +43 -0
  108. package/dist/open-api-client-SR4B7265.js.map +6 -0
  109. package/dist/open-api-client.d.ts +2 -1
  110. package/dist/org-535LB4PD.js +134 -0
  111. package/dist/org-535LB4PD.js.map +6 -0
  112. package/dist/org-resolve.d.ts +2 -0
  113. package/dist/package-app-dev.d.ts +2 -2
  114. package/dist/package-manifest-DFF6XCPV.js +15 -0
  115. package/dist/package-manifest-DFF6XCPV.js.map +6 -0
  116. package/dist/remote-execute-JN6DRFEU.js +129 -0
  117. package/dist/remote-execute-JN6DRFEU.js.map +6 -0
  118. package/dist/remote-execute.d.ts +3 -3
  119. package/dist/setup-git-MHK563LB.js +87 -0
  120. package/dist/setup-git-MHK563LB.js.map +6 -0
  121. package/dist/setup-git.d.ts +1 -1
  122. package/dist/skill-D74XVI6T.js +61 -0
  123. package/dist/skill-D74XVI6T.js.map +6 -0
  124. package/dist/store-27J4CQZ2.js +48 -0
  125. package/dist/store-27J4CQZ2.js.map +6 -0
  126. package/dist/structured-error-5MLWXYR3.js +14 -0
  127. package/dist/structured-error-5MLWXYR3.js.map +6 -0
  128. package/dist/structured-error.d.ts +1 -1
  129. package/dist/target-33ATHDUF.js +17 -0
  130. package/dist/target-33ATHDUF.js.map +6 -0
  131. package/package.json +12 -11
  132. package/skills/kody/SKILL.md +53 -50
  133. package/dist/add-mcp-install.js +0 -59
  134. package/dist/add-mcp-install.js.map +0 -1
  135. package/dist/api-token-store.js +0 -120
  136. package/dist/api-token-store.js.map +0 -1
  137. package/dist/api-token.js +0 -238
  138. package/dist/api-token.js.map +0 -1
  139. package/dist/auth-bootstrap.js +0 -373
  140. package/dist/auth-bootstrap.js.map +0 -1
  141. package/dist/auth.js +0 -386
  142. package/dist/auth.js.map +0 -1
  143. package/dist/capability-proxy.js +0 -527
  144. package/dist/capability-proxy.js.map +0 -1
  145. package/dist/credential-call-map.js +0 -155
  146. package/dist/credential-call-map.js.map +0 -1
  147. package/dist/credential-client-runtime-source.js +0 -9
  148. package/dist/credential-client-runtime-source.js.map +0 -1
  149. package/dist/credentialed-fetch-scan.js +0 -98
  150. package/dist/credentialed-fetch-scan.js.map +0 -1
  151. package/dist/defaults.js +0 -34
  152. package/dist/defaults.js.map +0 -1
  153. package/dist/detect-running-hosts.js +0 -13
  154. package/dist/detect-running-hosts.js.map +0 -1
  155. package/dist/dev/dev-assets.js +0 -202
  156. package/dist/dev/dev-assets.js.map +0 -1
  157. package/dist/dev/dev-bundler.js +0 -65
  158. package/dist/dev/dev-bundler.js.map +0 -1
  159. package/dist/dev/dev-events.js +0 -94
  160. package/dist/dev/dev-events.js.map +0 -1
  161. package/dist/dev/dev-port.js +0 -80
  162. package/dist/dev/dev-port.js.map +0 -1
  163. package/dist/dev/dev-protocol.js +0 -14
  164. package/dist/dev/dev-protocol.js.map +0 -1
  165. package/dist/dev/dev-registry.js +0 -95
  166. package/dist/dev/dev-registry.js.map +0 -1
  167. package/dist/dev/dev-watcher.js +0 -162
  168. package/dist/dev/dev-watcher.js.map +0 -1
  169. package/dist/dev/error-page.js +0 -64
  170. package/dist/dev/error-page.js.map +0 -1
  171. package/dist/dev/live-reload.js +0 -151
  172. package/dist/dev/live-reload.js.map +0 -1
  173. package/dist/dev/prebuild.js +0 -102
  174. package/dist/dev/prebuild.js.map +0 -1
  175. package/dist/dev/process-reaper.js +0 -151
  176. package/dist/dev/process-reaper.js.map +0 -1
  177. package/dist/dev/stack-trace.js +0 -56
  178. package/dist/dev/stack-trace.js.map +0 -1
  179. package/dist/dev/workerd-process.js +0 -118
  180. package/dist/dev/workerd-process.js.map +0 -1
  181. package/dist/dev-command.js +0 -676
  182. package/dist/dev-command.js.map +0 -1
  183. package/dist/discover-login-identity.js +0 -77
  184. package/dist/discover-login-identity.js.map +0 -1
  185. package/dist/discover-org.js +0 -62
  186. package/dist/discover-org.js.map +0 -1
  187. package/dist/git-credential.js +0 -147
  188. package/dist/git-credential.js.map +0 -1
  189. package/dist/help.js +0 -333
  190. package/dist/help.js.map +0 -1
  191. package/dist/host-catalog.js +0 -427
  192. package/dist/host-catalog.js.map +0 -1
  193. package/dist/host-config.js +0 -80
  194. package/dist/host-config.js.map +0 -1
  195. package/dist/http-error-body.js +0 -35
  196. package/dist/http-error-body.js.map +0 -1
  197. package/dist/install-hosts.js +0 -328
  198. package/dist/install-hosts.js.map +0 -1
  199. package/dist/install.js +0 -120
  200. package/dist/install.js.map +0 -1
  201. package/dist/invoke-passthrough.js +0 -60
  202. package/dist/invoke-passthrough.js.map +0 -1
  203. package/dist/local-bundle.js +0 -200
  204. package/dist/local-bundle.js.map +0 -1
  205. package/dist/local-execute-auth.js +0 -53
  206. package/dist/local-execute-auth.js.map +0 -1
  207. package/dist/local-execute.js +0 -338
  208. package/dist/local-execute.js.map +0 -1
  209. package/dist/local-gateway-fetch-forward.js +0 -135
  210. package/dist/local-gateway-fetch-forward.js.map +0 -1
  211. package/dist/local-host-runtime-surface.js +0 -75
  212. package/dist/local-host-runtime-surface.js.map +0 -1
  213. package/dist/local-package-graph.js +0 -405
  214. package/dist/local-package-graph.js.map +0 -1
  215. package/dist/local-package-run.js +0 -307
  216. package/dist/local-package-run.js.map +0 -1
  217. package/dist/local-runtime-bridge.js +0 -132
  218. package/dist/local-runtime-bridge.js.map +0 -1
  219. package/dist/local-runtime-source.js +0 -541
  220. package/dist/local-runtime-source.js.map +0 -1
  221. package/dist/login-callback-assets.js +0 -10
  222. package/dist/login-callback-assets.js.map +0 -1
  223. package/dist/login-callback-page.js +0 -362
  224. package/dist/login-callback-page.js.map +0 -1
  225. package/dist/mcp.d.ts +0 -34
  226. package/dist/mcp.js +0 -134
  227. package/dist/mcp.js.map +0 -1
  228. package/dist/mock/ensure-msw.js +0 -215
  229. package/dist/mock/ensure-msw.js.map +0 -1
  230. package/dist/mock/install-mock-fetch-shim.js +0 -36
  231. package/dist/mock/install-mock-fetch-shim.js.map +0 -1
  232. package/dist/mock/load-package-mocks.js +0 -136
  233. package/dist/mock/load-package-mocks.js.map +0 -1
  234. package/dist/mock/mock-fetch-gateway.js +0 -343
  235. package/dist/mock/mock-fetch-gateway.js.map +0 -1
  236. package/dist/mock/mock-gateway-fetch-shim.js +0 -104
  237. package/dist/mock/mock-gateway-fetch-shim.js.map +0 -1
  238. package/dist/mock/mock-server.js +0 -499
  239. package/dist/mock/mock-server.js.map +0 -1
  240. package/dist/mock/mock-storage.js +0 -186
  241. package/dist/mock/mock-storage.js.map +0 -1
  242. package/dist/mock/mock-supported.js +0 -63
  243. package/dist/mock/mock-supported.js.map +0 -1
  244. package/dist/mock-dep-resolve.js +0 -47
  245. package/dist/mock-dep-resolve.js.map +0 -1
  246. package/dist/mock-local-deps.js +0 -207
  247. package/dist/mock-local-deps.js.map +0 -1
  248. package/dist/network-error.js +0 -11
  249. package/dist/network-error.js.map +0 -1
  250. package/dist/node-engine.js +0 -21
  251. package/dist/node-engine.js.map +0 -1
  252. package/dist/oauth-provider.js +0 -107
  253. package/dist/oauth-provider.js.map +0 -1
  254. package/dist/onboarding-prompt.js +0 -15
  255. package/dist/onboarding-prompt.js.map +0 -1
  256. package/dist/open-api-client.js +0 -432
  257. package/dist/open-api-client.js.map +0 -1
  258. package/dist/open-url.js +0 -21
  259. package/dist/open-url.js.map +0 -1
  260. package/dist/org-resolve.js +0 -16
  261. package/dist/org-resolve.js.map +0 -1
  262. package/dist/org-slug.js +0 -11
  263. package/dist/org-slug.js.map +0 -1
  264. package/dist/org.js +0 -100
  265. package/dist/org.js.map +0 -1
  266. package/dist/package-app-dev.js +0 -922
  267. package/dist/package-app-dev.js.map +0 -1
  268. package/dist/package-collaborators.js +0 -179
  269. package/dist/package-collaborators.js.map +0 -1
  270. package/dist/package-info.js +0 -19
  271. package/dist/package-info.js.map +0 -1
  272. package/dist/package-local-runtime-source.js.map +0 -1
  273. package/dist/package-manifest.js +0 -364
  274. package/dist/package-manifest.js.map +0 -1
  275. package/dist/process-info.js +0 -14
  276. package/dist/process-info.js.map +0 -1
  277. package/dist/redact.js +0 -16
  278. package/dist/redact.js.map +0 -1
  279. package/dist/remote-execute.js +0 -108
  280. package/dist/remote-execute.js.map +0 -1
  281. package/dist/setup-git.js +0 -676
  282. package/dist/setup-git.js.map +0 -1
  283. package/dist/skill.js +0 -35
  284. package/dist/skill.js.map +0 -1
  285. package/dist/store.js +0 -597
  286. package/dist/store.js.map +0 -1
  287. package/dist/structured-error.js +0 -57
  288. package/dist/structured-error.js.map +0 -1
  289. package/dist/target.js +0 -52
  290. package/dist/target.js.map +0 -1
  291. package/dist/tool-result.js +0 -19
  292. package/dist/tool-result.js.map +0 -1
  293. package/dist/which.js +0 -22
  294. package/dist/which.js.map +0 -1
  295. package/dist/workerd-binary.js +0 -98
  296. package/dist/workerd-binary.js.map +0 -1
@@ -1,922 +0,0 @@
1
- /**
2
- * Long-running `kody dev` app server: bundles `kody.app.entry` the same way
3
- * local-bundle/publish does for esbuild, serves via workerd behind a Node
4
- * proxy that strips the mount, and rebuilds on file changes.
5
- *
6
- * Each successful rebuild starts a new workerd "generation" and only swaps the
7
- * proxy over once it is listening; the previous generation drains in-flight
8
- * requests and is then stopped. Requests that arrive mid-rebuild wait for it,
9
- * so a save is never answered by a 503 or a stale bundle.
10
- */
11
- import { randomBytes } from 'node:crypto';
12
- import { rmSync } from 'node:fs';
13
- import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
14
- import { createServer, request as httpRequest, } from 'node:http';
15
- import { tmpdir } from 'node:os';
16
- import { join, relative, resolve, sep } from 'node:path';
17
- import { assertTokenSafeApiUrl, callCapabilityProxy, } from './capability-proxy.js';
18
- import { apiTokenEnvVar } from './defaults.js';
19
- import { createDevClientBundler, parseDevAssetPath, serveDevAsset, } from './dev/dev-assets.js';
20
- import { forwardLocalGatewayFetchStream } from './local-gateway-fetch-forward.js';
21
- import { startLocalRuntimeBridge, } from './local-runtime-bridge.js';
22
- import { createDevBundler } from './dev/dev-bundler.js';
23
- import { parseWorkerdStdoutLine, runtimeErrorFix, } from './dev/dev-events.js';
24
- import { devErrorHeader, devRequestIdHeader } from './dev/dev-protocol.js';
25
- import { listenDevServer } from './dev/dev-port.js';
26
- import { devStatusPath } from './dev/dev-registry.js';
27
- import { createDevWatcher } from './dev/dev-watcher.js';
28
- import { sendDevError } from './dev/error-page.js';
29
- import { createLiveReloadHub, injectLiveReloadScript, liveReloadClientPath, liveReloadClientSource, liveReloadEventsPath, liveReloadScriptTag, shouldInjectLiveReload, } from './dev/live-reload.js';
30
- import { devWorkDirPrefix, startProcessReaper, sweepStaleDevDirs, } from './dev/process-reaper.js';
31
- import { runPrebuild } from './dev/prebuild.js';
32
- import { createStackMapper } from './dev/stack-trace.js';
33
- import { cleanWorkerdStderrLine, startWorkerd, } from './dev/workerd-process.js';
34
- import { BundleError, formatBundleDiagnostic } from './local-bundle.js';
35
- import { localExecuteGatewayFetchShimModuleName, resolveLocalPackageGraph, writePackageModuleFiles, } from './local-package-graph.js';
36
- import { createRuntimeFlatAliasSource, createWorkerdConfig, localWorkerModuleNames, } from './local-runtime-source.js';
37
- import { buildLocalPackageContext } from './local-package-run.js';
38
- import { installMockFetchShimModules } from './mock/install-mock-fetch-shim.js';
39
- import { resolveMockFetchGateway, tryHandleMockGatewayFetchCall, } from './mock/mock-fetch-gateway.js';
40
- import { createPackageAppEntrySource, createPackageLocalRuntimeModuleSource, runSecretEnvVar, runSecretHeader, } from './package-local-runtime-source.js';
41
- import { resolvePackagePath } from './package-manifest.js';
42
- import { redact } from './redact.js';
43
- import { ensureWorkerdBinary } from './workerd-binary.js';
44
- const defaultDebounceMs = 30;
45
- /** Watcher events this soon after a prebuild finishes are its own writes, not edits. */
46
- const prebuildSettleMs = 150;
47
- /**
48
- * After a *failed* prebuild, ignore watcher events this long. Chokidar/poll
49
- * echoes of partial output can arrive well after {@link prebuildSettleMs} on
50
- * slower CI and would otherwise restart the rebuild loop.
51
- */
52
- const failedPrebuildAbsorbMs = 1500;
53
- /** Longest a request waits for an in-progress rebuild before the old build answers. */
54
- const rebuildGateMs = 10_000;
55
- /** Longest a retired generation may keep draining in-flight requests. */
56
- const drainTimeoutMs = 10_000;
57
- export async function startPackageAppDev(options) {
58
- if (!options.manifest.app?.entry) {
59
- throw new Error('This package has no kody.app.entry. Add `"kody": { "app": { "entry": "./app/router.ts" } }` or use `kody dev job|webhook|emit|check`.');
60
- }
61
- assertTokenSafeApiUrl(options.apiUrl);
62
- const host = options.host ?? '127.0.0.1';
63
- const appBasePath = normalizeBasePath(options.appBasePath ?? '');
64
- const root = options.manifest.root;
65
- const runSecret = randomBytes(32).toString('hex');
66
- const emit = (event) => options.onEvent?.(event);
67
- const liveReload = options.liveReload ?? options.watch !== false;
68
- const errorPageTail = liveReload
69
- ? `<script>globalThis.__kodyDevErrorPage = true</script>${liveReloadScriptTag}`
70
- : '';
71
- void sweepStaleDevDirs().catch(() => { });
72
- const workDir = await mkdtemp(join(tmpdir(), devWorkDirPrefix));
73
- const reaper = await startProcessReaper({ workDir });
74
- const workerdPath = options.workerdPath ??
75
- (await ensureWorkerdBinary({
76
- onDownload: (url) => options.onStatus?.(`Downloading workerd from ${url}…`),
77
- }));
78
- const client = {
79
- apiUrl: options.apiUrl,
80
- token: options.token,
81
- fetchFn: options.fetchFn,
82
- ...(options.org ? { org: options.org } : {}),
83
- };
84
- const generations = new Set();
85
- let active;
86
- let buildFailure = null;
87
- let generationCounter = 0;
88
- let requestCounter = 0;
89
- let closed = false;
90
- let buildLoop = null;
91
- let rebuildAgain = false;
92
- const changedFiles = new Set();
93
- /** True while the watcher debounce timer has paths waiting to rebuild. */
94
- let debouncePending = false;
95
- /** Resolves when the current debounce window flushes into `requestBuild`. */
96
- let debounceFlush = null;
97
- let resolveDebounceFlush = null;
98
- let debounceTimer;
99
- const liveReloadHub = createLiveReloadHub({
100
- state: () => ({
101
- buildId: active?.id ?? null,
102
- error: buildFailure ? buildErrorView(buildFailure) : null,
103
- }),
104
- });
105
- const startedAt = new Date().toISOString();
106
- let lastRebuild = null;
107
- let lastRuntimeError = null;
108
- let buildFailureAt = startedAt;
109
- let markStarted = () => { };
110
- const started = new Promise((resolve) => {
111
- markStarted = resolve;
112
- });
113
- const killAllSync = () => {
114
- for (const generation of generations) {
115
- try {
116
- process.kill(generation.workerd.pid, 'SIGKILL');
117
- }
118
- catch { }
119
- }
120
- try {
121
- rmSync(workDir, { recursive: true, force: true });
122
- }
123
- catch { }
124
- };
125
- process.once('exit', killAllSync);
126
- const proxy = createServer((req, res) => {
127
- void handleRequest(req, res);
128
- });
129
- try {
130
- await listenDevServer(proxy, {
131
- host,
132
- port: options.port ?? options.defaultPort ?? 0,
133
- explicit: options.port !== undefined,
134
- });
135
- }
136
- catch (error) {
137
- process.off('exit', killAllSync);
138
- reaper.close();
139
- await rm(workDir, { recursive: true, force: true });
140
- throw error;
141
- }
142
- const address = proxy.address();
143
- const hostedUrl = `http://${host}:${address.port}`;
144
- try {
145
- await options.onListening?.({
146
- port: address.port,
147
- hostedUrl,
148
- appBasePath,
149
- });
150
- }
151
- catch (error) {
152
- // Port is bound but startPackageAppDev has not returned yet — close the
153
- // listen handle now or the process stays alive after the throw.
154
- process.off('exit', killAllSync);
155
- reaper.close();
156
- proxy.closeAllConnections();
157
- await new Promise((resolve) => {
158
- proxy.close(() => resolve());
159
- });
160
- await rm(workDir, { recursive: true, force: true });
161
- throw error;
162
- }
163
- const contextFor = (client) => buildLocalPackageContext({
164
- kodyId: options.manifest.kodyId,
165
- packageId: `local:${options.manifest.kodyId}`,
166
- hostedUrl,
167
- appBasePath,
168
- clientModuleUrl: client ? clientModuleUrlFor(client) : null,
169
- });
170
- const clientModuleUrlFor = (client) => `${hostedUrl}${appBasePath}/_assets/${client.name}`;
171
- const mockFetchGateway = await resolveMockFetchGateway({
172
- target: options.target,
173
- packageRoot: root,
174
- passthroughHosts: options.passthroughHosts,
175
- allowPrivateNetwork: options.allowPrivateNetwork,
176
- onStatus: options.onStatus,
177
- });
178
- const bridge = await startLocalRuntimeBridge({
179
- runSecret,
180
- forwardCall: async (call, signal) => {
181
- const mocked = tryHandleMockGatewayFetchCall({
182
- gateway: mockFetchGateway,
183
- path: call.path,
184
- args: call.args,
185
- signal,
186
- });
187
- if (mocked)
188
- return await mocked;
189
- return await callCapabilityProxy({
190
- ...client,
191
- ...call,
192
- signal,
193
- });
194
- },
195
- forwardGatewayFetchStream: async ({ request, response, signal }) => {
196
- await forwardLocalGatewayFetchStream({
197
- request,
198
- response,
199
- signal,
200
- client,
201
- ...(mockFetchGateway ? { mockFetchGateway } : {}),
202
- });
203
- },
204
- });
205
- const app = options.manifest.app;
206
- const entryPath = resolvePackagePath(options.manifest, app.entry);
207
- const bundler = createDevBundler({ entryPath, root });
208
- const clientBundler = app.client
209
- ? createDevClientBundler({
210
- entryPath: resolvePackagePath(options.manifest, app.client),
211
- root,
212
- externals: app.clientExternals,
213
- })
214
- : null;
215
- const assetsDir = app.assets ? resolve(root, app.assets) : null;
216
- const prebuild = options.manifest.dev?.prebuild;
217
- let prebuildRunning = false;
218
- let prebuildSettledAt = 0;
219
- /** `performance.now()` until which onChange ignores events (failed-prebuild absorb). */
220
- let ignoreWatcherUntil = 0;
221
- let prebuildAbort;
222
- const workerdEnv = { ...process.env, [runSecretEnvVar]: runSecret };
223
- delete workerdEnv[apiTokenEnvVar];
224
- function requestBuild(paths) {
225
- if (closed)
226
- return Promise.resolve();
227
- for (const path of paths)
228
- changedFiles.add(path);
229
- if (buildLoop) {
230
- rebuildAgain = true;
231
- return buildLoop;
232
- }
233
- buildLoop = (async () => {
234
- do {
235
- rebuildAgain = false;
236
- const files = [...changedFiles];
237
- changedFiles.clear();
238
- await buildOnce(files);
239
- } while (rebuildAgain && !closed);
240
- })().finally(() => {
241
- buildLoop = null;
242
- });
243
- return buildLoop;
244
- }
245
- async function buildOnce(files) {
246
- const started = performance.now();
247
- emit({ type: 'rebuild_start', files: files.map((file) => relative(root, file) || file) });
248
- const assetsChanged = assetsDir !== null &&
249
- files.some((file) => file === assetsDir || file.startsWith(`${assetsDir}${sep}`));
250
- try {
251
- if (prebuild) {
252
- await runPrebuildStep(prebuild);
253
- }
254
- const [bundle, client] = await Promise.all([
255
- bundler.build(),
256
- clientBundler ? clientBundler.build() : Promise.resolve(null),
257
- ]);
258
- const midBuildEdits = (await watcher?.track([...bundle.inputs, ...(client?.inputs ?? []), options.manifest.packageJsonPath], { ignoreChanges: files })) ?? [];
259
- // Queue mid-build edits for the next loop iteration directly — do not
260
- // call onChange (debounced); chokidar may already have the same paths
261
- // pending and would double-schedule a rebuild after debounce.
262
- if (midBuildEdits.length > 0) {
263
- for (const path of midBuildEdits)
264
- changedFiles.add(path);
265
- rebuildAgain = true;
266
- }
267
- if (active &&
268
- !buildFailure &&
269
- bundle.code === active.code &&
270
- client?.name === active.client?.name) {
271
- // Still stamp lastRebuild so agents polling lastRebuild.at see
272
- // the no-op rebuild finish (status already flipped building→ready).
273
- lastRebuild = { ms: elapsed(started), at: new Date().toISOString() };
274
- emit({
275
- type: 'rebuild_ok',
276
- ms: lastRebuild.ms,
277
- buildId: active.id,
278
- restarted: false,
279
- });
280
- if (assetsChanged || prebuild) {
281
- liveReloadHub.broadcast({ event: 'reload', data: { buildId: active.id } });
282
- }
283
- return;
284
- }
285
- const generation = await startGeneration(bundle, client);
286
- if (closed) {
287
- await stopGeneration(generation);
288
- return;
289
- }
290
- const previous = active;
291
- active = generation;
292
- buildFailure = null;
293
- if (previous)
294
- retireGeneration(previous);
295
- lastRuntimeError = null;
296
- lastRebuild = { ms: elapsed(started), at: new Date().toISOString() };
297
- emit({ type: 'rebuild_ok', ms: lastRebuild.ms, buildId: generation.id, restarted: true });
298
- liveReloadHub.broadcast({ event: 'reload', data: { buildId: generation.id } });
299
- }
300
- catch (error) {
301
- buildFailure = toBuildFailure(error);
302
- buildFailureAt = new Date().toISOString();
303
- const [first] = buildFailure.diagnostics;
304
- emit({
305
- type: 'build_error',
306
- ms: elapsed(started),
307
- message: buildFailure.message,
308
- file: first?.file ?? null,
309
- line: first?.line ?? null,
310
- col: first?.col ?? null,
311
- diagnostics: buildFailure.diagnostics,
312
- });
313
- liveReloadHub.broadcast({ event: 'build_error', data: buildErrorView(buildFailure) });
314
- }
315
- }
316
- let clearWatcherPending = null;
317
- async function runPrebuildStep(command) {
318
- prebuildRunning = true;
319
- prebuildAbort = new AbortController();
320
- let failed = false;
321
- try {
322
- await runPrebuild({
323
- command,
324
- cwd: root,
325
- signal: prebuildAbort.signal,
326
- onSpawn: (pid) => reaper.trackGroup(pid),
327
- onExit: (pid) => reaper.untrackGroup(pid),
328
- onLine: (line, stream) => emit({
329
- type: 'log',
330
- source: 'prebuild',
331
- level: stream === 'stderr' ? 'warn' : 'log',
332
- message: redact(line),
333
- request: null,
334
- }),
335
- });
336
- }
337
- catch (error) {
338
- failed = true;
339
- throw error;
340
- }
341
- finally {
342
- prebuildAbort = undefined;
343
- prebuildRunning = false;
344
- prebuildSettledAt = performance.now();
345
- // Absorb writes even when prebuild fails — otherwise the 1s poll
346
- // treats partial/failed output as new edits and loops rebuilds.
347
- await watcher?.rebaseline();
348
- if (failed) {
349
- // Drop chokidar echoes of the failed prebuild / trigger burst so
350
- // they cannot restart the loop after buildLoop clears.
351
- changedFiles.clear();
352
- rebuildAgain = false;
353
- clearWatcherPending?.();
354
- ignoreWatcherUntil = performance.now() + failedPrebuildAbsorbMs;
355
- }
356
- }
357
- }
358
- async function startGeneration(bundle, client) {
359
- const id = ++generationCounter;
360
- const dir = join(workDir, `g${id}`);
361
- await writeWorkerFiles({
362
- workDir: dir,
363
- code: bundle.code,
364
- packageContext: contextFor(client),
365
- packageRoot: root,
366
- mockStorage: options.target === 'mock',
367
- bridgePort: bridge.port,
368
- allowPrivateNetwork: options.allowPrivateNetwork,
369
- apiUrl: options.apiUrl,
370
- token: options.token,
371
- org: options.org,
372
- fetchFn: options.fetchFn,
373
- depResolve: options.depResolve,
374
- mockFetchGateway,
375
- onStatus: options.onStatus,
376
- });
377
- let trackedPid;
378
- let workerd;
379
- try {
380
- workerd = await startWorkerd({
381
- workerdPath,
382
- configPath: join(dir, 'config.capnp'),
383
- cwd: dir,
384
- env: workerdEnv,
385
- onSpawn: (pid) => {
386
- trackedPid = pid;
387
- reaper.track(pid);
388
- },
389
- onStdoutLine: (line) => emit(parseWorkerdStdoutLine(line)),
390
- onStderrLine: (line) => {
391
- const cleaned = cleanWorkerdStderrLine(line);
392
- if (cleaned === null)
393
- return;
394
- emit({
395
- type: 'log',
396
- source: 'workerd',
397
- level: 'error',
398
- message: redact(cleaned),
399
- request: null,
400
- });
401
- },
402
- });
403
- }
404
- catch (error) {
405
- // onSpawn tracks before listen; a failed start never reaches the
406
- // exited/untrack path, so drop the pid here before pid reuse.
407
- if (trackedPid !== undefined)
408
- reaper.untrack(trackedPid);
409
- await rm(dir, { recursive: true, force: true }).catch(() => { });
410
- throw error;
411
- }
412
- const generation = {
413
- id,
414
- dir,
415
- workerd,
416
- code: bundle.code,
417
- client,
418
- mapStack: createStackMapper({
419
- sourceMap: bundle.sourceMap,
420
- userModule: localWorkerModuleNames.user,
421
- }),
422
- inflight: 0,
423
- retired: false,
424
- stopped: false,
425
- };
426
- generations.add(generation);
427
- void workerd.exited.then((detail) => {
428
- reaper.untrack(workerd.pid);
429
- if (closed || generation.retired || active !== generation)
430
- return;
431
- active = undefined;
432
- buildFailure = {
433
- message: `workerd stopped unexpectedly (${detail}). Save a file to restart it.`,
434
- diagnostics: [],
435
- };
436
- options.onError?.(buildFailure.message);
437
- });
438
- return generation;
439
- }
440
- function retireGeneration(generation) {
441
- generation.retired = true;
442
- if (generation.inflight === 0) {
443
- void stopGeneration(generation);
444
- return;
445
- }
446
- setTimeout(() => void stopGeneration(generation), drainTimeoutMs).unref();
447
- }
448
- async function stopGeneration(generation) {
449
- if (generation.stopped)
450
- return;
451
- generation.stopped = true;
452
- generation.retired = true;
453
- await generation.workerd.kill();
454
- reaper.untrack(generation.workerd.pid);
455
- generations.delete(generation);
456
- await rm(generation.dir, { recursive: true, force: true });
457
- }
458
- async function waitForBuild() {
459
- // Flush any watcher debounce first so a save → immediate fetch cannot
460
- // slip through on the previous generation while the timer is still open.
461
- const flush = debounceFlush;
462
- if (flush)
463
- await flush;
464
- const pending = buildLoop ?? (active || buildFailure ? null : started);
465
- if (!pending)
466
- return;
467
- await Promise.race([
468
- pending.catch(() => { }),
469
- new Promise((resolve) => setTimeout(resolve, rebuildGateMs).unref()),
470
- ]);
471
- }
472
- function status() {
473
- const [first] = buildFailure?.diagnostics ?? [];
474
- return {
475
- ok: buildFailure === null && active !== undefined,
476
- state: buildLoop || debouncePending
477
- ? 'building'
478
- : buildFailure
479
- ? 'build_error'
480
- : active
481
- ? 'ready'
482
- : 'starting',
483
- buildId: active?.id ?? null,
484
- url: `${hostedUrl}${appBasePath || '/'}`,
485
- port: address.port,
486
- basePath: appBasePath,
487
- target: options.target,
488
- package: {
489
- name: options.manifest.name,
490
- kodyId: options.manifest.kodyId,
491
- root,
492
- },
493
- pid: process.pid,
494
- startedAt,
495
- lastRebuild,
496
- lastError: buildFailure
497
- ? {
498
- kind: 'build',
499
- message: buildFailure.message,
500
- file: first?.file ?? null,
501
- line: first?.line ?? null,
502
- col: first?.col ?? null,
503
- at: buildFailureAt,
504
- }
505
- : lastRuntimeError,
506
- };
507
- }
508
- function handleDevRoute(req, res) {
509
- const pathname = stripMount(new URL(req.url ?? '/', hostedUrl).pathname, appBasePath);
510
- if (pathname === devStatusPath) {
511
- res.writeHead(200, {
512
- 'content-type': 'application/json; charset=utf-8',
513
- 'cache-control': 'no-store',
514
- });
515
- res.end(`${JSON.stringify(status(), null, 2)}\n`);
516
- return true;
517
- }
518
- if (!liveReload)
519
- return false;
520
- if (pathname === liveReloadEventsPath) {
521
- liveReloadHub.handleEvents(req, res);
522
- return true;
523
- }
524
- if (pathname === liveReloadClientPath) {
525
- res.writeHead(200, {
526
- 'content-type': 'text/javascript; charset=utf-8',
527
- 'cache-control': 'no-store',
528
- });
529
- res.end(liveReloadClientSource);
530
- return true;
531
- }
532
- return false;
533
- }
534
- async function handleRequest(req, res) {
535
- try {
536
- if (handleDevRoute(req, res))
537
- return;
538
- await waitForBuild();
539
- const assetPath = parseDevAssetPath(stripMount(new URL(req.url ?? '/', hostedUrl).pathname, appBasePath));
540
- if (assetPath !== null) {
541
- const client = active?.client ?? null;
542
- await serveDevAsset({
543
- req,
544
- res,
545
- relativePath: assetPath,
546
- assetsDir,
547
- client,
548
- clientModuleUrl: client ? clientModuleUrlFor(client) : null,
549
- appBasePath,
550
- });
551
- return;
552
- }
553
- if (buildFailure) {
554
- sendDevError(req, res, 500, buildErrorView(buildFailure), {
555
- htmlTail: errorPageTail,
556
- });
557
- return;
558
- }
559
- const generation = active;
560
- if (!generation) {
561
- res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' });
562
- res.end(closed ? 'kody dev is shutting down.\n' : 'kody dev is still starting.\n');
563
- return;
564
- }
565
- generation.inflight += 1;
566
- try {
567
- await forwardRequest(generation, req, res);
568
- }
569
- finally {
570
- generation.inflight -= 1;
571
- if (generation.retired && generation.inflight === 0) {
572
- void stopGeneration(generation);
573
- }
574
- }
575
- }
576
- catch (error) {
577
- const message = error instanceof Error ? error.message : String(error);
578
- options.onError?.(`Dev proxy error: ${message}`);
579
- if (!res.headersSent) {
580
- res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
581
- res.end(`Dev proxy error: ${message}\n`);
582
- }
583
- else if (!res.writableEnded) {
584
- res.destroy();
585
- }
586
- }
587
- }
588
- function forwardRequest(generation, req, res) {
589
- const incomingUrl = new URL(req.url ?? '/', hostedUrl);
590
- const restPath = stripMount(incomingUrl.pathname, appBasePath);
591
- const forwardUrl = new URL(restPath + incomingUrl.search, `http://127.0.0.1:${generation.workerd.port}`);
592
- const tag = {
593
- id: String(++requestCounter),
594
- method: req.method ?? 'GET',
595
- path: restPath + incomingUrl.search,
596
- };
597
- const headers = {
598
- ...req.headers,
599
- host: `127.0.0.1:${generation.workerd.port}`,
600
- [runSecretHeader]: runSecret,
601
- [devRequestIdHeader]: tag.id,
602
- };
603
- return new Promise((resolve, reject) => {
604
- const upstream = httpRequest(forwardUrl, { method: req.method, headers }, (upstreamRes) => {
605
- if (upstreamRes.headers[devErrorHeader]) {
606
- void readStream(upstreamRes)
607
- .then((raw) => {
608
- respondWithRuntimeError(generation, req, res, tag, raw);
609
- resolve();
610
- })
611
- .catch(reject);
612
- return;
613
- }
614
- const status = upstreamRes.statusCode ?? 502;
615
- if (status >= 500) {
616
- emit({
617
- type: 'log',
618
- source: 'app',
619
- level: 'warn',
620
- message: `responded HTTP ${status}`,
621
- request: tag,
622
- });
623
- }
624
- if (liveReload &&
625
- shouldInjectLiveReload({
626
- method: req.method,
627
- accept: req.headers.accept,
628
- status,
629
- headers: upstreamRes.headers,
630
- })) {
631
- void readStream(upstreamRes)
632
- .then((html) => {
633
- const body = Buffer.from(injectLiveReloadScript(html), 'utf8');
634
- const headers = { ...upstreamRes.headers };
635
- delete headers['transfer-encoding'];
636
- headers['content-length'] = String(body.length);
637
- res.writeHead(status, headers);
638
- res.end(body);
639
- resolve();
640
- })
641
- .catch(reject);
642
- return;
643
- }
644
- res.writeHead(status, upstreamRes.headers);
645
- upstreamRes.pipe(res);
646
- upstreamRes.on('end', () => resolve());
647
- upstreamRes.on('error', reject);
648
- });
649
- upstream.on('error', reject);
650
- res.on('close', () => {
651
- if (!res.writableFinished)
652
- upstream.destroy();
653
- resolve();
654
- });
655
- req.pipe(upstream);
656
- });
657
- }
658
- function respondWithRuntimeError(generation, req, res, tag, raw) {
659
- let message = 'Uncaught error';
660
- let stack = '';
661
- try {
662
- const parsed = JSON.parse(raw);
663
- message = `${parsed.name ?? 'Error'}: ${parsed.message ?? ''}`;
664
- stack = parsed.stack ?? message;
665
- }
666
- catch {
667
- stack = raw;
668
- }
669
- const mapped = redact(generation.mapStack(stack));
670
- const fix = runtimeErrorFix(message);
671
- lastRuntimeError = {
672
- kind: 'runtime',
673
- message: redact(message),
674
- stack: mapped,
675
- request: tag,
676
- ...(fix ? { fix } : {}),
677
- at: new Date().toISOString(),
678
- };
679
- emit({
680
- type: 'runtime_error',
681
- message: redact(message),
682
- stack: mapped,
683
- request: tag,
684
- ...(fix ? { fix } : {}),
685
- });
686
- const view = {
687
- kind: 'runtime',
688
- title: redact(message),
689
- detail: fix ? `${mapped}\n\nfix: ${fix}` : mapped,
690
- request: `${tag.method} ${tag.path}`,
691
- };
692
- liveReloadHub.broadcast({ event: 'runtime_error', data: view });
693
- sendDevError(req, res, 500, view, { htmlTail: errorPageTail });
694
- }
695
- const watcher = options.watch === false
696
- ? null
697
- : (() => {
698
- const pending = new Set();
699
- clearWatcherPending = () => {
700
- pending.clear();
701
- clearTimeout(debounceTimer);
702
- debouncePending = false;
703
- const resolve = resolveDebounceFlush;
704
- resolveDebounceFlush = null;
705
- debounceFlush = null;
706
- resolve?.();
707
- };
708
- return createDevWatcher({
709
- root,
710
- ignore: options.manifest.dev?.ignore,
711
- onChange: (path) => {
712
- if (closed)
713
- return;
714
- const now = performance.now();
715
- // Soft absorb: fingerprint already advanced by the
716
- // poller — prebuild's own writes / brief settle chatter.
717
- if (prebuildRunning || now - prebuildSettledAt < prebuildSettleMs) {
718
- return;
719
- }
720
- // Hard defer after a *failed* prebuild: leave the
721
- // poll fingerprint so a real save in this window is
722
- // seen again after absorb (Bugbot: do not drop).
723
- if (now < ignoreWatcherUntil) {
724
- return false;
725
- }
726
- // Fold mid-build watcher events into the active loop
727
- // (including another save of a file already building).
728
- // Debouncing them instead schedules a second rebuild
729
- // after buildLoop clears (often a no-op echo).
730
- if (buildLoop) {
731
- changedFiles.add(path);
732
- rebuildAgain = true;
733
- return;
734
- }
735
- pending.add(path);
736
- debouncePending = true;
737
- if (!debounceFlush) {
738
- debounceFlush = new Promise((resolve) => {
739
- resolveDebounceFlush = resolve;
740
- });
741
- }
742
- clearTimeout(debounceTimer);
743
- debounceTimer = setTimeout(() => {
744
- const paths = [...pending];
745
- pending.clear();
746
- debouncePending = false;
747
- // Start the build before releasing waiters so
748
- // waitForBuild sees buildLoop, not a ready gap.
749
- const build = requestBuild(paths);
750
- const resolve = resolveDebounceFlush;
751
- resolveDebounceFlush = null;
752
- debounceFlush = null;
753
- resolve?.();
754
- void build;
755
- }, options.debounceMs ?? defaultDebounceMs);
756
- },
757
- });
758
- })();
759
- const close = async () => {
760
- if (closed)
761
- return;
762
- closed = true;
763
- process.off('exit', killAllSync);
764
- clearTimeout(debounceTimer);
765
- debouncePending = false;
766
- const resolve = resolveDebounceFlush;
767
- resolveDebounceFlush = null;
768
- debounceFlush = null;
769
- resolve?.();
770
- prebuildAbort?.abort();
771
- await watcher?.close();
772
- await buildLoop?.catch(() => { });
773
- await bundler.dispose();
774
- await clientBundler?.dispose();
775
- await Promise.all([...generations].map((generation) => stopGeneration(generation)));
776
- reaper.close();
777
- await bridge.close();
778
- liveReloadHub.close();
779
- proxy.closeAllConnections();
780
- await new Promise((resolve) => {
781
- proxy.close(() => resolve());
782
- });
783
- await rm(workDir, { recursive: true, force: true });
784
- };
785
- try {
786
- await Promise.all([requestBuild([]), watcher?.ready]);
787
- }
788
- catch (error) {
789
- await close();
790
- throw error;
791
- }
792
- finally {
793
- markStarted();
794
- }
795
- if (options.watch === false && buildFailure) {
796
- const message = buildFailure.message;
797
- await close();
798
- throw new Error(message);
799
- }
800
- if (active)
801
- options.onStatus?.(`App ready at ${hostedUrl}${appBasePath || '/'}`);
802
- const fetchPath = async (path, init = {}) => {
803
- const url = new URL(joinUrlPath(appBasePath, path), hostedUrl);
804
- const response = await fetch(url, {
805
- method: init.method ?? 'GET',
806
- headers: init.headers,
807
- body: init.body,
808
- });
809
- const body = await response.text();
810
- const headers = {};
811
- response.headers.forEach((value, key) => {
812
- headers[key] = value;
813
- });
814
- return { status: response.status, headers, body };
815
- };
816
- return {
817
- url: hostedUrl,
818
- port: address.port,
819
- hostedUrl,
820
- appBasePath,
821
- get packageContext() {
822
- return contextFor(active?.client ?? null);
823
- },
824
- fetchPath,
825
- status,
826
- close,
827
- };
828
- }
829
- function elapsed(started) {
830
- return Math.round(performance.now() - started);
831
- }
832
- function toBuildFailure(error) {
833
- if (error instanceof BundleError) {
834
- return { message: error.message, diagnostics: error.diagnostics };
835
- }
836
- return {
837
- message: redact(error instanceof Error ? error.message : String(error)),
838
- diagnostics: [],
839
- };
840
- }
841
- function buildErrorView(failure) {
842
- const [first] = failure.diagnostics;
843
- return {
844
- kind: 'build',
845
- title: first
846
- ? `${first.file ?? 'bundle'}${first.line !== null ? `:${first.line}:${first.col}` : ''} ${first.message}`
847
- : (failure.message.split('\n')[0] ?? 'Build failed'),
848
- detail: failure.diagnostics.length > 0
849
- ? failure.diagnostics.map(formatBundleDiagnostic).join('\n\n')
850
- : failure.message,
851
- };
852
- }
853
- async function readStream(stream) {
854
- const chunks = [];
855
- for await (const chunk of stream) {
856
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
857
- }
858
- return Buffer.concat(chunks).toString('utf8');
859
- }
860
- async function writeWorkerFiles(input) {
861
- await mkdir(input.workDir, { recursive: true });
862
- const packageGraph = await resolveLocalPackageGraph({
863
- code: input.code,
864
- apiUrl: input.apiUrl,
865
- token: input.token,
866
- ...(input.org ? { org: input.org } : {}),
867
- fetchFn: input.fetchFn,
868
- ...(input.depResolve ? { depResolve: input.depResolve } : {}),
869
- ...(input.packageRoot ? { packageRoot: input.packageRoot } : {}),
870
- onStatus: input.onStatus,
871
- });
872
- const files = { entry: 'entry.js', user: 'main.js', runtime: 'runtime.js' };
873
- let packageModules = await writePackageModuleFiles(input.workDir, packageGraph, writeFile, join);
874
- let gatewayFetchShimModules = packageGraph.modules
875
- .map((module) => module.name)
876
- .filter((name) => name === localExecuteGatewayFetchShimModuleName);
877
- if (input.mockFetchGateway) {
878
- const installed = await installMockFetchShimModules({
879
- workDir: input.workDir,
880
- packageModules,
881
- });
882
- packageModules = installed.packageModules;
883
- gatewayFetchShimModules = installed.sideEffectModules;
884
- }
885
- await writeFile(join(input.workDir, files.entry), createPackageAppEntrySource({ sideEffectModules: gatewayFetchShimModules }));
886
- await writeFile(join(input.workDir, files.user), input.code);
887
- await writeFile(join(input.workDir, files.runtime), createPackageLocalRuntimeModuleSource({
888
- packageContext: input.packageContext,
889
- mockStorage: input.mockStorage,
890
- }));
891
- await writeFile(join(input.workDir, localWorkerModuleNames.runtimeFlatAlias), createRuntimeFlatAliasSource());
892
- await writeFile(join(input.workDir, 'config.capnp'), createWorkerdConfig({
893
- bridgePort: input.bridgePort,
894
- files,
895
- packageModules,
896
- allowPrivateNetwork: input.allowPrivateNetwork,
897
- }));
898
- }
899
- function normalizeBasePath(value) {
900
- const trimmed = value.trim();
901
- if (!trimmed || trimmed === '/')
902
- return '';
903
- const withSlash = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
904
- return withSlash.replace(/\/+$/, '');
905
- }
906
- function stripMount(pathname, appBasePath) {
907
- if (!appBasePath)
908
- return pathname || '/';
909
- if (pathname === appBasePath)
910
- return '/';
911
- if (pathname.startsWith(`${appBasePath}/`)) {
912
- return pathname.slice(appBasePath.length) || '/';
913
- }
914
- return pathname || '/';
915
- }
916
- function joinUrlPath(base, path) {
917
- const rest = path.startsWith('/') ? path : `/${path}`;
918
- if (!base)
919
- return rest;
920
- return `${base}${rest === '/' ? '' : rest}` || base;
921
- }
922
- //# sourceMappingURL=package-app-dev.js.map