| 1 | import assert from "node:assert/strict"; |
| 2 | import { test } from "node:test"; |
| 3 | import { fileURLToPath } from "node:url"; |
| 4 | import { build } from "esbuild"; |
| 5 | |
| 6 | const bundle = await build({ |
| 7 | entryPoints: [fileURLToPath(new URL("./service.ts", import.meta.url))], |
| 8 | bundle: true, |
| 9 | write: false, |
| 10 | format: "esm", |
| 11 | platform: "node", |
| 12 | plugins: [ |
| 13 | { |
| 14 | name: "worker-host", |
| 15 | setup(build) { |
| 16 | build.onResolve({ filter: /^cloudflare:workers$/ }, () => ({ path: "host", namespace: "host" })); |
| 17 | build.onLoad({ filter: /.*/, namespace: "host" }, () => ({ contents: "export class DurableObject {}" })); |
| 18 | }, |
| 19 | }, |
| 20 | ], |
| 21 | }); |
| 22 | const { Folios } = await import(`data:text/javascript;base64,${Buffer.from(bundle.outputFiles[0].text).toString("base64")}`); |
| 23 | |
| 24 | test("a cold room never holds up page state; its snapshot is saved in the background", async () => { |
| 25 | let resolve!: (value: Uint8Array) => void; |
| 26 | const pending = new Promise<Uint8Array>((done) => { |
| 27 | resolve = done; |
| 28 | }); |
| 29 | const deferred: Promise<unknown>[] = []; |
| 30 | const writes: unknown[][] = []; |
| 31 | const statement = { |
| 32 | bind: (...values: unknown[]) => { |
| 33 | writes.push(values); |
| 34 | return statement; |
| 35 | }, |
| 36 | run: async () => ({ success: true }), |
| 37 | }; |
| 38 | const service = new Folios({ DB: { prepare: () => statement } }, (work: Promise<unknown>) => deferred.push(work)); |
| 39 | service.ready = async () => ({ state: () => pending }); |
| 40 | assert.equal(service.stateFor({ slug: "cold" }, { id: "folio_cold", state: null }), null); |
| 41 | assert.equal(deferred.length, 1); |
| 42 | assert.deepEqual(writes, []); |
| 43 | const bytes = new Uint8Array([1, 2, 3]); |
| 44 | resolve(bytes); |
| 45 | await Promise.all(deferred); |
| 46 | assert.deepEqual(writes, [[bytes, "folio_cold"]]); |
| 47 | }); |
| 48 | |
| 49 | test("saved state and trashed documents never wake the live room", () => { |
| 50 | const service = new Folios({}, () => assert.fail("must not start background work")); |
| 51 | assert.equal(service.stateFor({}, { state: [104, 105] }), btoa("hi")); |
| 52 | assert.equal(service.stateFor({}, { state: null, trashed_at: "2026-10-15" }), null); |
| 53 | }); |