toiljs 0.0.115 → 0.0.117

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 (326) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +16 -7
  3. package/TYPESCRIPT_LAW.md +1946 -2073
  4. package/build/backend/.tsbuildinfo +1 -1
  5. package/build/cli/.tsbuildinfo +1 -1
  6. package/build/cli/index.js +2375 -258
  7. package/build/client/.tsbuildinfo +1 -1
  8. package/build/client/dev/devtools.js +1 -1
  9. package/build/client/dev/error-overlay.js +1 -1
  10. package/build/client/routing/mount.js +1 -1
  11. package/build/compiler/.tsbuildinfo +1 -1
  12. package/build/compiler/auth-emails.js +7 -3
  13. package/build/compiler/emails.js +1 -1
  14. package/build/compiler/index.d.ts +1 -0
  15. package/build/compiler/index.js +25 -4
  16. package/build/compiler/pages.js +2 -3
  17. package/build/compiler/prerender.d.ts +3 -8
  18. package/build/compiler/prerender.js +88 -127
  19. package/build/compiler/ssg.js +3 -4
  20. package/build/compiler/template-build.js +3 -4
  21. package/build/compiler/toil-docs.generated.js +6 -5
  22. package/build/compiler/vite.js +3 -6
  23. package/build/devserver/.tsbuildinfo +1 -1
  24. package/build/devserver/db/database.js +7 -3
  25. package/build/devserver/db/types.js +1 -1
  26. package/build/devserver/production.js +4 -3
  27. package/build/devserver/runtime/crypto.d.ts +1 -1
  28. package/build/io/.tsbuildinfo +1 -1
  29. package/build/logger/.tsbuildinfo +1 -1
  30. package/build/shared/.tsbuildinfo +1 -1
  31. package/examples/basic/client/routes/analytics.tsx +7 -5
  32. package/examples/basic/server/tsconfig.json +1 -3
  33. package/package.json +45 -44
  34. package/presets/no-uint8array-tostring.js +120 -153
  35. package/presets/oxlint.d.ts +5 -0
  36. package/presets/oxlint.js +224 -0
  37. package/server/runtime/tsconfig.json +1 -3
  38. package/tsconfig.json +2 -11
  39. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -38
  40. package/.github/ISSUE_TEMPLATE/bug_report.yml +0 -90
  41. package/.github/ISSUE_TEMPLATE/config.yml +0 -8
  42. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
  43. package/.github/PULL_REQUEST_TEMPLATE.md +0 -43
  44. package/.github/changelog-config.json +0 -45
  45. package/.github/dependabot.yml +0 -27
  46. package/.github/workflows/ci.yml +0 -222
  47. package/.vscode/settings.json +0 -10
  48. package/docs/README.md +0 -107
  49. package/docs/auth/README.md +0 -104
  50. package/docs/auth/configuration.md +0 -105
  51. package/docs/auth/emails.md +0 -92
  52. package/docs/auth/extending.md +0 -202
  53. package/docs/auth/how-it-works.md +0 -138
  54. package/docs/auth/usage.md +0 -188
  55. package/docs/backend/README.md +0 -143
  56. package/docs/backend/data.md +0 -351
  57. package/docs/backend/rest.md +0 -402
  58. package/docs/backend/rpc.md +0 -226
  59. package/docs/background/README.md +0 -114
  60. package/docs/background/daemons.md +0 -276
  61. package/docs/background/derive.md +0 -179
  62. package/docs/cli/README.md +0 -379
  63. package/docs/concepts/ai-guide.md +0 -132
  64. package/docs/concepts/config.md +0 -416
  65. package/docs/concepts/decorators.md +0 -127
  66. package/docs/concepts/security.md +0 -108
  67. package/docs/concepts/tiers.md +0 -166
  68. package/docs/concepts/types.md +0 -216
  69. package/docs/database/README.md +0 -143
  70. package/docs/database/capacity.md +0 -350
  71. package/docs/database/counters.md +0 -174
  72. package/docs/database/documents.md +0 -277
  73. package/docs/database/events.md +0 -307
  74. package/docs/database/membership.md +0 -246
  75. package/docs/database/setup.md +0 -155
  76. package/docs/database/unique.md +0 -216
  77. package/docs/database/views.md +0 -246
  78. package/docs/frontend/README.md +0 -104
  79. package/docs/frontend/components.md +0 -286
  80. package/docs/frontend/data-fetching.md +0 -260
  81. package/docs/frontend/images.md +0 -148
  82. package/docs/frontend/metadata.md +0 -344
  83. package/docs/frontend/navigation.md +0 -296
  84. package/docs/frontend/rendering.md +0 -236
  85. package/docs/frontend/routing.md +0 -346
  86. package/docs/frontend/scripts.md +0 -118
  87. package/docs/frontend/search.md +0 -191
  88. package/docs/frontend/styling.md +0 -147
  89. package/docs/frontend/toil-global.md +0 -216
  90. package/docs/getting-started/README.md +0 -81
  91. package/docs/getting-started/create-project.md +0 -131
  92. package/docs/getting-started/deploy.md +0 -101
  93. package/docs/getting-started/first-app.md +0 -215
  94. package/docs/getting-started/installation.md +0 -124
  95. package/docs/getting-started/migrating.md +0 -125
  96. package/docs/getting-started/project-structure.md +0 -163
  97. package/docs/introduction/README.md +0 -66
  98. package/docs/introduction/design-principles.md +0 -81
  99. package/docs/introduction/distributed.md +0 -91
  100. package/docs/introduction/how-it-works.md +0 -121
  101. package/docs/introduction/hyperscale.md +0 -70
  102. package/docs/introduction/modern-stack.md +0 -85
  103. package/docs/introduction/vs-other-frameworks.md +0 -64
  104. package/docs/introduction/why-toil.md +0 -99
  105. package/docs/llms.txt +0 -95
  106. package/docs/realtime/README.md +0 -102
  107. package/docs/realtime/channels.md +0 -211
  108. package/docs/realtime/streams.md +0 -369
  109. package/docs/services/README.md +0 -60
  110. package/docs/services/analytics.md +0 -279
  111. package/docs/services/caching.md +0 -175
  112. package/docs/services/cookies.md +0 -235
  113. package/docs/services/crypto.md +0 -209
  114. package/docs/services/email.md +0 -289
  115. package/docs/services/environment.md +0 -141
  116. package/docs/services/ratelimit.md +0 -174
  117. package/docs/services/time.md +0 -85
  118. package/eslint.config.js +0 -57
  119. package/examples/basic/client/routes/docs/[...slug].tsx +0 -12
  120. package/presets/eslint.js +0 -88
  121. package/src/backend/index.ts +0 -204
  122. package/src/cli/configure.ts +0 -363
  123. package/src/cli/create.ts +0 -924
  124. package/src/cli/db.ts +0 -158
  125. package/src/cli/diagnostics.ts +0 -665
  126. package/src/cli/doctor.ts +0 -982
  127. package/src/cli/features.ts +0 -170
  128. package/src/cli/index.ts +0 -326
  129. package/src/cli/notify.ts +0 -120
  130. package/src/cli/proc.ts +0 -56
  131. package/src/cli/ui.ts +0 -169
  132. package/src/cli/update.ts +0 -248
  133. package/src/cli/updates.ts +0 -92
  134. package/src/cli/validate.ts +0 -31
  135. package/src/cli/version-check.ts +0 -125
  136. package/src/client/auth.ts +0 -869
  137. package/src/client/channel/channel.ts +0 -146
  138. package/src/client/components/Form.tsx +0 -65
  139. package/src/client/components/Image.tsx +0 -160
  140. package/src/client/components/Script.tsx +0 -113
  141. package/src/client/components/Slot.tsx +0 -21
  142. package/src/client/dev/devtools.tsx +0 -1089
  143. package/src/client/dev/error-overlay.tsx +0 -225
  144. package/src/client/errors.ts +0 -11
  145. package/src/client/head/head.ts +0 -182
  146. package/src/client/head/metadata.ts +0 -110
  147. package/src/client/index.ts +0 -130
  148. package/src/client/navigation/Link.tsx +0 -108
  149. package/src/client/navigation/NavLink.tsx +0 -86
  150. package/src/client/navigation/navigation.ts +0 -235
  151. package/src/client/navigation/prefetch.ts +0 -169
  152. package/src/client/navigation/scroll.ts +0 -53
  153. package/src/client/routing/Router.tsx +0 -216
  154. package/src/client/routing/action.ts +0 -122
  155. package/src/client/routing/error-boundary.tsx +0 -43
  156. package/src/client/routing/hooks.ts +0 -140
  157. package/src/client/routing/lazy.ts +0 -77
  158. package/src/client/routing/loader.ts +0 -381
  159. package/src/client/routing/match.ts +0 -47
  160. package/src/client/routing/mount.tsx +0 -90
  161. package/src/client/routing/params-context.ts +0 -10
  162. package/src/client/routing/slot-context.ts +0 -7
  163. package/src/client/rpc.ts +0 -97
  164. package/src/client/search/search.ts +0 -189
  165. package/src/client/search/use-page-search.ts +0 -73
  166. package/src/client/ssr/markers.tsx +0 -172
  167. package/src/client/stream/client.ts +0 -237
  168. package/src/client/types.ts +0 -73
  169. package/src/compiler/auth-emails.ts +0 -312
  170. package/src/compiler/config.ts +0 -369
  171. package/src/compiler/docs.ts +0 -127
  172. package/src/compiler/email-preview.ts +0 -314
  173. package/src/compiler/emails.ts +0 -404
  174. package/src/compiler/fonts.ts +0 -89
  175. package/src/compiler/generate.ts +0 -471
  176. package/src/compiler/image-blur.ts +0 -42
  177. package/src/compiler/image-report.ts +0 -88
  178. package/src/compiler/index.ts +0 -1362
  179. package/src/compiler/pages.ts +0 -49
  180. package/src/compiler/plugin.ts +0 -391
  181. package/src/compiler/prerender.ts +0 -263
  182. package/src/compiler/routes.ts +0 -170
  183. package/src/compiler/seo.ts +0 -415
  184. package/src/compiler/sri.ts +0 -144
  185. package/src/compiler/ssg.ts +0 -177
  186. package/src/compiler/ssr-codegen.ts +0 -85
  187. package/src/compiler/template-build.ts +0 -676
  188. package/src/compiler/template.ts +0 -262
  189. package/src/compiler/toil-docs.generated.ts +0 -77
  190. package/src/compiler/vite.ts +0 -245
  191. package/src/devserver/analytics/index.ts +0 -317
  192. package/src/devserver/config/dotenv.ts +0 -102
  193. package/src/devserver/config/env.ts +0 -30
  194. package/src/devserver/config/ratelimit.ts +0 -123
  195. package/src/devserver/daemon/catalog.ts +0 -120
  196. package/src/devserver/daemon/cron.ts +0 -87
  197. package/src/devserver/daemon/host.ts +0 -134
  198. package/src/devserver/daemon/index.ts +0 -369
  199. package/src/devserver/daemon/runtime.ts +0 -48
  200. package/src/devserver/db/catalog.ts +0 -109
  201. package/src/devserver/db/database.ts +0 -1834
  202. package/src/devserver/db/derives.ts +0 -121
  203. package/src/devserver/db/index.ts +0 -20
  204. package/src/devserver/db/routeKinds.ts +0 -191
  205. package/src/devserver/db/types.ts +0 -168
  206. package/src/devserver/email/caps.ts +0 -0
  207. package/src/devserver/email/config.ts +0 -141
  208. package/src/devserver/email/console.ts +0 -348
  209. package/src/devserver/email/index.ts +0 -155
  210. package/src/devserver/email/providers.ts +0 -131
  211. package/src/devserver/email/status.ts +0 -23
  212. package/src/devserver/email/validate.ts +0 -37
  213. package/src/devserver/email/wire.ts +0 -55
  214. package/src/devserver/http/cache.ts +0 -0
  215. package/src/devserver/http/envelope.ts +0 -157
  216. package/src/devserver/http/proxy.ts +0 -172
  217. package/src/devserver/http/runtime.ts +0 -387
  218. package/src/devserver/index.ts +0 -43
  219. package/src/devserver/production-ipc.ts +0 -63
  220. package/src/devserver/production-worker.ts +0 -83
  221. package/src/devserver/production.ts +0 -718
  222. package/src/devserver/runtime/crypto.ts +0 -587
  223. package/src/devserver/runtime/host.ts +0 -427
  224. package/src/devserver/runtime/module.ts +0 -442
  225. package/src/devserver/server.ts +0 -251
  226. package/src/devserver/ssr.ts +0 -208
  227. package/src/devserver/stream/catalog.ts +0 -106
  228. package/src/devserver/stream/host.ts +0 -42
  229. package/src/devserver/stream/index.ts +0 -301
  230. package/src/devserver/stream/manager.ts +0 -167
  231. package/src/devserver/stream/router.ts +0 -101
  232. package/src/devserver/stream/wire.ts +0 -58
  233. package/src/devserver/stream/ws.ts +0 -78
  234. package/src/devserver/wasm/sections.ts +0 -59
  235. package/src/devserver/wasm/surface.ts +0 -115
  236. package/src/io/FastMap.ts +0 -151
  237. package/src/io/FastSet.ts +0 -113
  238. package/src/io/codec.ts +0 -362
  239. package/src/io/index.ts +0 -10
  240. package/src/io/lengths.ts +0 -14
  241. package/src/io/types.ts +0 -19
  242. package/src/logger/index.ts +0 -22
  243. package/src/shared/index.ts +0 -46
  244. package/test/analytics-dev.test.ts +0 -113
  245. package/test/assembly/aspect-shim.ts +0 -33
  246. package/test/assembly/cookie.spec.ts +0 -303
  247. package/test/assembly/example.spec.ts +0 -22
  248. package/test/assembly/ssr.spec.ts +0 -95
  249. package/test/assembly.test.ts +0 -59
  250. package/test/auth-emails.test.ts +0 -118
  251. package/test/built-ssr.test.ts +0 -148
  252. package/test/channel.test.ts +0 -21
  253. package/test/config-host-port.test.ts +0 -59
  254. package/test/configure.test.ts +0 -94
  255. package/test/daemon-build.test.ts +0 -278
  256. package/test/daemon-catalog.test.ts +0 -349
  257. package/test/daemon-emulation.test.ts +0 -256
  258. package/test/db.test.ts +0 -0
  259. package/test/devserver-database.test.ts +0 -1102
  260. package/test/devserver-email.test.ts +0 -306
  261. package/test/devserver-pqauth.test.ts +0 -93
  262. package/test/devserver-secrets.test.ts +0 -63
  263. package/test/devserver.test.ts +0 -259
  264. package/test/doctor.test.ts +0 -298
  265. package/test/dom/Image.test.tsx +0 -144
  266. package/test/dom/Link.test.tsx +0 -67
  267. package/test/dom/NavLink.test.tsx +0 -37
  268. package/test/dom/Script.test.tsx +0 -48
  269. package/test/dom/action.test.tsx +0 -146
  270. package/test/dom/error-overlay.test.tsx +0 -44
  271. package/test/dom/loader.test.tsx +0 -121
  272. package/test/dom/navigation.test.ts +0 -59
  273. package/test/dom/revalidate.test.tsx +0 -38
  274. package/test/dom/route-head.test.tsx +0 -56
  275. package/test/dom/router-loading.test.tsx +0 -44
  276. package/test/dom/scroll.test.ts +0 -56
  277. package/test/dom/slot.test.tsx +0 -131
  278. package/test/dom/use-metadata.test.tsx +0 -58
  279. package/test/dom/view-transitions.test.tsx +0 -53
  280. package/test/dynamic-routing.test.ts +0 -132
  281. package/test/email-console.test.ts +0 -86
  282. package/test/email-preview.test.ts +0 -73
  283. package/test/emails.test.ts +0 -58
  284. package/test/errors.test.ts +0 -21
  285. package/test/example-guestbook.test.ts +0 -123
  286. package/test/features.test.ts +0 -149
  287. package/test/fixtures/bignum-wire/spec.ts +0 -25
  288. package/test/fixtures/daemon-app.ts +0 -65
  289. package/test/fixtures/stream-echo.ts +0 -26
  290. package/test/fixtures/stream-gate.ts +0 -28
  291. package/test/fixtures/stream-trap.ts +0 -18
  292. package/test/fixtures/stream-typed.ts +0 -41
  293. package/test/fonts.test.ts +0 -28
  294. package/test/global-setup.ts +0 -17
  295. package/test/head.test.ts +0 -42
  296. package/test/image-blur.test.ts +0 -50
  297. package/test/io.test.ts +0 -117
  298. package/test/metadata.test.ts +0 -40
  299. package/test/navlink.test.ts +0 -28
  300. package/test/pages.test.ts +0 -105
  301. package/test/placeholder.test.ts +0 -9
  302. package/test/pqauth-e2e.test.ts +0 -216
  303. package/test/pqauth-email.test.ts +0 -801
  304. package/test/prerender.test.ts +0 -116
  305. package/test/prettier-plugin.test.ts +0 -46
  306. package/test/routes.test.ts +0 -76
  307. package/test/rpc-bignum-wire.test.ts +0 -164
  308. package/test/rpc-dispatch.test.ts +0 -132
  309. package/test/rpc-kinds.test.ts +0 -18
  310. package/test/rpc.test.ts +0 -66
  311. package/test/search.test.ts +0 -114
  312. package/test/seo.test.ts +0 -175
  313. package/test/slot-layouts.test.ts +0 -69
  314. package/test/sri.test.ts +0 -129
  315. package/test/ssg.test.ts +0 -36
  316. package/test/ssr-hydration.test.tsx +0 -122
  317. package/test/ssr-render.test.ts +0 -197
  318. package/test/ssr-template.test.tsx +0 -482
  319. package/test/stream-emulation.test.ts +0 -479
  320. package/test/ui.test.ts +0 -40
  321. package/test/update.test.ts +0 -58
  322. package/test/validate.test.ts +0 -42
  323. package/test/version-check.test.ts +0 -130
  324. package/tests/data-parity/generated-parity.ts +0 -99
  325. package/tests/data-parity/parity.ts +0 -80
  326. package/tests/data-parity/spec.ts +0 -46
@@ -1,369 +0,0 @@
1
- /**
2
- * Dev DAEMON (L4) emulation. Loads `release-cold.wasm` ONCE into a single resident
3
- * instance, calls the guest `daemon_start()` export (RECONCILIATION Part 2; runs
4
- * once, `0` ok), registers the `@scheduled` tasks from `toildaemon.catalog`, and
5
- * drives them: interval tasks via `setInterval`, cron tasks via a one-shot
6
- * `setTimeout` armed at the next minute whose precomputed bitmasks all pass (F6;
7
- * never a runtime cron-string parse).
8
- *
9
- * Single-process at-most-once: there is exactly one dev process, so the leader
10
- * stub is always true and the lease never expires. The epoch is a fencing-token
11
- * stub that bumps on each (re)start, so guest code that compares epochs behaves
12
- * like the edge across a cold-artifact hot reload. A trapped tick does NOT tear
13
- * down the long-lived daemon box (deliberate asymmetry with the stream box); the
14
- * overlap guard (`ticking` set) prevents a slow tick from piling up
15
- * (overlap_policy 0 = skip-if-running).
16
- *
17
- * DAEMON path only; stream + WebSocket dev emulation is Phase 4.
18
- */
19
-
20
- import fs from 'node:fs';
21
-
22
- import pc from 'picocolors';
23
-
24
- import { type MemoryRef } from '../runtime/host.js';
25
- import { parseSurface } from '../wasm/surface.js';
26
- import {
27
- type CronMasks,
28
- type DaemonCatalog,
29
- parseDaemonCatalog,
30
- type ScheduledTask,
31
- } from './catalog.js';
32
- import { cronMatches, cronNeverFires, nextCronFireMs } from './cron.js';
33
- import {
34
- buildDaemonImports,
35
- type DaemonRuntime,
36
- type DaemonState,
37
- freshDaemonState,
38
- type ResolvedDaemonConfig,
39
- } from './host.js';
40
-
41
- interface ColdExports {
42
- readonly memory: WebAssembly.Memory;
43
- readonly daemon_start: () => number;
44
- readonly scheduled_tick: (taskId: number) => bigint;
45
- /** OPTIONAL: the host calls it before `daemon_start` if exported (Part 2). */
46
- readonly init?: () => number;
47
- }
48
-
49
- /** RECONCILIATION Part 3 decode of a negative packed-i64 return, for logging. */
50
- function decodeAbiError(ret: bigint): string {
51
- if (ret >= 0n) return 'ok';
52
- if (ret === -1n) return 'STATUS_TOO_SMALL';
53
- if (ret === -2n) return 'STATUS_ABSENT';
54
- if (ret <= -0x10000n) return '0x' + ((-ret - 0x10000n) & 0xffffn).toString(16).padStart(4, '0');
55
- if (ret <= -1000n) return 'DB(TDL ' + String(-ret - 1000n) + ')';
56
- return String(ret);
57
- }
58
-
59
- /**
60
- * Whether the daemon emulator should run for this dev process and artifact. Per
61
- * doc 08 section 5.1: `nodeMode` is `daemon` or `all`, the cold artifact's
62
- * `toil.surface` declares a daemon surface, AND `parseDaemonCatalog` returns
63
- * non-null with a daemon present.
64
- */
65
- export function daemonEmulationEnabled(nodeMode: string): boolean {
66
- return nodeMode === 'daemon' || nodeMode === 'all';
67
- }
68
-
69
- export class DaemonHost implements DaemonRuntime {
70
- private module: WebAssembly.Module | null = null;
71
- private instance: WebAssembly.Instance | null = null;
72
- private exports: ColdExports | null = null;
73
- private state: DaemonState = freshDaemonState();
74
- private catalog: DaemonCatalog | null = null;
75
- private loadedMtimeMs = -1;
76
- private running = false;
77
- /** Fencing-token stub (00 D3); bumps on each (re)start. */
78
- private epochValue = 0n;
79
- /** task_index -> active interval/timeout handle. */
80
- private timers = new Map<number, NodeJS.Timeout>();
81
- /** task_index -> next computed fire time (epoch ms), for daemon.next_fire_ms. */
82
- private nextFire = new Map<number, number>();
83
- /** task_index of ticks currently executing (overlap guard). */
84
- private ticking = new Set<number>();
85
-
86
- constructor(
87
- private readonly coldWasmPath: string,
88
- private readonly cfg: ResolvedDaemonConfig,
89
- private readonly nodeMode: string,
90
- private readonly log: (s: string) => void = (s) => process.stdout.write(s),
91
- ) {}
92
-
93
- /** Whether the daemon box is currently resident and started. */
94
- get active(): boolean {
95
- return this.running;
96
- }
97
-
98
- get tasks(): readonly ScheduledTask[] {
99
- return this.catalog?.tasks ?? [];
100
- }
101
-
102
- /** Test/dev introspection for fixtures that export scalar counters. */
103
- callI32Export(name: string): number | null {
104
- const fn = (this.exports as unknown as Record<string, unknown> | null)?.[name];
105
- if (typeof fn !== 'function') return null;
106
- const value = (fn as () => number)();
107
- return Number.isFinite(value) ? value : null;
108
- }
109
-
110
- // --- DaemonRuntime (the daemon.* host imports read these) ---
111
- isLeader(): boolean {
112
- return true; // single dev process is always the leader
113
- }
114
- epoch(): bigint {
115
- return this.epochValue;
116
- }
117
- taskCount(): number {
118
- return this.catalog?.tasks.length ?? 0;
119
- }
120
- nextFireMs(taskId: number): number | null {
121
- return this.nextFire.get(taskId) ?? null;
122
- }
123
-
124
- /**
125
- * (Re)load on mtime change, mirroring `WasmServerModule.refresh`. A cold-artifact
126
- * change PAUSES + RESTARTS the daemon with a bumped epoch (section 9.1). Returns
127
- * `true` when a (re)load happened.
128
- */
129
- refresh(): boolean {
130
- if (!daemonEmulationEnabled(this.nodeMode)) return false;
131
- let mtimeMs: number;
132
- try {
133
- mtimeMs = fs.statSync(this.coldWasmPath).mtimeMs;
134
- } catch {
135
- // Cold artifact gone -> stop a running daemon, stay idle.
136
- if (this.running) this.stop();
137
- this.module = null;
138
- this.loadedMtimeMs = -1;
139
- return false;
140
- }
141
- if (this.module !== null && mtimeMs === this.loadedMtimeMs) return false;
142
-
143
- const bytes = fs.readFileSync(this.coldWasmPath);
144
-
145
- // The cold artifact must declare a daemon surface and a non-null catalog,
146
- // else the emulator stays off (fail-closed; section 3.3 / 5.1).
147
- const surface = parseSurface(bytes);
148
- if (surface === 'invalid') {
149
- this.log(
150
- pc.red(' ✗ cold artifact toil.surface is corrupt; daemon not started') + '\n',
151
- );
152
- if (this.running) this.stop();
153
- this.loadedMtimeMs = mtimeMs;
154
- return false;
155
- }
156
- if (surface.targetMode !== 'cold') {
157
- this.log(
158
- pc.yellow(' ! ') +
159
- pc.dim('cold slot holds a hot-mode artifact; ignoring daemon emulator') +
160
- '\n',
161
- );
162
- if (this.running) this.stop();
163
- this.module = null;
164
- this.catalog = null;
165
- this.loadedMtimeMs = mtimeMs;
166
- return false;
167
- }
168
- const catalog = parseDaemonCatalog(bytes);
169
- const declaresDaemon = surface.flags.daemon && (catalog?.hasDaemon ?? false);
170
-
171
- // A restart: stop the old box (timers + instance), bump epoch, start fresh.
172
- if (this.running) this.stop();
173
-
174
- if (!declaresDaemon || catalog === null || !catalog.hasDaemon) {
175
- // No daemon in this artifact: load nothing, stay idle.
176
- this.module = null;
177
- this.catalog = null;
178
- this.loadedMtimeMs = mtimeMs;
179
- return false;
180
- }
181
-
182
- this.module = new WebAssembly.Module(bytes);
183
- this.catalog = catalog;
184
- this.loadedMtimeMs = mtimeMs;
185
- this.epochValue += 1n; // fencing token bumps on each (re)start
186
- this.start();
187
- return true;
188
- }
189
-
190
- /** Instantiate the cold box, run daemon_start once, register the tasks. */
191
- private start(): void {
192
- if (this.module === null || this.catalog === null) return;
193
- const ref: MemoryRef = { memory: null };
194
- this.state = freshDaemonState();
195
- const imports = buildDaemonImports(ref, this.state, this);
196
-
197
- // Fail-closed up front, with names, when the cold box imports anything outside its allowed
198
- // surface (the request env subset + crypto + @data, and the separate `daemon` module; NO
199
- // response/stream functions). Mirrors `WasmServerModule.assertImportSurface` (section 7.1).
200
- // Both namespaces are checked: `daemon.*` is its own wasm module at the edge, so a guest
201
- // that declares those names under `env` must fail HERE rather than trap only in production.
202
- // A non-function import is rejected outright, as the edge does (`NonFunctionImport`):
203
- // no memory/global/table is ever registered, so leaving one to fail later would
204
- // surface as an opaque LinkError rather than a named, fail-closed diagnostic.
205
- const provided = imports as Record<string, Record<string, unknown>>;
206
- const missing = WebAssembly.Module.imports(this.module)
207
- .filter(
208
- (i) => i.kind !== 'function' || !Object.hasOwn(provided[i.module] ?? {}, i.name),
209
- )
210
- .map((i) => `${i.module}.${i.name}${i.kind === 'function' ? '' : ` (${i.kind})`}`);
211
- if (missing.length > 0) {
212
- this.log(
213
- pc.red(
214
- ` ✗ cold daemon wasm imports unsupported host functions: ${missing.join(', ')}`,
215
- ) + '\n',
216
- );
217
- this.module = null;
218
- return;
219
- }
220
-
221
- this.instance = new WebAssembly.Instance(this.module, imports);
222
- this.exports = this.instance.exports as unknown as ColdExports;
223
- ref.memory = this.exports.memory;
224
-
225
- try {
226
- if (typeof this.exports.init === 'function') this.exports.init();
227
- const rc = this.exports.daemon_start();
228
- if (rc !== 0) {
229
- this.log(
230
- pc.red(` ✗ daemon_start() returned ${String(rc)}; daemon not running`) + '\n',
231
- );
232
- this.instance = null;
233
- this.exports = null;
234
- return;
235
- }
236
- } catch (e) {
237
- // A trap in daemon_start leaves the daemon stopped; surface it (do not
238
- // retry-loop in dev, mirroring the request-path error handling).
239
- this.log(pc.red(` ✗ daemon_start() trapped: ${String(e)}`) + '\n');
240
- this.instance = null;
241
- this.exports = null;
242
- return;
243
- }
244
-
245
- this.running = true;
246
- const limited = this.catalog.tasks.slice(0, this.cfg.maxTasks);
247
- for (const task of limited) this.registerTask(task);
248
- this.log(
249
- pc.green(' ⏱ ') +
250
- pc.dim(
251
- `daemon started (epoch ${String(this.epochValue)}, ${String(limited.length)} task${
252
- limited.length === 1 ? '' : 's'
253
- })`,
254
- ) +
255
- '\n',
256
- );
257
- }
258
-
259
- /** Clear timers, drop the resident instance. In-flight ticks finish on their own
260
- * (the overlap guard prevents a NEW tick; a running one completes). */
261
- private stop(): void {
262
- for (const t of this.timers.values()) clearTimeout(t);
263
- this.timers.clear();
264
- this.nextFire.clear();
265
- // Best-effort guest stop hook, if the artifact exports one.
266
- const stop = (this.exports as unknown as { daemon_stop?: () => void } | null)?.daemon_stop;
267
- if (typeof stop === 'function') {
268
- try {
269
- stop();
270
- } catch {
271
- /* ignore a trap in the optional stop hook */
272
- }
273
- }
274
- this.instance = null;
275
- this.exports = null;
276
- this.running = false;
277
- }
278
-
279
- private registerTask(task: ScheduledTask): void {
280
- if (task.schedule.kind === 'interval') {
281
- const ms = Math.max(1000, task.schedule.ms || this.cfg.defaultIntervalMs);
282
- this.nextFire.set(task.taskIndex, Date.now() + ms);
283
- const handle = setInterval(() => {
284
- this.nextFire.set(task.taskIndex, Date.now() + ms);
285
- this.runTick(task);
286
- }, ms);
287
- // Do not keep the event loop alive solely for the dev scheduler.
288
- handle.unref?.();
289
- this.timers.set(task.taskIndex, handle);
290
- } else {
291
- const masks = task.schedule.masks;
292
- if (cronNeverFires(masks)) {
293
- this.log(
294
- pc.yellow(' ! ') +
295
- pc.dim(
296
- `@scheduled ${task.name} has an unsatisfiable cron mask; skipping (DAEMON_SCHEDULE_REJECTED)`,
297
- ) +
298
- '\n',
299
- );
300
- return;
301
- }
302
- this.armCron(task, masks);
303
- }
304
- }
305
-
306
- /** Arm a one-shot timer to the next cron fire time, re-arming after each tick. */
307
- private armCron(task: ScheduledTask, masks: CronMasks): void {
308
- const next = nextCronFireMs(masks, Date.now());
309
- if (next === null) {
310
- this.nextFire.delete(task.taskIndex);
311
- return;
312
- }
313
- this.nextFire.set(task.taskIndex, next);
314
- const delay = Math.max(0, next - Date.now());
315
- const handle = setTimeout(() => {
316
- // Guard against a coarse-timer early fire: only run when the masks
317
- // actually match the current minute (they should by construction).
318
- if (cronMatches(masks, new Date())) this.runTick(task);
319
- if (this.running) this.armCron(task, masks);
320
- }, delay);
321
- handle.unref?.();
322
- this.timers.set(task.taskIndex, handle);
323
- }
324
-
325
- /** Fire one `@scheduled` task via `scheduled_tick(task_id)` (Part 2). */
326
- private runTick(task: ScheduledTask): void {
327
- if (!this.running || this.exports === null) return;
328
- if (this.ticking.has(task.taskIndex)) {
329
- // overlap_policy 0 = skip-if-running: a slow tick must not pile up.
330
- this.log(
331
- pc.dim(` ⏱ @scheduled ${task.name} overran its interval; skipping a tick`) + '\n',
332
- );
333
- return;
334
- }
335
- if (!this.isLeader()) return; // always true in dev; kept for parity
336
- this.ticking.add(task.taskIndex);
337
- const startedAt = Date.now();
338
- try {
339
- const ret = this.exports.scheduled_tick(task.taskIndex); // packed-i64
340
- if (ret < 0n)
341
- this.log(
342
- pc.yellow(` ⏱ @scheduled ${task.name} returned error ${decodeAbiError(ret)}`) +
343
- '\n',
344
- );
345
- } catch (e) {
346
- // A trapped tick does NOT tear down the long-lived daemon box (unlike a
347
- // stream box); the next tick runs normally on the same memory.
348
- this.log(pc.red(` ✗ @scheduled ${task.name} trapped: ${String(e)}`) + '\n');
349
- } finally {
350
- const took = Date.now() - startedAt;
351
- if (took > this.cfg.tickBudgetMs)
352
- this.log(
353
- pc.yellow(
354
- ` ⏱ @scheduled ${task.name} took ${String(took)}ms (> tickBudgetMs ${String(
355
- this.cfg.tickBudgetMs,
356
- )})`,
357
- ) + '\n',
358
- );
359
- this.ticking.delete(task.taskIndex);
360
- }
361
- }
362
-
363
- /** Tear the daemon down for good (dev-server shutdown). */
364
- close(): void {
365
- if (this.running) this.stop();
366
- this.module = null;
367
- this.catalog = null;
368
- }
369
- }
@@ -1,48 +0,0 @@
1
- import pc from 'picocolors';
2
-
3
- import { DaemonHost, daemonEmulationEnabled } from './index.js';
4
- import type { ResolvedDaemonConfig } from './host.js';
5
-
6
- export interface DaemonRuntimeOptions {
7
- readonly coldWasmFile?: string;
8
- readonly nodeMode?: string;
9
- readonly daemon?: ResolvedDaemonConfig;
10
- readonly pollMs?: number;
11
- }
12
-
13
- export interface RunningDaemonRuntime {
14
- readonly host: DaemonHost;
15
- close(): void;
16
- }
17
-
18
- /** Starts the shared cold-artifact daemon runtime used by both `dev` and `start`. */
19
- export function startDaemonRuntime(options: DaemonRuntimeOptions): RunningDaemonRuntime | null {
20
- const nodeMode = options.nodeMode ?? 'all';
21
- if (
22
- options.coldWasmFile === undefined ||
23
- !daemonEmulationEnabled(nodeMode) ||
24
- options.daemon === undefined
25
- ) {
26
- return null;
27
- }
28
-
29
- const host = new DaemonHost(options.coldWasmFile, options.daemon, nodeMode);
30
- const pollDaemon = (): void => {
31
- try {
32
- host.refresh();
33
- } catch (e) {
34
- process.stdout.write(pc.red(` x daemon reload failed: ${String(e)}`) + '\n');
35
- }
36
- };
37
- pollDaemon();
38
- const timer = setInterval(pollDaemon, options.pollMs ?? 500);
39
- timer.unref?.();
40
-
41
- return {
42
- host,
43
- close: (): void => {
44
- clearInterval(timer);
45
- host.close();
46
- },
47
- };
48
- }
@@ -1,109 +0,0 @@
1
- /**
2
- * Parse a compiled server wasm's `toildb.catalog` custom section into structured
3
- * dev capability metadata keyed by `"<Db>/<collection>"` (the resolve key the
4
- * guest passes to `data.resolve_collection`).
5
- *
6
- * The dev DB uses this to STAMP each write with the value type's current schema
7
- * version. When the developer evolves a `@data` type and rebuilds, the catalog
8
- * version changes; data already on disk keeps its OLD stamp, so a read surfaces
9
- * that old version and the guest's woven `decodeInto` runs the `@migrate` - the
10
- * dev-side equivalent of the edge binding the cap's schema_version into the row.
11
- * The parsed family is also used to reject wrong-family imports locally.
12
- *
13
- * Wire format mirrors `toildb::catalog` / the backend `db_catalog` decoder and the
14
- * compiler's `buildToilDbCatalog` emitter (all little-endian).
15
- */
16
-
17
- import { DataReader } from 'toiljs/io';
18
- import { customSection } from '../wasm/sections.js';
19
- import {
20
- CollectionFamily,
21
- type DbCatalogState,
22
- DEFAULT_FILL_WAIT_MS,
23
- type DevCollectionHandle,
24
- type DevField,
25
- isCollectionFamily,
26
- MAX_FILL_WAIT_MS,
27
- } from './types.js';
28
-
29
- function validReplication(value: number): boolean {
30
- return value === 0 || value === 1 || value === 2 || value === 5;
31
- }
32
-
33
- function validPlacement(value: number): boolean {
34
- return value === 0 || value === 1;
35
- }
36
-
37
- /** Decode the devserver's catalog state. A missing section stays distinct from a
38
- * present-but-bad section so `resolve_collection` can match the edge's
39
- * Present/Malformed/NoSection admission behavior. */
40
- export function parseCatalog(wasm: Buffer): DbCatalogState {
41
- const collections = new Map<string, DevCollectionHandle>();
42
- let sec: Buffer | null;
43
- try {
44
- sec = customSection(wasm, 'toildb.catalog');
45
- } catch {
46
- return { kind: 'no-section' }; // garbage section table (mid-rebuild) -> no catalog
47
- }
48
- if (sec === null) return { kind: 'no-section' };
49
-
50
- const r = new DataReader(sec);
51
- const version = r.readU16();
52
- if (!r.ok || version !== 1) return { kind: 'malformed' };
53
- const ndb = r.readU16();
54
- for (let d = 0; d < ndb && r.ok; d++) {
55
- const db = r.readString();
56
- const nc = r.readU16();
57
- for (let c = 0; c < nc && r.ok; c++) {
58
- const name = r.readString();
59
- const family = r.readU8();
60
- r.readString(); // keyType
61
- r.readString(); // valueType
62
- r.readU32(); // valueDataId
63
- const schemaVersion = r.readU32();
64
- r.readU32(); // generation
65
- const replication = r.readU8(); // emitter order: replication then placement
66
- const placement = r.readU8();
67
- const fillMaxWaitMs = r.readU32();
68
- const fillAllowStaleByte = r.readU8();
69
- if (
70
- fillMaxWaitMs > MAX_FILL_WAIT_MS ||
71
- (fillAllowStaleByte !== 0 && fillAllowStaleByte !== 1)
72
- )
73
- return { kind: 'malformed' };
74
- const fillAllowStale = fillAllowStaleByte === 1;
75
- const nFields = r.readU16();
76
- const fields: DevField[] = [];
77
- for (let f = 0; f < nFields; f++) {
78
- const fName = r.readString();
79
- const fType = r.readString();
80
- const isArray = r.readU8() !== 0;
81
- const unique = r.readU8() !== 0;
82
- fields.push({ name: fName, typeName: fType, isArray, unique });
83
- }
84
- const nMig = r.readU16();
85
- for (let m = 0; m < nMig; m++) r.readU32(); // migratableFrom versions
86
- if (
87
- !isCollectionFamily(family) ||
88
- !validReplication(replication) ||
89
- !validPlacement(placement)
90
- )
91
- return { kind: 'malformed' };
92
- const key = db + '/' + name;
93
- if (collections.has(key)) return { kind: 'malformed' };
94
- if (r.ok)
95
- collections.set(key, {
96
- name: key,
97
- family: family as CollectionFamily,
98
- schemaVersion: schemaVersion >>> 0,
99
- replication,
100
- placement,
101
- fillMaxWaitMs,
102
- fillAllowStale,
103
- fields,
104
- });
105
- }
106
- }
107
- if (!r.ok || r.remaining() !== 0) return { kind: 'malformed' };
108
- return { kind: 'present', collections };
109
- }