@rsc-kit/core 0.29.0 → 0.29.2
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.
- package/dist/changed.d.ts +11 -9
- package/dist/changed.js +1 -2
- package/dist/changed.js.map +1 -1
- package/dist/conformance.d.ts +14 -1
- package/dist/conformance.js +116 -5
- package/dist/conformance.js.map +1 -1
- package/dist/hostCalls.js +14 -5
- package/dist/hostCalls.js.map +1 -1
- package/dist/js/section.d.ts +14 -4
- package/dist/js/section.js.map +1 -1
- package/dist/request.d.ts +8 -0
- package/dist/request.js +31 -0
- package/dist/request.js.map +1 -1
- package/dist/testHost.d.ts +2 -0
- package/dist/testHost.js +12 -1
- package/dist/testHost.js.map +1 -1
- package/dist/vite.js +13 -4
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
package/dist/changed.d.ts
CHANGED
|
@@ -63,8 +63,7 @@ export interface VersionSource {
|
|
|
63
63
|
* change. A time never comes round again, so a name may be forgotten at any
|
|
64
64
|
* moment: a tab holding the old value sees a different one, and at worst
|
|
65
65
|
* refreshes once for nothing. It is also when the name last moved, which is
|
|
66
|
-
* all cleanup needs. Every store bumps with it
|
|
67
|
-
* works, it is just not safe to prune.
|
|
66
|
+
* all cleanup needs. Every store bumps with it - a counter is not a version.
|
|
68
67
|
*/
|
|
69
68
|
export declare function nextVersion(current?: number): number;
|
|
70
69
|
/** The safety-net read of a store that listens: longer than any ask waits, so once per ask. */
|
|
@@ -157,23 +156,26 @@ export declare function sqlVersions(options: SqlVersionsOptions): PrunableVersio
|
|
|
157
156
|
* (await db.select().from(rscVersions).where(inArray(rscVersions.name, names)))
|
|
158
157
|
* .map((r) => [r.name, Number(r.version)])),
|
|
159
158
|
* bump: async (names) => { for (const name of names) await db.insert(rscVersions)
|
|
160
|
-
* .values({ name, version:
|
|
161
|
-
* .onConflictDoUpdate({ target: rscVersions.name,
|
|
159
|
+
* .values({ name, version: Date.now() })
|
|
160
|
+
* .onConflictDoUpdate({ target: rscVersions.name,
|
|
161
|
+
* set: { version: sql`GREATEST(${rscVersions.version} + 1, excluded.version)` } }) },
|
|
162
162
|
*
|
|
163
163
|
* // Redis
|
|
164
164
|
* read: async (names) => Object.fromEntries((await redis.mget(names.map(k)))
|
|
165
165
|
* .map((v, i) => [names[i], Number(v ?? 0)])),
|
|
166
|
-
*
|
|
166
|
+
* // nextVersion in one step: the larger of one past the old value and now.
|
|
167
|
+
* bump: async (names) => { await Promise.all(names.map((n) => redis.eval(
|
|
168
|
+
* "local v = math.max(tonumber(redis.call('GET', KEYS[1]) or '0') + 1, tonumber(ARGV[1])) " +
|
|
169
|
+
* "redis.call('SET', KEYS[1], v) return v", 1, k(n), Date.now()))) },
|
|
167
170
|
*/
|
|
168
171
|
export interface VersionStore {
|
|
169
172
|
/** The current version of each name asked for. A name it has never seen may be left out: it is 0. */
|
|
170
173
|
read(names: string[]): Promise<Record<string, number>>;
|
|
171
174
|
/**
|
|
172
175
|
* Move each name's version to `nextVersion(current)` - one past where it
|
|
173
|
-
* was, or the current time in ms if that is larger.
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
* deleted.
|
|
176
|
+
* was, or the current time in ms if that is larger. Required, not a
|
|
177
|
+
* suggestion: a version must never repeat, which is what makes it safe to
|
|
178
|
+
* delete a name, and a counter repeats the moment one is deleted.
|
|
177
179
|
*/
|
|
178
180
|
bump(names: string[]): Promise<void>;
|
|
179
181
|
/**
|
package/dist/changed.js
CHANGED
|
@@ -42,8 +42,7 @@ export const CHANGED_FUNCTION = "__rsc.changed";
|
|
|
42
42
|
* change. A time never comes round again, so a name may be forgotten at any
|
|
43
43
|
* moment: a tab holding the old value sees a different one, and at worst
|
|
44
44
|
* refreshes once for nothing. It is also when the name last moved, which is
|
|
45
|
-
* all cleanup needs. Every store bumps with it
|
|
46
|
-
* works, it is just not safe to prune.
|
|
45
|
+
* all cleanup needs. Every store bumps with it - a counter is not a version.
|
|
47
46
|
*/
|
|
48
47
|
export function nextVersion(current = 0) {
|
|
49
48
|
return Math.max(current + 1, Date.now());
|
package/dist/changed.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"changed.js","sourceRoot":"","sources":["../src/changed.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEnD,OAAO,EAAE,iBAAiB,EAAyB,MAAM,gBAAgB,CAAC;AAE1E,4DAA4D;AAC5D,MAAM,CAAC,MAAM,gBAAgB,GAAG,eAAe,CAAC;AAgChD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,WAAW,CAAC,OAAO,GAAG,CAAC;IACrC,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,GAAG,CAAC,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;AAC3C,CAAC;AAED,+FAA+F;AAC/F,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC;AAExC,sFAAsF;AACtF,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAEzD;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAC5B,OAAO,GAA6B,EAAE;IAEtC,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,gBAAgB,CAAC;IAC5D,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC3C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAc,CAAC;IACtC,IAAI,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAEvB,MAAM,KAAK,GAAG,GAAG,EAAE;QACjB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAEvB,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AC;AACvC,CAAC","sourcesContent":["/**\n * Names: a name for data a page depends on, so whatever changes it can say so\n * from anywhere - a webhook, a job, another visitor's action - and every open\n * tab showing it refreshes.\n *\n * // a section says what it depends on\n * export default section('repos', Repos, { refreshOn: ({ params }) => [`team:${params.team}:repos`] })\n *\n * // and whatever changes it says so\n * changed(`team:${team}:repos`) // here, from a route.ts or an action\n * rsckit.Changed(ctx, \"team:1:repos\") // or the backend, from its webhook\n * Rsc::changed(\"team:$team:repos\"); // Laravel\n *\n * A name has a version: a number that moves whenever something says the name\n * changed. Nothing else - not what changed, not the data. A page learns the\n * versions at render; one stream per open tab watches them; when one moves,\n * the sections carrying that name ask for themselves again, the way refresh()\n * does. Data is never pushed, which is what keeps this working on a host that\n * cannot hold state: a version is a read.\n *\n * Where versions live is the source's business. Without a backend they are in\n * this process, which is one instance. With one, the backend keeps them - in\n * its cache or a table, shared by every instance it runs - and answers\n * `__rsc.changed`: given the versions a watcher holds, the ones that differ now.\n * A backend that can wait holds the call until one does; one that cannot\n * answers at once, and the watcher asks again on its interval. The protocol\n * is the same either way, and so is the page.\n */\n\nimport { frame, keepaliveMs } from \"./events.js\";\nimport { HEADER } from \"./headers.js\";\nimport { listenToBroadcast } from \"./broadcast.js\";\n\nexport { listenToBroadcast, type BroadcastOptions } from \"./broadcast.js\";\n\n/** The reserved name a backend answers name versions on. */\nexport const CHANGED_FUNCTION = \"__rsc.changed\";\n\n/** What `__rsc.changed` is asked. */\nexport interface ChangedQuery {\n /** The versions the asker holds. A name never changed is 0; -1 asks for every current version. */\n since: Record<string, number>;\n /** How long the backend may hold the call waiting for one to differ, in ms. It may answer at once. */\n wait?: number;\n}\n\n/** What `__rsc.changed` answers: the versions among `since` that differ now. */\nexport interface ChangedAnswer {\n versions: Record<string, number>;\n}\n\n/**\n * Where name versions are read from, and - when they live here - bumped.\n *\n * `changed` answers the versions among `since` that differ now, and may wait\n * up to `wait` ms for one to. Nothing else is required of it, which is why a\n * backend's cache, a table, this process's memory, or a pub/sub that answers\n * the moment a name moves all fit behind it.\n */\nexport interface VersionSource {\n changed(\n since: Record<string, number>,\n wait: number,\n ): Promise<Record<string, number>>;\n /** Say these names changed. Only a source that holds its own versions can. */\n bump(names: string[]): void | Promise<void>;\n}\n\n/**\n * The version a name moves to: the larger of one past where it was and the\n * current time in milliseconds.\n *\n * A counter would do for \"it moved\", but a counter repeats once its row is\n * gone - deleted to keep the store small, a name starts again from 0 and\n * climbs back to a value some tab is still holding, and that tab misses the\n * change. A time never comes round again, so a name may be forgotten at any\n * moment: a tab holding the old value sees a different one, and at worst\n * refreshes once for nothing. It is also when the name last moved, which is\n * all cleanup needs. Every store bumps with it; one that writes `+ 1` still\n * works, it is just not safe to prune.\n */\nexport function nextVersion(current = 0): number {\n return Math.max(current + 1, Date.now());\n}\n\n/** The safety-net read of a store that listens: longer than any ask waits, so once per ask. */\nexport const LISTENING_POLL_MS = 30_000;\n\n/** How long a name nobody changes is kept, by the stores that forget on their own. */\nexport const VERSIONS_KEPT_MS = 30 * 24 * 60 * 60 * 1000;\n\n/**\n * Versions kept in this process: the source without a backend, and the one\n * tests use. A name not changed in `forgetAfter` ms (30 days) is forgotten,\n * swept at most once an hour, so a process up for months does not hold every\n * name it ever saw.\n */\nexport function memoryVersions(\n options: { forgetAfter?: number } = {},\n): VersionSource {\n const forgetAfter = options.forgetAfter ?? VERSIONS_KEPT_MS;\n const versions = new Map<string, number>();\n const waiters = new Set<() => void>();\n let swept = Date.now();\n\n const sweep = () => {\n const now = Date.now();\n\n if (now - swept < Math.min(forgetAfter, 60 * 60 * 1000)) return;\n swept = now;\n\n for (const [name, version] of versions)\n if (version < now - forgetAfter) versions.delete(name);\n };\n\n const differing = (since: Record<string, number>): Record<string, number> => {\n const out: Record<string, number> = {};\n\n for (const [name, held] of Object.entries(since)) {\n const current = versions.get(name) ?? 0;\n\n if (current !== held) out[name] = current;\n }\n\n return out;\n };\n\n return {\n async changed(since, wait) {\n const now = differing(since);\n\n if (Object.keys(now).length > 0 || wait <= 0) return now;\n\n await new Promise<void>((resolve) => {\n const done = () => {\n clearTimeout(timer);\n waiters.delete(done);\n resolve();\n };\n const timer = setTimeout(done, wait);\n\n // A test or a build must not be held open by a watcher's wait.\n (timer as { unref?: () => void }).unref?.();\n waiters.add(done);\n });\n\n return differing(since);\n },\n bump(names) {\n sweep();\n for (const name of names)\n versions.set(name, nextVersion(versions.get(name)));\n for (const wake of [...waiters]) wake();\n },\n };\n}\n\ntype HostFn = (name: string, ...args: unknown[]) => Promise<unknown>;\n\n/**\n * Versions kept by the backend, read through `__rsc.changed`.\n *\n * A backend that has not got the function - an adapter from before names, or\n * a host of plain rpc functions - is answered from this process instead,\n * found out on the first ask and remembered, so a page with names still works\n * on it: one instance, versions bumped by `changed()` here.\n */\nexport function backendVersions(call: HostFn): VersionSource {\n let local: VersionSource | null = null;\n\n // A backend's \"no such function\", or the test host's \"no handler for\".\n const unknown = (error: unknown): boolean =>\n /no host function named|has no handler for/i.test(\n error instanceof Error ? error.message : String(error),\n );\n\n return {\n async changed(since, wait) {\n if (local) return local.changed(since, wait);\n\n try {\n const answer = (await call(CHANGED_FUNCTION, {\n since,\n wait,\n } satisfies ChangedQuery)) as Partial<ChangedAnswer> | null;\n\n return answer?.versions ?? {};\n } catch (error) {\n if (!unknown(error)) throw error;\n\n local = memoryVersions();\n\n return local.changed(since, wait);\n }\n },\n bump(names) {\n if (local) return local.bump(names);\n\n throw new Error(\n \"changed() bumps versions this process keeps, and a backend keeps these: say the name changed there - \" +\n \"rsckit.Changed(ctx, ...) in Go, Rsc::changed(...) in Laravel.\",\n );\n },\n };\n}\n\n/** Runs one statement with positional parameters and resolves to its rows. */\nexport type SqlQuery = (\n text: string,\n params: unknown[],\n) => Promise<readonly Record<string, unknown>[]>;\n\nexport interface SqlVersionsOptions {\n /**\n * Which database, so a change is one statement - an upsert of every name\n * it moves - rather than a read and a write per name. Left out, the store\n * uses only SQL every database has, at the cost of those extra queries.\n */\n dialect?: \"postgres\" | \"mysql\" | \"sqlite\";\n /**\n * Postgres only: NOTIFY this channel in the same statement as the upsert,\n * so a listening server wakes - and only once the write commits.\n */\n channel?: string;\n /**\n * Your driver, as a function of SQL text and parameters:\n *\n * query: (text, params) => sql.unsafe(text, params) // postgres.js, Bun.sql\n * query: async (text, params) => (await pool.query(text, params)).rows // node-postgres\n */\n query: SqlQuery;\n /** The table: `CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL)`. */\n table?: string;\n /** How the n-th parameter is written (1-based). Default `?`; Postgres is `(n) => '$' + n`. */\n placeholder?: (n: number) => string;\n /**\n * Called once with a function that wakes every waiting ask, for a database\n * that can say the moment a version moved - Postgres's LISTEN:\n *\n * listen: (wake) => sql.listen('rsc_versions', wake)\n *\n * Without it, a waiting ask reads the table every `poll` ms.\n */\n listen?: (wake: () => void, health: ListenerHealth) => unknown;\n /**\n * Run after every bump, to tell the other instances - Postgres's NOTIFY:\n *\n * notify: () => sql.notify('rsc_versions', '')\n */\n notify?: () => unknown;\n /**\n * How often a waiting ask reads the table: every second by default, or,\n * with `listen`, only as a safety net - about once per ask.\n */\n poll?: number;\n}\n\n/**\n * Versions in a table every instance shares: the web servers, and the worker\n * that finishes a job and says so. The same table and columns Go's\n * `SQLVersions` uses, so a Go service and a JavaScript worker can share one.\n *\n * installVersionSource(sqlVersions({\n * query: (text, params) => sql.unsafe(text, params),\n * placeholder: (n) => '$' + n,\n * listen: (wake) => sql.listen('rsc_versions', wake),\n * notify: () => sql.notify('rsc_versions', ''),\n * }))\n *\n * Written with an UPDATE and, the first time, an INSERT - two statements any\n * SQL dialect has - rather than an upsert each spells differently. Takes the\n * app's own driver, so the engine has no database dependency of its own.\n */\n/**\n * One statement that moves every name to nextVersion: an upsert, in the\n * dialect's own words, and on Postgres the NOTIFY with it. A name is either\n * inserted at `now` or moved to the larger of one more and `now`.\n */\nfunction upsert(\n dialect: \"postgres\" | \"mysql\" | \"sqlite\",\n table: string,\n mark: (n: number) => string,\n names: string[],\n now: number,\n channel?: string,\n): [string, unknown[]] {\n if (dialect === \"postgres\") {\n // $1 is now, the names follow; the channel, if any, comes last.\n const rows = names.map((_, i) => `(${mark(i + 2)}, ${mark(1)})`).join(\", \");\n const insert =\n `INSERT INTO ${table} (name, version) VALUES ${rows} ` +\n `ON CONFLICT (name) DO UPDATE SET version = GREATEST(${table}.version + 1, EXCLUDED.version)`;\n\n if (!channel) return [insert, [now, ...names]];\n\n // A NOTIFY is delivered when the transaction commits, so a listener is\n // never woken before the change it is told about can be read.\n return [\n `WITH moved AS (${insert} RETURNING 1) SELECT pg_notify(${mark(names.length + 2)}, '') FROM (SELECT count(*) FROM moved) AS done`,\n [now, ...names, channel],\n ];\n }\n\n const rows = names.map(() => `(${mark(1)}, ${mark(1)})`).join(\", \");\n const params = names.flatMap((name) => [name, now]);\n\n return dialect === \"mysql\"\n ? [\n `INSERT INTO ${table} (name, version) VALUES ${rows} ON DUPLICATE KEY UPDATE version = GREATEST(version + 1, VALUES(version))`,\n params,\n ]\n : [\n `INSERT INTO ${table} (name, version) VALUES ${rows} ON CONFLICT (name) DO UPDATE SET version = MAX(version + 1, excluded.version)`,\n params,\n ];\n}\n\n/** A store whose old names can be cleared out: the SQL ones. */\nexport interface PrunableVersions extends VersionSource {\n /**\n * Delete every name not changed in `olderThan` ms (30 days by default).\n * Always safe: a version is a time and never comes round again, so a tab\n * still holding a pruned name sees it differ and refreshes once. Run it\n * from a scheduled job - a daily one is plenty.\n */\n prune(olderThan?: number): Promise<void>;\n}\n\nexport function sqlVersions(options: SqlVersionsOptions): PrunableVersions {\n const { query } = options;\n const table = options.table ?? \"rsc_versions\";\n const mark = options.placeholder ?? (() => \"?\");\n\n const source = createVersions(\n {\n async read(names) {\n const rows = await query(\n `SELECT name, version FROM ${table} WHERE name IN (${names.map((_, i) => mark(i + 1)).join(\", \")})`,\n names,\n );\n\n // A BIGINT comes back as a string from most drivers.\n return Object.fromEntries(\n rows.map((row) => [String(row.name), Number(row.version)]),\n );\n },\n async bump(names) {\n if (options.dialect) {\n await query(\n ...upsert(\n options.dialect,\n table,\n mark,\n names,\n Date.now(),\n options.channel,\n ),\n );\n\n return;\n }\n\n // nextVersion, in SQL every dialect has: CASE rather than GREATEST,\n // which SQLite spells MAX. The time is this process's, passed in, so\n // the database's clock never has to agree with it.\n const update =\n `UPDATE ${table} SET version = CASE WHEN version + 1 > ${mark(1)} THEN version + 1 ELSE ${mark(2)} END ` +\n `WHERE name = ${mark(3)}`;\n const insert = `INSERT INTO ${table} (name, version) VALUES (${mark(1)}, ${mark(2)})`;\n\n for (const name of names) {\n const now = Date.now();\n\n // The row count is not something every driver reports the same way,\n // so ask: a name with no row yet gets one.\n const [exists] = await query(\n `SELECT 1 AS found FROM ${table} WHERE name = ${mark(1)}`,\n [name],\n );\n\n if (exists) {\n await query(update, [now, now, name]);\n continue;\n }\n\n try {\n await query(insert, [name, now]);\n } catch {\n // Another instance inserted it first: bump that one.\n await query(update, [now, now, name]);\n }\n }\n },\n listen: options.listen,\n notify: options.notify,\n },\n { poll: options.poll },\n );\n\n return {\n ...source,\n async prune(olderThan = VERSIONS_KEPT_MS) {\n await query(`DELETE FROM ${table} WHERE version < ${mark(1)}`, [\n Date.now() - olderThan,\n ]);\n },\n };\n}\n\n/**\n * Where versions are kept, as the app writes it for its own database: the\n * three things rsc-kit cannot know about your storage, and nothing else.\n * `createVersions` does the rest - comparing, waiting, waking.\n *\n * // Drizzle\n * read: async (names) => Object.fromEntries(\n * (await db.select().from(rscVersions).where(inArray(rscVersions.name, names)))\n * .map((r) => [r.name, Number(r.version)])),\n * bump: async (names) => { for (const name of names) await db.insert(rscVersions)\n * .values({ name, version: 1 })\n * .onConflictDoUpdate({ target: rscVersions.name, set: { version: sql`${rscVersions.version} + 1` } }) },\n *\n * // Redis\n * read: async (names) => Object.fromEntries((await redis.mget(names.map(k)))\n * .map((v, i) => [names[i], Number(v ?? 0)])),\n * bump: async (names) => { await Promise.all(names.map((n) => redis.incr(k(n)))) },\n */\nexport interface VersionStore {\n /** The current version of each name asked for. A name it has never seen may be left out: it is 0. */\n read(names: string[]): Promise<Record<string, number>>;\n /**\n * Move each name's version to `nextVersion(current)` - one past where it\n * was, or the current time in ms if that is larger. Watchers only compare,\n * so any new value works; this one never repeats, which is what makes it\n * safe to delete a name later. A plain `+ 1` works too, until a row is\n * deleted.\n */\n bump(names: string[]): Promise<void>;\n /**\n * Called once with a function that wakes every waiting ask, when the store\n * can say the moment a version moved - Postgres LISTEN, Redis SUBSCRIBE.\n * Without it a waiting ask reads again every `poll` ms.\n *\n * Given `health` too: a store that finds it hears nothing - a Postgres\n * listener behind a pooler in transaction mode - calls `health.deaf(why)`,\n * and rsc-kit says so and goes back to reading every second.\n */\n listen?(wake: () => void, health: ListenerHealth): unknown;\n /** Run after a bump, to tell the other instances listening: Postgres NOTIFY, Redis PUBLISH. */\n notify?(): unknown;\n}\n\n/**\n * A version source over any store: SQL through any driver or ORM - Drizzle,\n * Prisma, Kysely, Knex - or Redis, or anything with a read and an increment.\n *\n * installVersionSource(createVersions({ read, bump, listen, notify }))\n *\n * rsc-kit owns the rest: an ask waits up to the time it was given for a\n * version to differ, reading every `poll` ms (1000 by default) or the moment\n * `listen` wakes it, and a bump in this process wakes this process's asks at\n * once whatever the store.\n */\nexport function createVersions(\n store: VersionStore,\n options: { poll?: number } = {},\n): VersionSource {\n // A store that listens is woken the moment a version moves, so reading the\n // table on a timer is only a safety net - for a listening connection that\n // dropped without a word. Once an ask is enough: about every five seconds\n // per server, where one that cannot listen reads every second.\n let listening = Boolean(store.listen);\n const poll = () => options.poll ?? (listening ? LISTENING_POLL_MS : 1_000);\n const waiters = new Set<() => void>();\n const wakeAll = () => {\n for (const wake of [...waiters]) wake();\n };\n\n // A store that can listen wakes the renderer the way anything else does -\n // through wakeOn, which starts it with the first watching tab and never in\n // a build. A wake also ends an ask this store is holding.\n if (store.listen) {\n const listen = store.listen.bind(store);\n\n wakeOn((wake, health) =>\n listen(wake, {\n deaf: (reason) => {\n listening = false;\n health.deaf(reason);\n },\n }),\n );\n }\n wakers().sleepers.add(wakeAll);\n\n const read = async (names: string[]): Promise<Record<string, number>> => {\n if (names.length === 0) return {};\n\n const found = await store.read(names);\n\n return Object.fromEntries(\n names.map((name) => [name, Number(found[name] ?? 0)]),\n );\n };\n\n return {\n async changed(since, wait) {\n // Only a server with a tab watching asks with a wait - never a build -\n // so this is a safe moment to start listening, as is the first tab.\n if (wait > 0) startWakers();\n\n const names = Object.keys(since);\n const deadline = Date.now() + Math.max(0, wait);\n\n for (;;) {\n const versions = await read(names);\n const differ: Record<string, number> = {};\n\n for (const name of names)\n if (versions[name] !== since[name])\n differ[name] = versions[name] ?? 0;\n\n const remaining = deadline - Date.now();\n\n if (Object.keys(differ).length > 0 || remaining <= 0) return differ;\n\n await new Promise<void>((resolve) => {\n const done = () => {\n clearTimeout(timer);\n waiters.delete(done);\n resolve();\n };\n const timer = setTimeout(done, Math.min(poll(), remaining));\n\n (timer as { unref?: () => void }).unref?.();\n waiters.add(done);\n });\n }\n },\n async bump(names) {\n const unique = [...new Set(names)];\n\n if (unique.length === 0) return;\n\n await store.bump(unique);\n wakeAll();\n if (store.notify) await store.notify();\n },\n };\n}\n\n/** The parts of a Postgres client `postgresVersions` uses: postgres.js and `Bun.sql` both have them. */\nexport interface PostgresClient {\n unsafe(\n text: string,\n params?: unknown[],\n ): PromiseLike<readonly Record<string, unknown>[]>;\n /** postgres.js and Bun.sql have it; with it, a waiting ask hears another instance at once. */\n listen?(channel: string, onNotify: (payload?: string) => void): unknown;\n notify?(channel: string, payload: string): unknown;\n}\n\n/**\n * Versions in Postgres, from the client the app already has:\n *\n * installVersionSource(postgresVersions(sql))\n *\n * `sqlVersions` with Postgres's placeholders, and - when the client can\n * LISTEN, as postgres.js and `Bun.sql` (Bun 1.4+) can - a change on one\n * instance wakes the waiting asks on every other at once, rather than on\n * their next read of the table. Without it, the table is read once a second\n * while an ask waits.\n *\n * CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL)\n */\nexport function postgresVersions(\n sql: PostgresClient,\n options: {\n table?: string;\n channel?: string;\n poll?: number;\n /**\n * A client to listen on, when `sql` goes through a connection pooler in\n * transaction mode - PgBouncer, or DigitalOcean's, Supabase's or Neon's\n * pooled connection - which hands the server connection back after each\n * statement, so a LISTEN on it hears nothing. A direct or session-mode\n * connection; reads and writes stay on `sql`. One connection per process.\n */\n listenWith?: PostgresClient;\n /**\n * `false`: do not listen - read every second instead, on purpose. For a\n * database whose direct connections are too few to spend one per process\n * on, behind a pooler that cannot listen. No listener, so no probe and no\n * warning about one. A change made in this process still reaches its own\n * tabs at once; one made elsewhere within about a second.\n */\n listen?: boolean;\n } = {},\n): PrunableVersions {\n const channel = options.channel ?? \"rsc_versions\";\n const listener = options.listenWith ?? sql;\n const listenOn =\n options.listen === false ? undefined : listener.listen?.bind(listener);\n\n // One statement per change: the upsert of every name, and the NOTIFY that\n // wakes every listening server - this one included - when it commits.\n return sqlVersions({\n query: async (text, params) => await sql.unsafe(text, params),\n placeholder: (n) => \"$\" + n,\n dialect: \"postgres\",\n channel,\n table: options.table,\n poll: options.poll,\n listen: listenOn\n ? async (wake, health) => {\n // A probe, sent the way a change is - through `sql` - and listened\n // for on the listening connection. Behind a transaction-mode pooler\n // the LISTEN lands on a connection the pooler takes back, sending\n // still works, and nothing says the listener is deaf: changes from\n // other instances would wait for the safety-net read. The probe\n // not arriving is how that is found out - once, as listening starts.\n const probe = \"rsc-kit:probe:\" + crypto.randomUUID();\n let heard = false;\n\n await listenOn(channel, (payload) => {\n if (payload === probe) heard = true;\n else wake();\n });\n await sql.unsafe(\"SELECT pg_notify($1, $2)\", [channel, probe]);\n\n const timer = setTimeout(() => {\n if (heard) return;\n\n health.deaf(\n \"listening on Postgres receives no notifications - is the connection going through a pooler \" +\n \"in transaction mode (PgBouncer; DigitalOcean, Supabase or Neon pooled connections)? \" +\n \"Pass a direct or session-mode connection: postgresVersions(sql, { listenWith }). \" +\n \"Reading every second meanwhile.\",\n );\n }, LISTEN_PROBE_MS);\n\n (timer as { unref?: () => void }).unref?.();\n }\n : undefined,\n });\n}\n\n/** How long a listener's probe may take to come back before it counts as deaf. */\nexport const LISTEN_PROBE_MS = 5_000;\n\nconst SOURCE = Symbol.for(\"rsc-kit.version-source\");\nconst BACKEND_SOURCE = Symbol.for(\"rsc-kit.backend-version-source\");\nconst LOCAL_SOURCE = Symbol.for(\"rsc-kit.local-version-source\");\nconst globals = globalThis as Record<symbol, unknown>;\n\n/**\n * Install where versions are read from - a table, Redis, any store - for this\n * process; `null` takes it out again.\n *\n * The app's choice wins over the backend's: with a Go or Laravel backend that\n * writes its versions to a store this process can read too, reading it here\n * means watching costs the backend nothing.\n */\nexport function installVersionSource(\n source: VersionSource | (() => VersionSource) | null,\n): void {\n globals[SOURCE] = source;\n}\n\n/** The engine's, when a backend is installed: its versions, read through it. Not for apps. */\nexport function installBackendVersionSource(\n source: VersionSource | null,\n): void {\n globals[BACKEND_SOURCE] = source;\n}\n\n/** The source in use: the app's, else the backend's, else this process's own. */\nexport function versionSource(): VersionSource {\n // A factory, made into the store on first use: a store made in register()\n // would make its database client in the build too, which runs register()\n // without the database's settings.\n if (typeof globals[SOURCE] === \"function\")\n globals[SOURCE] = (globals[SOURCE] as () => VersionSource)();\n\n const chosen =\n (globals[SOURCE] as VersionSource | null | undefined) ??\n (globals[BACKEND_SOURCE] as VersionSource | null | undefined);\n\n if (chosen) return chosen;\n\n let local = globals[LOCAL_SOURCE] as VersionSource | undefined;\n\n if (!local) {\n local = globals[LOCAL_SOURCE] = memoryVersions();\n\n // The fallback works in development and in tests, which are one process,\n // and fails silently in production with two: a change on one instance\n // never reaches the tabs on another. Said once, at the first use. An app\n // that really is one instance installs memoryVersions() itself, which is\n // a choice rather than a fallback, and is not warned.\n if (production()) {\n console.warn(\n \"[rsc-kit] refreshOn versions are kept in this process only: a change made on another \" +\n \"instance, or in a worker, will not reach the tabs this one serves. Install a store every \" +\n \"process shares with installVersionSource() in instrumentation.ts - sqlVersions for MySQL \" +\n \"or SQLite, postgresVersions for Postgres, createVersions for anything else: \" +\n \"https://docs.rsc-kit.dev/guides/live-data#where-the-versions-live. For a deploy that is one \" +\n \"instance, installVersionSource(memoryVersions()) says so.\",\n );\n }\n }\n\n return local;\n}\n\n/**\n * Say these names changed, so every open tab showing them refreshes.\n *\n * export async function POST(request: Request) { // a webhook, in a route.ts\n * const { team } = await request.json()\n * changed(`team:${team}:repos`)\n * return new Response(null, { status: 204 })\n * }\n *\n * For an app that keeps its versions here. With a backend the versions are\n * its, and so is the call: `rsckit.Changed`, `Rsc::changed`.\n */\nexport async function changed(...names: string[]): Promise<void> {\n await versionSource().bump(names);\n // On Workers with a hub, the tabs are held by the hub, not this isolate:\n // tell it, so they hear now rather than at the hub's next read.\n await pokeHub();\n}\n\n// ── Tokens ───────────────────────────────────────────────────────────────────\n//\n// A tab may watch exactly the names its page was rendered with. Rather than\n// remembering what each tab was given - state, which a Worker cannot keep\n// between requests - every name goes to the client signed, and comes back\n// with its signature. Verified, not looked up, so a watch request is\n// stateless, and a browser cannot make up a name to watch.\n\n/** Thrown when a production server has no key to sign names with. */\nexport class MissingSigningSecret extends Error {\n constructor() {\n super(\n \"refreshOn needs a signing secret in production, the same on every instance: set RSC_SIGNING_SECRET \" +\n \"to a long random string. Without one, each instance would sign with its own random key, and a tab \" +\n \"served by one would be refused by the next.\",\n );\n this.name = \"MissingSigningSecret\";\n }\n}\n\n// On the global rather than in this module: an app imports this file through\n// its own copy of the package, and a key configured there must be the key the\n// engine's copy signs and verifies with.\nconst KEY = Symbol.for(\"rsc-kit.signing-key\");\n\ninterface Keying {\n secret: string | null;\n keyed: Promise<CryptoKey> | null;\n signatures: Map<string, Promise<string>>;\n}\n\nfunction keying(): Keying {\n return ((globals[KEY] as Keying | undefined) ??= {\n secret: null,\n keyed: null,\n signatures: new Map(),\n });\n}\n\nconst env = (name: string): string | undefined =>\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env?.[name] || undefined;\n\nconst production = (): boolean => env(\"NODE_ENV\") === \"production\";\n\n/**\n * The secret names are signed with, when it does not come from the\n * environment. Normally it does: `RSC_SIGNING_SECRET`, the same on every\n * instance, or a tab served by one is refused by another.\n *\n * Its own secret, not the backend's host-call secret: that one authorises\n * calls between the renderer and a backend, and an app with no backend has\n * no reason to have it. Two jobs, two keys - one leaking does not hand out\n * the other.\n */\nexport function configureChanged(options: { secret?: string | null }): void {\n const state = keying();\n\n state.secret = options.secret ?? null;\n state.keyed = null;\n state.signatures.clear();\n}\n\n/** The secret in use: configured, or from the environment; null when there is none. */\nfunction secretInUse(): string | null {\n const state = keying();\n\n return state.secret ?? env(\"RSC_SIGNING_SECRET\") ?? null;\n}\n\n/**\n * Refuse, in production, to sign with a key nobody else has.\n *\n * A random key is right for one process - a dev server - and silently wrong\n * for two: every tab served by one instance is refused by the next, and never\n * refreshes. The server calls this on its first request when the app uses\n * refreshOn, so the misconfiguration is an error at once rather than a page\n * that quietly stops updating.\n */\nexport function assertSigningSecret(): void {\n if (!secretInUse() && production()) throw new MissingSigningSecret();\n}\n\nlet warnedRandom = false;\n\nasync function key(): Promise<CryptoKey> {\n const state = keying();\n\n return (state.keyed ??= (async () => {\n const secret = secretInUse();\n let raw: Uint8Array<ArrayBuffer>;\n\n if (secret) raw = new TextEncoder().encode(secret);\n else if (production()) throw new MissingSigningSecret();\n else {\n if (!warnedRandom) {\n warnedRandom = true;\n console.warn(\n \"[rsc-kit] refreshOn is signing with a random key, which is fine for one dev server. \" +\n \"Set RSC_SIGNING_SECRET before running more than one instance.\",\n );\n }\n\n raw = crypto.getRandomValues(new Uint8Array(32));\n }\n\n return await crypto.subtle.importKey(\n \"raw\",\n raw,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n })());\n}\n\n/** A name's signature: the first 16 bytes of an HMAC, base64url, which is what rides in a url. */\nexport function sign(name: string): Promise<string> {\n const { signatures } = keying();\n let pending = signatures.get(name);\n\n if (!pending) {\n pending = (async () => {\n const mac = await crypto.subtle.sign(\n \"HMAC\",\n await key(),\n new TextEncoder().encode(name),\n );\n\n return base64url(new Uint8Array(mac).slice(0, 16));\n })();\n\n // Bounded: a name with a visitor's id in it is a new entry per visitor.\n if (signatures.size > 10_000) signatures.clear();\n signatures.set(name, pending);\n }\n\n return pending;\n}\n\nasync function verify(name: string, signature: string): Promise<boolean> {\n const expected = await sign(name);\n\n if (expected.length !== signature.length) return false;\n\n let differ = 0;\n\n for (let i = 0; i < expected.length; i++)\n differ |= expected.charCodeAt(i) ^ signature.charCodeAt(i);\n\n return differ === 0;\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let text = \"\";\n\n for (const byte of bytes) text += String.fromCharCode(byte);\n\n return btoa(text).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** What a page hands the client for one name: its version at render, and its signature. */\nexport type SignedName = [version: number, signature: string];\n\n// ── Watching ─────────────────────────────────────────────────────────────────\n//\n// One stream per open tab, and one ask of the source per process: every\n// stream's names are asked about together, on an interval, and a version that\n// moved is written to every stream holding its name. A thousand tabs on a\n// long-lived server cost the backend one call per interval, not a thousand.\n// On a host that answers each request in its own isolate the sharing is\n// whatever the isolate serves at once, and a lone stream asks for itself -\n// the same code, degrading to one small call per tab per interval.\n\n/** How often the source is asked, when it answered at once. */\nexport const CHANGES_INTERVAL_MS = 2_000;\n\n/** How long the source may hold one ask. Bounds how long a new tab waits to join the shared ask. */\nexport const CHANGES_WAIT_MS = 5_000;\n\ninterface Stream {\n names: Set<string>;\n send(name: string, version: number): void;\n}\n\nconst streams = new Set<Stream>();\n\n/** The latest version seen for each name any stream holds. */\nconst known = new Map<string, number>();\n\nlet running = false;\nlet wake: (() => void) | null = null;\nlet warned = false;\n\nfunction observe(name: string, version: number): void {\n if (known.get(name) === version) return;\n\n known.set(name, version);\n\n for (const stream of streams)\n if (stream.names.has(name)) stream.send(name, version);\n}\n\n/**\n * A stream gone: and with it every name no other stream holds, which this\n * process has no reason to remember. Kept, the latest version of every name\n * any tab ever watched piled up for as long as the server ran.\n */\nfunction close(stream: Stream): void {\n if (!streams.delete(stream)) return;\n\n for (const name of stream.names) {\n let held = false;\n\n for (const other of streams) {\n if (other.names.has(name)) {\n held = true;\n break;\n }\n }\n\n if (!held) known.delete(name);\n }\n}\n\n/** Mapped to this process's set of streams: what to ask about, relative to what is known. */\nfunction sinceAll(): Record<string, number> {\n const since: Record<string, number> = {};\n\n for (const stream of streams)\n for (const name of stream.names) since[name] = known.get(name) ?? 0;\n\n return since;\n}\n\n// ── Waking ───────────────────────────────────────────────────────────────────\n//\n// A backend that cannot hold a question open - PHP - is asked again on an\n// interval. Something that can say \"a version moved\" the moment it does -\n// a broadcast, a Redis channel - makes that interval a safety net: the\n// renderer asks the moment it is woken, and otherwise rarely.\n\nconst WAKERS = Symbol.for(\"rsc-kit.wakers\");\n\ninterface Wakers {\n listens: ((wake: () => void, health: ListenerHealth) => unknown)[];\n started: boolean;\n /** A wake that came while an ask was in flight: ask again straight after. */\n pending: boolean;\n /** Asks a store is holding open, ended by a wake. */\n sleepers: Set<() => void>;\n}\n\nfunction wakers(): Wakers {\n return ((globals[WAKERS] as Wakers | undefined) ??= {\n listens: [],\n started: false,\n pending: false,\n sleepers: new Set(),\n });\n}\n\n/**\n * Wake the renderer when a version may have moved, so it asks then rather\n * than on its next interval.\n *\n * wakeOn(listenToBroadcast({ url, key })) // a broadcast server\n * wakeOn((wake) => subscriber.subscribe('rsc', wake)) // a Redis channel\n *\n * `listen` is given a function to call - it carries no names and no data;\n * the renderer asks wherever the versions live, as always. It is started\n * when the first tab starts watching, never in a build. With one installed,\n * a backend that answers at once is asked again every 30 seconds as a safety\n * net instead of every two.\n */\n/** What a listener is told besides how to wake: how to say it hears nothing. */\nexport interface ListenerHealth {\n /** This listener will never wake anything: say why, once, and stop counting on it. */\n deaf(reason: string): void;\n}\n\nexport function wakeOn(\n listen: (wake: () => void, health: ListenerHealth) => unknown,\n): void {\n const state = wakers();\n\n state.listens.push(listen);\n if (state.started) start(listen);\n}\n\n/**\n * Start one listener; one that fails - a database not up yet - is tried\n * again, backing off to thirty seconds. Until it is up the timer stands in.\n */\nfunction start(\n listen: (wake: () => void, health: ListenerHealth) => unknown,\n failures = 0,\n): void {\n const health: ListenerHealth = {\n deaf: (reason) => {\n const state = wakers();\n const at = state.listens.indexOf(listen);\n\n // No longer counted: the renderer goes back to asking on the shorter\n // interval, as it does with nothing to wake it.\n if (at === -1) return;\n state.listens.splice(at, 1);\n console.warn(\"[rsc-kit] \" + reason);\n },\n };\n\n void Promise.resolve()\n .then(() => listen(signal, health))\n .catch((error: unknown) => {\n if (failures === 0) {\n console.warn(\n \"[rsc-kit] a wakeOn listener failed to start, trying again: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n\n const retry = setTimeout(\n () => start(listen, failures + 1),\n Math.min(30_000, 1000 * 2 ** failures),\n );\n\n (retry as { unref?: () => void }).unref?.();\n });\n}\n\n/** Something said a version may have moved: ask now, and end any ask a store is holding. */\nfunction signal(): void {\n const state = wakers();\n\n state.pending = true;\n wake?.();\n for (const sleeper of [...state.sleepers]) sleeper();\n}\n\nfunction startWakers(): void {\n const state = wakers();\n\n if (state.started) return;\n state.started = true;\n\n // Set in the environment, not guessed: a broadcast server to listen to.\n const url = env(\"RSC_BROADCAST_URL\");\n const key = env(\"RSC_BROADCAST_KEY\");\n\n if (url && key) state.listens.push(listenToBroadcast({ url, key }));\n\n for (const listen of state.listens) start(listen);\n}\n\nasync function loop(): Promise<void> {\n running = true;\n startWakers();\n\n try {\n while (streams.size > 0) {\n const started = Date.now();\n const state = wakers();\n\n state.pending = false;\n\n try {\n const moved = await versionSource().changed(\n sinceAll(),\n CHANGES_WAIT_MS,\n );\n\n for (const [name, version] of Object.entries(moved))\n observe(name, version);\n } catch (error) {\n // A backend blip is not the end of watching. Said once, not per interval.\n if (!warned) {\n warned = true;\n console.warn(\n \"[rsc-kit] asking the backend for name versions failed: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n\n // A source that waited used the interval; one that answered at once is\n // asked again after it - or, with something to wake it, only as a\n // safety net. A stream opening, or a wake, ends the wait early; a wake\n // that came during the ask is answered at once.\n const interval =\n state.listens.length > 0 ? LISTENING_POLL_MS : CHANGES_INTERVAL_MS;\n const remaining = state.pending ? 0 : interval - (Date.now() - started);\n\n if (remaining > 0 && streams.size > 0) {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, remaining);\n\n (timer as { unref?: () => void }).unref?.();\n wake = () => {\n clearTimeout(timer);\n resolve();\n };\n });\n wake = null;\n }\n }\n } finally {\n running = false;\n // A stream that opened as the loop was ending starts it again.\n if (streams.size > 0) void loop();\n }\n}\n\nfunction parseWatch(\n url: URL,\n): { name: string; version: number; signature: string }[] | null {\n const raw = url.searchParams.get(\"w\");\n\n if (!raw) return null;\n\n let entries: unknown;\n\n try {\n entries = JSON.parse(raw);\n } catch {\n return null;\n }\n\n if (!Array.isArray(entries) || entries.length === 0 || entries.length > 200)\n return null;\n\n const parsed: { name: string; version: number; signature: string }[] = [];\n\n for (const entry of entries) {\n if (!Array.isArray(entry) || entry.length !== 3) return null;\n\n const [name, version, signature] = entry as unknown[];\n\n if (\n typeof name !== \"string\" ||\n typeof version !== \"number\" ||\n typeof signature !== \"string\"\n )\n return null;\n\n parsed.push({ name, version, signature });\n }\n\n return parsed;\n}\n\n/**\n * The stream a tab watches its names on: `GET /_rsc/changes?w=[[name, version, signature], …]`.\n *\n * One `data:` line per version that moved, `{ name, version }`, from the moment\n * the stream opens - a name that moved between the render and now is reported\n * at once, so nothing that happened in the gap is missed. Keepalives as an\n * events() route sends them; ends when the browser goes away.\n */\nexport async function changes(request: Request): Promise<Response> {\n const entries = parseWatch(new URL(request.url));\n\n if (!entries) return new Response(\"Bad watch request.\", { status: 400 });\n\n for (const { name, signature } of entries) {\n if (!(await verify(name, signature))) {\n return new Response(\"Not a name this page was rendered with.\", {\n status: 403,\n });\n }\n }\n\n const since: Record<string, number> = {};\n\n for (const { name, version } of entries) since[name] = version;\n\n const encoder = new TextEncoder();\n let stream: Stream | null = null;\n\n const body = new ReadableStream<Uint8Array>({\n start(sink) {\n const write = (text: string) => {\n try {\n sink.enqueue(encoder.encode(text));\n } catch {\n // Closed under us; the cancel below ends the rest.\n }\n };\n\n write(\"retry: 2000\\n\\n\");\n\n const keepalive = setInterval(\n () => write(\": keepalive\\n\\n\"),\n keepaliveMs(),\n );\n\n (keepalive as { unref?: () => void }).unref?.();\n\n const me: Stream = {\n names: new Set(Object.keys(since)),\n send: (name, version) => write(frame({ name, version })),\n };\n\n stream = me;\n streams.add(me);\n\n const end = () => {\n clearInterval(keepalive);\n close(me);\n\n try {\n sink.close();\n } catch {\n // Already closed.\n }\n };\n\n request.signal.addEventListener(\"abort\", end, { once: true });\n\n // What is known already answers at once; what is not is seeded with\n // what this tab holds, so the shared ask compares against it.\n for (const [name, version] of Object.entries(since)) {\n const seen = known.get(name);\n\n if (seen === undefined) known.set(name, version);\n else if (seen !== version) me.send(name, seen);\n }\n\n // This tab's own first ask, holding as long as the source will: the\n // shared ask may be mid-wait on an older set of names, and a name moving\n // in the seconds before this one joins it must not go unnoticed.\n void versionSource()\n .changed(since, CHANGES_WAIT_MS)\n .then((moved) => {\n for (const [name, version] of Object.entries(moved))\n observe(name, version);\n })\n .catch(() => {});\n\n if (!running) void loop();\n else wake?.();\n },\n cancel() {\n if (stream) close(stream);\n },\n });\n\n return new Response(body, {\n headers: {\n \"Content-Type\": \"text/event-stream; charset=utf-8\",\n // no-transform: a proxy or CDN in front must not compress or buffer\n // it either - Cloudflare compresses text unless told not to.\n \"Cache-Control\": \"no-store, no-transform\",\n \"X-Accel-Buffering\": \"no\",\n },\n });\n}\n\n/** For tests: forget every stream and version this process has seen. */\n/** For tests: how many names this process remembers for its open streams. */\nexport function rememberedNames(): number {\n return known.size;\n}\n\nexport function resetChanges(): void {\n warnedHub = false;\n delete globals[WAKERS];\n streams.clear();\n known.clear();\n warned = false;\n delete globals[LOCAL_SOURCE];\n}\n\n/** The url a tab opens to watch, for the client. */\nexport const CHANGES_PATH = HEADER.changesPath;\n\n// ── The hub ──────────────────────────────────────────────────────────────────\n//\n// On Workers each isolate watches for the tabs it happens to hold, which is\n// often one: an ask per tab per interval, a listener per isolate. A Durable\n// Object is one place every isolate can reach. With RSC_CHANGES_HUB naming\n// its binding, every tab's stream is forwarded to one instance of it, which\n// runs the shared ask above for all of them - one ask an interval for the\n// whole deployment, one listener, and a changed() anywhere wakes it at once.\n//\n// Opt-in, by name: the binding is the app's, declared in its wrangler config,\n// and nothing here guesses that a Durable Object is there to use.\n\n/** Marks a request the hub sent itself; its value is signed, so a browser cannot. */\nconst HUB_HEADER = \"x-rsc-changes-hub\";\n/** The one instance every isolate's streams go to. */\nconst HUB_INSTANCE = \"rsc-kit-changes\";\n/** What the header's value is the signature of. */\nconst HUB_PROOF = \"rsc-kit:changes-hub\";\n\ninterface HubNamespace {\n idFromName(name: string): unknown;\n get(id: unknown): { fetch(request: Request): Promise<Response> };\n}\n\nlet warnedHub = false;\n\n/** The hub's stub, when RSC_CHANGES_HUB names a Durable Object binding; null otherwise. */\nasync function hubStub(\n request?: Request,\n): Promise<{ fetch(request: Request): Promise<Response> } | null> {\n const binding = env(\"RSC_CHANGES_HUB\");\n\n if (!binding) return null;\n\n let bindings = (\n request as { runtime?: { cloudflare?: { env?: Record<string, unknown> } } } | undefined\n )?.runtime?.cloudflare?.env;\n\n // Nitro's Workers entry keeps the bindings here for code with no request -\n // changed() from a webhook's handler.\n bindings ??= (globalThis as { __env__?: Record<string, unknown> }).__env__;\n\n if (!bindings) {\n try {\n // Computed, so neither the bundler nor tsc looks for a module only the\n // Workers runtime has.\n const specifier = \"cloudflare:workers\";\n\n bindings = ((await import(/* @vite-ignore */ specifier)) as { env: Record<string, unknown> }).env;\n } catch {\n bindings = undefined;\n }\n }\n\n const namespace = bindings?.[binding] as HubNamespace | undefined;\n\n if (!namespace || typeof namespace.idFromName !== \"function\") {\n if (!warnedHub) {\n warnedHub = true;\n console.warn(\n `[rsc-kit] RSC_CHANGES_HUB names ${JSON.stringify(binding)}, which is not a Durable Object binding ` +\n \"here: each isolate watches for its own tabs. Declare the binding in wrangler config: \" +\n \"https://docs.rsc-kit.dev/guides/live-data#one-hub-on-workers\",\n );\n }\n\n return null;\n }\n\n return namespace.get(namespace.idFromName(HUB_INSTANCE));\n}\n\n/** Whether this request came from an isolate forwarding to the hub. */\nasync function fromIsolate(request: Request): Promise<boolean> {\n const proof = request.headers.get(HUB_HEADER);\n\n return proof !== null && (await verify(HUB_PROOF, proof));\n}\n\n/** Tell the hub something changed, so the tabs it holds hear at once. */\nasync function pokeHub(): Promise<void> {\n let stub: Awaited<ReturnType<typeof hubStub>>;\n\n try {\n stub = await hubStub();\n } catch {\n return;\n }\n\n if (!stub) return;\n\n try {\n await stub.fetch(\n new Request(\"https://hub\" + HEADER.changesPath, {\n method: \"POST\",\n headers: { [HUB_HEADER]: await sign(HUB_PROOF) },\n }),\n );\n } catch (error) {\n // The change is in the store; the hub reads it at its next ask.\n if (!warnedHub) {\n warnedHub = true;\n console.warn(\n \"[rsc-kit] telling the changes hub failed; its tabs hear at its next read: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n}\n\n/**\n * The changes endpoint: a tab's stream here, or - with a hub - in the hub,\n * where every tab's is. The hub itself answers what isolates forward to it:\n * a stream to hold, or a poke to ask now.\n */\nexport async function serveChanges(request: Request): Promise<Response> {\n // Forwarded, but not with this key: never forwarded again, which would be\n // a loop - the hub reaching itself - and never served as if from the hub.\n if (request.headers.has(HUB_HEADER) && !(await fromIsolate(request))) {\n return new Response(\"Not from this deployment's isolates.\", { status: 403 });\n }\n\n if (request.headers.has(HUB_HEADER)) {\n if (request.method === \"POST\") {\n signal();\n\n return new Response(null, { status: 204 });\n }\n\n return await changes(request);\n }\n\n if (request.method !== \"GET\") return new Response(\"Method not allowed.\", { status: 405 });\n\n const stub = await hubStub(request);\n\n if (!stub) return await changes(request);\n\n const headers = new Headers(request.headers);\n\n headers.set(HUB_HEADER, await sign(HUB_PROOF));\n\n const held = await stub.fetch(new Request(request.url, { method: \"GET\", headers, signal: request.signal }));\n\n // A stub's response has immutable headers, and the response is still the\n // app's to finish - the server adds its own on the way out.\n return new Response(held.body, held);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"changed.js","sourceRoot":"","sources":["../src/changed.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEnD,OAAO,EAAE,iBAAiB,EAAyB,MAAM,gBAAgB,CAAC;AAE1E,4DAA4D;AAC5D,MAAM,CAAC,MAAM,gBAAgB,GAAG,eAAe,CAAC;AAgChD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,WAAW,CAAC,OAAO,GAAG,CAAC;IACrC,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,GAAG,CAAC,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;AAC3C,CAAC;AAED,+FAA+F;AAC/F,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC;AAExC,sFAAsF;AACtF,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAEzD;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAC5B,OAAO,GAA6B,EAAE;IAEtC,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,gBAAgB,CAAC;IAC5D,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC3C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAc,CAAC;IACtC,IAAI,KAAK,GAAG,I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M,EAAE,CAAC,CAAC,CAAC;IAE5G,yEAAyE;IACzE,4DAA4D;IAC5D,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACvC,CAAC","sourcesContent":["/**\n * Names: a name for data a page depends on, so whatever changes it can say so\n * from anywhere - a webhook, a job, another visitor's action - and every open\n * tab showing it refreshes.\n *\n * // a section says what it depends on\n * export default section('repos', Repos, { refreshOn: ({ params }) => [`team:${params.team}:repos`] })\n *\n * // and whatever changes it says so\n * changed(`team:${team}:repos`) // here, from a route.ts or an action\n * rsckit.Changed(ctx, \"team:1:repos\") // or the backend, from its webhook\n * Rsc::changed(\"team:$team:repos\"); // Laravel\n *\n * A name has a version: a number that moves whenever something says the name\n * changed. Nothing else - not what changed, not the data. A page learns the\n * versions at render; one stream per open tab watches them; when one moves,\n * the sections carrying that name ask for themselves again, the way refresh()\n * does. Data is never pushed, which is what keeps this working on a host that\n * cannot hold state: a version is a read.\n *\n * Where versions live is the source's business. Without a backend they are in\n * this process, which is one instance. With one, the backend keeps them - in\n * its cache or a table, shared by every instance it runs - and answers\n * `__rsc.changed`: given the versions a watcher holds, the ones that differ now.\n * A backend that can wait holds the call until one does; one that cannot\n * answers at once, and the watcher asks again on its interval. The protocol\n * is the same either way, and so is the page.\n */\n\nimport { frame, keepaliveMs } from \"./events.js\";\nimport { HEADER } from \"./headers.js\";\nimport { listenToBroadcast } from \"./broadcast.js\";\n\nexport { listenToBroadcast, type BroadcastOptions } from \"./broadcast.js\";\n\n/** The reserved name a backend answers name versions on. */\nexport const CHANGED_FUNCTION = \"__rsc.changed\";\n\n/** What `__rsc.changed` is asked. */\nexport interface ChangedQuery {\n /** The versions the asker holds. A name never changed is 0; -1 asks for every current version. */\n since: Record<string, number>;\n /** How long the backend may hold the call waiting for one to differ, in ms. It may answer at once. */\n wait?: number;\n}\n\n/** What `__rsc.changed` answers: the versions among `since` that differ now. */\nexport interface ChangedAnswer {\n versions: Record<string, number>;\n}\n\n/**\n * Where name versions are read from, and - when they live here - bumped.\n *\n * `changed` answers the versions among `since` that differ now, and may wait\n * up to `wait` ms for one to. Nothing else is required of it, which is why a\n * backend's cache, a table, this process's memory, or a pub/sub that answers\n * the moment a name moves all fit behind it.\n */\nexport interface VersionSource {\n changed(\n since: Record<string, number>,\n wait: number,\n ): Promise<Record<string, number>>;\n /** Say these names changed. Only a source that holds its own versions can. */\n bump(names: string[]): void | Promise<void>;\n}\n\n/**\n * The version a name moves to: the larger of one past where it was and the\n * current time in milliseconds.\n *\n * A counter would do for \"it moved\", but a counter repeats once its row is\n * gone - deleted to keep the store small, a name starts again from 0 and\n * climbs back to a value some tab is still holding, and that tab misses the\n * change. A time never comes round again, so a name may be forgotten at any\n * moment: a tab holding the old value sees a different one, and at worst\n * refreshes once for nothing. It is also when the name last moved, which is\n * all cleanup needs. Every store bumps with it - a counter is not a version.\n */\nexport function nextVersion(current = 0): number {\n return Math.max(current + 1, Date.now());\n}\n\n/** The safety-net read of a store that listens: longer than any ask waits, so once per ask. */\nexport const LISTENING_POLL_MS = 30_000;\n\n/** How long a name nobody changes is kept, by the stores that forget on their own. */\nexport const VERSIONS_KEPT_MS = 30 * 24 * 60 * 60 * 1000;\n\n/**\n * Versions kept in this process: the source without a backend, and the one\n * tests use. A name not changed in `forgetAfter` ms (30 days) is forgotten,\n * swept at most once an hour, so a process up for months does not hold every\n * name it ever saw.\n */\nexport function memoryVersions(\n options: { forgetAfter?: number } = {},\n): VersionSource {\n const forgetAfter = options.forgetAfter ?? VERSIONS_KEPT_MS;\n const versions = new Map<string, number>();\n const waiters = new Set<() => void>();\n let swept = Date.now();\n\n const sweep = () => {\n const now = Date.now();\n\n if (now - swept < Math.min(forgetAfter, 60 * 60 * 1000)) return;\n swept = now;\n\n for (const [name, version] of versions)\n if (version < now - forgetAfter) versions.delete(name);\n };\n\n const differing = (since: Record<string, number>): Record<string, number> => {\n const out: Record<string, number> = {};\n\n for (const [name, held] of Object.entries(since)) {\n const current = versions.get(name) ?? 0;\n\n if (current !== held) out[name] = current;\n }\n\n return out;\n };\n\n return {\n async changed(since, wait) {\n const now = differing(since);\n\n if (Object.keys(now).length > 0 || wait <= 0) return now;\n\n await new Promise<void>((resolve) => {\n const done = () => {\n clearTimeout(timer);\n waiters.delete(done);\n resolve();\n };\n const timer = setTimeout(done, wait);\n\n // A test or a build must not be held open by a watcher's wait.\n (timer as { unref?: () => void }).unref?.();\n waiters.add(done);\n });\n\n return differing(since);\n },\n bump(names) {\n sweep();\n for (const name of names)\n versions.set(name, nextVersion(versions.get(name)));\n for (const wake of [...waiters]) wake();\n },\n };\n}\n\ntype HostFn = (name: string, ...args: unknown[]) => Promise<unknown>;\n\n/**\n * Versions kept by the backend, read through `__rsc.changed`.\n *\n * A backend that has not got the function - an adapter from before names, or\n * a host of plain rpc functions - is answered from this process instead,\n * found out on the first ask and remembered, so a page with names still works\n * on it: one instance, versions bumped by `changed()` here.\n */\nexport function backendVersions(call: HostFn): VersionSource {\n let local: VersionSource | null = null;\n\n // A backend's \"no such function\", or the test host's \"no handler for\".\n const unknown = (error: unknown): boolean =>\n /no host function named|has no handler for/i.test(\n error instanceof Error ? error.message : String(error),\n );\n\n return {\n async changed(since, wait) {\n if (local) return local.changed(since, wait);\n\n try {\n const answer = (await call(CHANGED_FUNCTION, {\n since,\n wait,\n } satisfies ChangedQuery)) as Partial<ChangedAnswer> | null;\n\n return answer?.versions ?? {};\n } catch (error) {\n if (!unknown(error)) throw error;\n\n local = memoryVersions();\n\n return local.changed(since, wait);\n }\n },\n bump(names) {\n if (local) return local.bump(names);\n\n throw new Error(\n \"changed() bumps versions this process keeps, and a backend keeps these: say the name changed there - \" +\n \"rsckit.Changed(ctx, ...) in Go, Rsc::changed(...) in Laravel.\",\n );\n },\n };\n}\n\n/** Runs one statement with positional parameters and resolves to its rows. */\nexport type SqlQuery = (\n text: string,\n params: unknown[],\n) => Promise<readonly Record<string, unknown>[]>;\n\nexport interface SqlVersionsOptions {\n /**\n * Which database, so a change is one statement - an upsert of every name\n * it moves - rather than a read and a write per name. Left out, the store\n * uses only SQL every database has, at the cost of those extra queries.\n */\n dialect?: \"postgres\" | \"mysql\" | \"sqlite\";\n /**\n * Postgres only: NOTIFY this channel in the same statement as the upsert,\n * so a listening server wakes - and only once the write commits.\n */\n channel?: string;\n /**\n * Your driver, as a function of SQL text and parameters:\n *\n * query: (text, params) => sql.unsafe(text, params) // postgres.js, Bun.sql\n * query: async (text, params) => (await pool.query(text, params)).rows // node-postgres\n */\n query: SqlQuery;\n /** The table: `CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL)`. */\n table?: string;\n /** How the n-th parameter is written (1-based). Default `?`; Postgres is `(n) => '$' + n`. */\n placeholder?: (n: number) => string;\n /**\n * Called once with a function that wakes every waiting ask, for a database\n * that can say the moment a version moved - Postgres's LISTEN:\n *\n * listen: (wake) => sql.listen('rsc_versions', wake)\n *\n * Without it, a waiting ask reads the table every `poll` ms.\n */\n listen?: (wake: () => void, health: ListenerHealth) => unknown;\n /**\n * Run after every bump, to tell the other instances - Postgres's NOTIFY:\n *\n * notify: () => sql.notify('rsc_versions', '')\n */\n notify?: () => unknown;\n /**\n * How often a waiting ask reads the table: every second by default, or,\n * with `listen`, only as a safety net - about once per ask.\n */\n poll?: number;\n}\n\n/**\n * Versions in a table every instance shares: the web servers, and the worker\n * that finishes a job and says so. The same table and columns Go's\n * `SQLVersions` uses, so a Go service and a JavaScript worker can share one.\n *\n * installVersionSource(sqlVersions({\n * query: (text, params) => sql.unsafe(text, params),\n * placeholder: (n) => '$' + n,\n * listen: (wake) => sql.listen('rsc_versions', wake),\n * notify: () => sql.notify('rsc_versions', ''),\n * }))\n *\n * Written with an UPDATE and, the first time, an INSERT - two statements any\n * SQL dialect has - rather than an upsert each spells differently. Takes the\n * app's own driver, so the engine has no database dependency of its own.\n */\n/**\n * One statement that moves every name to nextVersion: an upsert, in the\n * dialect's own words, and on Postgres the NOTIFY with it. A name is either\n * inserted at `now` or moved to the larger of one more and `now`.\n */\nfunction upsert(\n dialect: \"postgres\" | \"mysql\" | \"sqlite\",\n table: string,\n mark: (n: number) => string,\n names: string[],\n now: number,\n channel?: string,\n): [string, unknown[]] {\n if (dialect === \"postgres\") {\n // $1 is now, the names follow; the channel, if any, comes last.\n const rows = names.map((_, i) => `(${mark(i + 2)}, ${mark(1)})`).join(\", \");\n const insert =\n `INSERT INTO ${table} (name, version) VALUES ${rows} ` +\n `ON CONFLICT (name) DO UPDATE SET version = GREATEST(${table}.version + 1, EXCLUDED.version)`;\n\n if (!channel) return [insert, [now, ...names]];\n\n // A NOTIFY is delivered when the transaction commits, so a listener is\n // never woken before the change it is told about can be read.\n return [\n `WITH moved AS (${insert} RETURNING 1) SELECT pg_notify(${mark(names.length + 2)}, '') FROM (SELECT count(*) FROM moved) AS done`,\n [now, ...names, channel],\n ];\n }\n\n const rows = names.map(() => `(${mark(1)}, ${mark(1)})`).join(\", \");\n const params = names.flatMap((name) => [name, now]);\n\n return dialect === \"mysql\"\n ? [\n `INSERT INTO ${table} (name, version) VALUES ${rows} ON DUPLICATE KEY UPDATE version = GREATEST(version + 1, VALUES(version))`,\n params,\n ]\n : [\n `INSERT INTO ${table} (name, version) VALUES ${rows} ON CONFLICT (name) DO UPDATE SET version = MAX(version + 1, excluded.version)`,\n params,\n ];\n}\n\n/** A store whose old names can be cleared out: the SQL ones. */\nexport interface PrunableVersions extends VersionSource {\n /**\n * Delete every name not changed in `olderThan` ms (30 days by default).\n * Always safe: a version is a time and never comes round again, so a tab\n * still holding a pruned name sees it differ and refreshes once. Run it\n * from a scheduled job - a daily one is plenty.\n */\n prune(olderThan?: number): Promise<void>;\n}\n\nexport function sqlVersions(options: SqlVersionsOptions): PrunableVersions {\n const { query } = options;\n const table = options.table ?? \"rsc_versions\";\n const mark = options.placeholder ?? (() => \"?\");\n\n const source = createVersions(\n {\n async read(names) {\n const rows = await query(\n `SELECT name, version FROM ${table} WHERE name IN (${names.map((_, i) => mark(i + 1)).join(\", \")})`,\n names,\n );\n\n // A BIGINT comes back as a string from most drivers.\n return Object.fromEntries(\n rows.map((row) => [String(row.name), Number(row.version)]),\n );\n },\n async bump(names) {\n if (options.dialect) {\n await query(\n ...upsert(\n options.dialect,\n table,\n mark,\n names,\n Date.now(),\n options.channel,\n ),\n );\n\n return;\n }\n\n // nextVersion, in SQL every dialect has: CASE rather than GREATEST,\n // which SQLite spells MAX. The time is this process's, passed in, so\n // the database's clock never has to agree with it.\n const update =\n `UPDATE ${table} SET version = CASE WHEN version + 1 > ${mark(1)} THEN version + 1 ELSE ${mark(2)} END ` +\n `WHERE name = ${mark(3)}`;\n const insert = `INSERT INTO ${table} (name, version) VALUES (${mark(1)}, ${mark(2)})`;\n\n for (const name of names) {\n const now = Date.now();\n\n // The row count is not something every driver reports the same way,\n // so ask: a name with no row yet gets one.\n const [exists] = await query(\n `SELECT 1 AS found FROM ${table} WHERE name = ${mark(1)}`,\n [name],\n );\n\n if (exists) {\n await query(update, [now, now, name]);\n continue;\n }\n\n try {\n await query(insert, [name, now]);\n } catch {\n // Another instance inserted it first: bump that one.\n await query(update, [now, now, name]);\n }\n }\n },\n listen: options.listen,\n notify: options.notify,\n },\n { poll: options.poll },\n );\n\n return {\n ...source,\n async prune(olderThan = VERSIONS_KEPT_MS) {\n await query(`DELETE FROM ${table} WHERE version < ${mark(1)}`, [\n Date.now() - olderThan,\n ]);\n },\n };\n}\n\n/**\n * Where versions are kept, as the app writes it for its own database: the\n * three things rsc-kit cannot know about your storage, and nothing else.\n * `createVersions` does the rest - comparing, waiting, waking.\n *\n * // Drizzle\n * read: async (names) => Object.fromEntries(\n * (await db.select().from(rscVersions).where(inArray(rscVersions.name, names)))\n * .map((r) => [r.name, Number(r.version)])),\n * bump: async (names) => { for (const name of names) await db.insert(rscVersions)\n * .values({ name, version: Date.now() })\n * .onConflictDoUpdate({ target: rscVersions.name,\n * set: { version: sql`GREATEST(${rscVersions.version} + 1, excluded.version)` } }) },\n *\n * // Redis\n * read: async (names) => Object.fromEntries((await redis.mget(names.map(k)))\n * .map((v, i) => [names[i], Number(v ?? 0)])),\n * // nextVersion in one step: the larger of one past the old value and now.\n * bump: async (names) => { await Promise.all(names.map((n) => redis.eval(\n * \"local v = math.max(tonumber(redis.call('GET', KEYS[1]) or '0') + 1, tonumber(ARGV[1])) \" +\n * \"redis.call('SET', KEYS[1], v) return v\", 1, k(n), Date.now()))) },\n */\nexport interface VersionStore {\n /** The current version of each name asked for. A name it has never seen may be left out: it is 0. */\n read(names: string[]): Promise<Record<string, number>>;\n /**\n * Move each name's version to `nextVersion(current)` - one past where it\n * was, or the current time in ms if that is larger. Required, not a\n * suggestion: a version must never repeat, which is what makes it safe to\n * delete a name, and a counter repeats the moment one is deleted.\n */\n bump(names: string[]): Promise<void>;\n /**\n * Called once with a function that wakes every waiting ask, when the store\n * can say the moment a version moved - Postgres LISTEN, Redis SUBSCRIBE.\n * Without it a waiting ask reads again every `poll` ms.\n *\n * Given `health` too: a store that finds it hears nothing - a Postgres\n * listener behind a pooler in transaction mode - calls `health.deaf(why)`,\n * and rsc-kit says so and goes back to reading every second.\n */\n listen?(wake: () => void, health: ListenerHealth): unknown;\n /** Run after a bump, to tell the other instances listening: Postgres NOTIFY, Redis PUBLISH. */\n notify?(): unknown;\n}\n\n/**\n * A version source over any store: SQL through any driver or ORM - Drizzle,\n * Prisma, Kysely, Knex - or Redis, or anything with a read and an increment.\n *\n * installVersionSource(createVersions({ read, bump, listen, notify }))\n *\n * rsc-kit owns the rest: an ask waits up to the time it was given for a\n * version to differ, reading every `poll` ms (1000 by default) or the moment\n * `listen` wakes it, and a bump in this process wakes this process's asks at\n * once whatever the store.\n */\nexport function createVersions(\n store: VersionStore,\n options: { poll?: number } = {},\n): VersionSource {\n // A store that listens is woken the moment a version moves, so reading the\n // table on a timer is only a safety net - for a listening connection that\n // dropped without a word. Once an ask is enough: about every five seconds\n // per server, where one that cannot listen reads every second.\n let listening = Boolean(store.listen);\n const poll = () => options.poll ?? (listening ? LISTENING_POLL_MS : 1_000);\n const waiters = new Set<() => void>();\n const wakeAll = () => {\n for (const wake of [...waiters]) wake();\n };\n\n // A store that can listen wakes the renderer the way anything else does -\n // through wakeOn, which starts it with the first watching tab and never in\n // a build. A wake also ends an ask this store is holding.\n if (store.listen) {\n const listen = store.listen.bind(store);\n\n wakeOn((wake, health) =>\n listen(wake, {\n deaf: (reason) => {\n listening = false;\n health.deaf(reason);\n },\n }),\n );\n }\n wakers().sleepers.add(wakeAll);\n\n const read = async (names: string[]): Promise<Record<string, number>> => {\n if (names.length === 0) return {};\n\n const found = await store.read(names);\n\n return Object.fromEntries(\n names.map((name) => [name, Number(found[name] ?? 0)]),\n );\n };\n\n return {\n async changed(since, wait) {\n // Only a server with a tab watching asks with a wait - never a build -\n // so this is a safe moment to start listening, as is the first tab.\n if (wait > 0) startWakers();\n\n const names = Object.keys(since);\n const deadline = Date.now() + Math.max(0, wait);\n\n for (;;) {\n const versions = await read(names);\n const differ: Record<string, number> = {};\n\n for (const name of names)\n if (versions[name] !== since[name])\n differ[name] = versions[name] ?? 0;\n\n const remaining = deadline - Date.now();\n\n if (Object.keys(differ).length > 0 || remaining <= 0) return differ;\n\n await new Promise<void>((resolve) => {\n const done = () => {\n clearTimeout(timer);\n waiters.delete(done);\n resolve();\n };\n const timer = setTimeout(done, Math.min(poll(), remaining));\n\n (timer as { unref?: () => void }).unref?.();\n waiters.add(done);\n });\n }\n },\n async bump(names) {\n const unique = [...new Set(names)];\n\n if (unique.length === 0) return;\n\n await store.bump(unique);\n wakeAll();\n if (store.notify) await store.notify();\n },\n };\n}\n\n/** The parts of a Postgres client `postgresVersions` uses: postgres.js and `Bun.sql` both have them. */\nexport interface PostgresClient {\n unsafe(\n text: string,\n params?: unknown[],\n ): PromiseLike<readonly Record<string, unknown>[]>;\n /** postgres.js and Bun.sql have it; with it, a waiting ask hears another instance at once. */\n listen?(channel: string, onNotify: (payload?: string) => void): unknown;\n notify?(channel: string, payload: string): unknown;\n}\n\n/**\n * Versions in Postgres, from the client the app already has:\n *\n * installVersionSource(postgresVersions(sql))\n *\n * `sqlVersions` with Postgres's placeholders, and - when the client can\n * LISTEN, as postgres.js and `Bun.sql` (Bun 1.4+) can - a change on one\n * instance wakes the waiting asks on every other at once, rather than on\n * their next read of the table. Without it, the table is read once a second\n * while an ask waits.\n *\n * CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL)\n */\nexport function postgresVersions(\n sql: PostgresClient,\n options: {\n table?: string;\n channel?: string;\n poll?: number;\n /**\n * A client to listen on, when `sql` goes through a connection pooler in\n * transaction mode - PgBouncer, or DigitalOcean's, Supabase's or Neon's\n * pooled connection - which hands the server connection back after each\n * statement, so a LISTEN on it hears nothing. A direct or session-mode\n * connection; reads and writes stay on `sql`. One connection per process.\n */\n listenWith?: PostgresClient;\n /**\n * `false`: do not listen - read every second instead, on purpose. For a\n * database whose direct connections are too few to spend one per process\n * on, behind a pooler that cannot listen. No listener, so no probe and no\n * warning about one. A change made in this process still reaches its own\n * tabs at once; one made elsewhere within about a second.\n */\n listen?: boolean;\n } = {},\n): PrunableVersions {\n const channel = options.channel ?? \"rsc_versions\";\n const listener = options.listenWith ?? sql;\n const listenOn =\n options.listen === false ? undefined : listener.listen?.bind(listener);\n\n // One statement per change: the upsert of every name, and the NOTIFY that\n // wakes every listening server - this one included - when it commits.\n return sqlVersions({\n query: async (text, params) => await sql.unsafe(text, params),\n placeholder: (n) => \"$\" + n,\n dialect: \"postgres\",\n channel,\n table: options.table,\n poll: options.poll,\n listen: listenOn\n ? async (wake, health) => {\n // A probe, sent the way a change is - through `sql` - and listened\n // for on the listening connection. Behind a transaction-mode pooler\n // the LISTEN lands on a connection the pooler takes back, sending\n // still works, and nothing says the listener is deaf: changes from\n // other instances would wait for the safety-net read. The probe\n // not arriving is how that is found out - once, as listening starts.\n const probe = \"rsc-kit:probe:\" + crypto.randomUUID();\n let heard = false;\n\n await listenOn(channel, (payload) => {\n if (payload === probe) heard = true;\n else wake();\n });\n await sql.unsafe(\"SELECT pg_notify($1, $2)\", [channel, probe]);\n\n const timer = setTimeout(() => {\n if (heard) return;\n\n health.deaf(\n \"listening on Postgres receives no notifications - is the connection going through a pooler \" +\n \"in transaction mode (PgBouncer; DigitalOcean, Supabase or Neon pooled connections)? \" +\n \"Pass a direct or session-mode connection: postgresVersions(sql, { listenWith }). \" +\n \"Reading every second meanwhile.\",\n );\n }, LISTEN_PROBE_MS);\n\n (timer as { unref?: () => void }).unref?.();\n }\n : undefined,\n });\n}\n\n/** How long a listener's probe may take to come back before it counts as deaf. */\nexport const LISTEN_PROBE_MS = 5_000;\n\nconst SOURCE = Symbol.for(\"rsc-kit.version-source\");\nconst BACKEND_SOURCE = Symbol.for(\"rsc-kit.backend-version-source\");\nconst LOCAL_SOURCE = Symbol.for(\"rsc-kit.local-version-source\");\nconst globals = globalThis as Record<symbol, unknown>;\n\n/**\n * Install where versions are read from - a table, Redis, any store - for this\n * process; `null` takes it out again.\n *\n * The app's choice wins over the backend's: with a Go or Laravel backend that\n * writes its versions to a store this process can read too, reading it here\n * means watching costs the backend nothing.\n */\nexport function installVersionSource(\n source: VersionSource | (() => VersionSource) | null,\n): void {\n globals[SOURCE] = source;\n}\n\n/** The engine's, when a backend is installed: its versions, read through it. Not for apps. */\nexport function installBackendVersionSource(\n source: VersionSource | null,\n): void {\n globals[BACKEND_SOURCE] = source;\n}\n\n/** The source in use: the app's, else the backend's, else this process's own. */\nexport function versionSource(): VersionSource {\n // A factory, made into the store on first use: a store made in register()\n // would make its database client in the build too, which runs register()\n // without the database's settings.\n if (typeof globals[SOURCE] === \"function\")\n globals[SOURCE] = (globals[SOURCE] as () => VersionSource)();\n\n const chosen =\n (globals[SOURCE] as VersionSource | null | undefined) ??\n (globals[BACKEND_SOURCE] as VersionSource | null | undefined);\n\n if (chosen) return chosen;\n\n let local = globals[LOCAL_SOURCE] as VersionSource | undefined;\n\n if (!local) {\n local = globals[LOCAL_SOURCE] = memoryVersions();\n\n // The fallback works in development and in tests, which are one process,\n // and fails silently in production with two: a change on one instance\n // never reaches the tabs on another. Said once, at the first use. An app\n // that really is one instance installs memoryVersions() itself, which is\n // a choice rather than a fallback, and is not warned.\n if (production()) {\n console.warn(\n \"[rsc-kit] refreshOn versions are kept in this process only: a change made on another \" +\n \"instance, or in a worker, will not reach the tabs this one serves. Install a store every \" +\n \"process shares with installVersionSource() in instrumentation.ts - sqlVersions for MySQL \" +\n \"or SQLite, postgresVersions for Postgres, createVersions for anything else: \" +\n \"https://docs.rsc-kit.dev/guides/live-data#where-the-versions-live. For a deploy that is one \" +\n \"instance, installVersionSource(memoryVersions()) says so.\",\n );\n }\n }\n\n return local;\n}\n\n/**\n * Say these names changed, so every open tab showing them refreshes.\n *\n * export async function POST(request: Request) { // a webhook, in a route.ts\n * const { team } = await request.json()\n * changed(`team:${team}:repos`)\n * return new Response(null, { status: 204 })\n * }\n *\n * For an app that keeps its versions here. With a backend the versions are\n * its, and so is the call: `rsckit.Changed`, `Rsc::changed`.\n */\nexport async function changed(...names: string[]): Promise<void> {\n await versionSource().bump(names);\n // On Workers with a hub, the tabs are held by the hub, not this isolate:\n // tell it, so they hear now rather than at the hub's next read.\n await pokeHub();\n}\n\n// ── Tokens ───────────────────────────────────────────────────────────────────\n//\n// A tab may watch exactly the names its page was rendered with. Rather than\n// remembering what each tab was given - state, which a Worker cannot keep\n// between requests - every name goes to the client signed, and comes back\n// with its signature. Verified, not looked up, so a watch request is\n// stateless, and a browser cannot make up a name to watch.\n\n/** Thrown when a production server has no key to sign names with. */\nexport class MissingSigningSecret extends Error {\n constructor() {\n super(\n \"refreshOn needs a signing secret in production, the same on every instance: set RSC_SIGNING_SECRET \" +\n \"to a long random string. Without one, each instance would sign with its own random key, and a tab \" +\n \"served by one would be refused by the next.\",\n );\n this.name = \"MissingSigningSecret\";\n }\n}\n\n// On the global rather than in this module: an app imports this file through\n// its own copy of the package, and a key configured there must be the key the\n// engine's copy signs and verifies with.\nconst KEY = Symbol.for(\"rsc-kit.signing-key\");\n\ninterface Keying {\n secret: string | null;\n keyed: Promise<CryptoKey> | null;\n signatures: Map<string, Promise<string>>;\n}\n\nfunction keying(): Keying {\n return ((globals[KEY] as Keying | undefined) ??= {\n secret: null,\n keyed: null,\n signatures: new Map(),\n });\n}\n\nconst env = (name: string): string | undefined =>\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env?.[name] || undefined;\n\nconst production = (): boolean => env(\"NODE_ENV\") === \"production\";\n\n/**\n * The secret names are signed with, when it does not come from the\n * environment. Normally it does: `RSC_SIGNING_SECRET`, the same on every\n * instance, or a tab served by one is refused by another.\n *\n * Its own secret, not the backend's host-call secret: that one authorises\n * calls between the renderer and a backend, and an app with no backend has\n * no reason to have it. Two jobs, two keys - one leaking does not hand out\n * the other.\n */\nexport function configureChanged(options: { secret?: string | null }): void {\n const state = keying();\n\n state.secret = options.secret ?? null;\n state.keyed = null;\n state.signatures.clear();\n}\n\n/** The secret in use: configured, or from the environment; null when there is none. */\nfunction secretInUse(): string | null {\n const state = keying();\n\n return state.secret ?? env(\"RSC_SIGNING_SECRET\") ?? null;\n}\n\n/**\n * Refuse, in production, to sign with a key nobody else has.\n *\n * A random key is right for one process - a dev server - and silently wrong\n * for two: every tab served by one instance is refused by the next, and never\n * refreshes. The server calls this on its first request when the app uses\n * refreshOn, so the misconfiguration is an error at once rather than a page\n * that quietly stops updating.\n */\nexport function assertSigningSecret(): void {\n if (!secretInUse() && production()) throw new MissingSigningSecret();\n}\n\nlet warnedRandom = false;\n\nasync function key(): Promise<CryptoKey> {\n const state = keying();\n\n return (state.keyed ??= (async () => {\n const secret = secretInUse();\n let raw: Uint8Array<ArrayBuffer>;\n\n if (secret) raw = new TextEncoder().encode(secret);\n else if (production()) throw new MissingSigningSecret();\n else {\n if (!warnedRandom) {\n warnedRandom = true;\n console.warn(\n \"[rsc-kit] refreshOn is signing with a random key, which is fine for one dev server. \" +\n \"Set RSC_SIGNING_SECRET before running more than one instance.\",\n );\n }\n\n raw = crypto.getRandomValues(new Uint8Array(32));\n }\n\n return await crypto.subtle.importKey(\n \"raw\",\n raw,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n })());\n}\n\n/** A name's signature: the first 16 bytes of an HMAC, base64url, which is what rides in a url. */\nexport function sign(name: string): Promise<string> {\n const { signatures } = keying();\n let pending = signatures.get(name);\n\n if (!pending) {\n pending = (async () => {\n const mac = await crypto.subtle.sign(\n \"HMAC\",\n await key(),\n new TextEncoder().encode(name),\n );\n\n return base64url(new Uint8Array(mac).slice(0, 16));\n })();\n\n // Bounded: a name with a visitor's id in it is a new entry per visitor.\n if (signatures.size > 10_000) signatures.clear();\n signatures.set(name, pending);\n }\n\n return pending;\n}\n\nasync function verify(name: string, signature: string): Promise<boolean> {\n const expected = await sign(name);\n\n if (expected.length !== signature.length) return false;\n\n let differ = 0;\n\n for (let i = 0; i < expected.length; i++)\n differ |= expected.charCodeAt(i) ^ signature.charCodeAt(i);\n\n return differ === 0;\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let text = \"\";\n\n for (const byte of bytes) text += String.fromCharCode(byte);\n\n return btoa(text).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** What a page hands the client for one name: its version at render, and its signature. */\nexport type SignedName = [version: number, signature: string];\n\n// ── Watching ─────────────────────────────────────────────────────────────────\n//\n// One stream per open tab, and one ask of the source per process: every\n// stream's names are asked about together, on an interval, and a version that\n// moved is written to every stream holding its name. A thousand tabs on a\n// long-lived server cost the backend one call per interval, not a thousand.\n// On a host that answers each request in its own isolate the sharing is\n// whatever the isolate serves at once, and a lone stream asks for itself -\n// the same code, degrading to one small call per tab per interval.\n\n/** How often the source is asked, when it answered at once. */\nexport const CHANGES_INTERVAL_MS = 2_000;\n\n/** How long the source may hold one ask. Bounds how long a new tab waits to join the shared ask. */\nexport const CHANGES_WAIT_MS = 5_000;\n\ninterface Stream {\n names: Set<string>;\n send(name: string, version: number): void;\n}\n\nconst streams = new Set<Stream>();\n\n/** The latest version seen for each name any stream holds. */\nconst known = new Map<string, number>();\n\nlet running = false;\nlet wake: (() => void) | null = null;\nlet warned = false;\n\nfunction observe(name: string, version: number): void {\n if (known.get(name) === version) return;\n\n known.set(name, version);\n\n for (const stream of streams)\n if (stream.names.has(name)) stream.send(name, version);\n}\n\n/**\n * A stream gone: and with it every name no other stream holds, which this\n * process has no reason to remember. Kept, the latest version of every name\n * any tab ever watched piled up for as long as the server ran.\n */\nfunction close(stream: Stream): void {\n if (!streams.delete(stream)) return;\n\n for (const name of stream.names) {\n let held = false;\n\n for (const other of streams) {\n if (other.names.has(name)) {\n held = true;\n break;\n }\n }\n\n if (!held) known.delete(name);\n }\n}\n\n/** Mapped to this process's set of streams: what to ask about, relative to what is known. */\nfunction sinceAll(): Record<string, number> {\n const since: Record<string, number> = {};\n\n for (const stream of streams)\n for (const name of stream.names) since[name] = known.get(name) ?? 0;\n\n return since;\n}\n\n// ── Waking ───────────────────────────────────────────────────────────────────\n//\n// A backend that cannot hold a question open - PHP - is asked again on an\n// interval. Something that can say \"a version moved\" the moment it does -\n// a broadcast, a Redis channel - makes that interval a safety net: the\n// renderer asks the moment it is woken, and otherwise rarely.\n\nconst WAKERS = Symbol.for(\"rsc-kit.wakers\");\n\ninterface Wakers {\n listens: ((wake: () => void, health: ListenerHealth) => unknown)[];\n started: boolean;\n /** A wake that came while an ask was in flight: ask again straight after. */\n pending: boolean;\n /** Asks a store is holding open, ended by a wake. */\n sleepers: Set<() => void>;\n}\n\nfunction wakers(): Wakers {\n return ((globals[WAKERS] as Wakers | undefined) ??= {\n listens: [],\n started: false,\n pending: false,\n sleepers: new Set(),\n });\n}\n\n/**\n * Wake the renderer when a version may have moved, so it asks then rather\n * than on its next interval.\n *\n * wakeOn(listenToBroadcast({ url, key })) // a broadcast server\n * wakeOn((wake) => subscriber.subscribe('rsc', wake)) // a Redis channel\n *\n * `listen` is given a function to call - it carries no names and no data;\n * the renderer asks wherever the versions live, as always. It is started\n * when the first tab starts watching, never in a build. With one installed,\n * a backend that answers at once is asked again every 30 seconds as a safety\n * net instead of every two.\n */\n/** What a listener is told besides how to wake: how to say it hears nothing. */\nexport interface ListenerHealth {\n /** This listener will never wake anything: say why, once, and stop counting on it. */\n deaf(reason: string): void;\n}\n\nexport function wakeOn(\n listen: (wake: () => void, health: ListenerHealth) => unknown,\n): void {\n const state = wakers();\n\n state.listens.push(listen);\n if (state.started) start(listen);\n}\n\n/**\n * Start one listener; one that fails - a database not up yet - is tried\n * again, backing off to thirty seconds. Until it is up the timer stands in.\n */\nfunction start(\n listen: (wake: () => void, health: ListenerHealth) => unknown,\n failures = 0,\n): void {\n const health: ListenerHealth = {\n deaf: (reason) => {\n const state = wakers();\n const at = state.listens.indexOf(listen);\n\n // No longer counted: the renderer goes back to asking on the shorter\n // interval, as it does with nothing to wake it.\n if (at === -1) return;\n state.listens.splice(at, 1);\n console.warn(\"[rsc-kit] \" + reason);\n },\n };\n\n void Promise.resolve()\n .then(() => listen(signal, health))\n .catch((error: unknown) => {\n if (failures === 0) {\n console.warn(\n \"[rsc-kit] a wakeOn listener failed to start, trying again: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n\n const retry = setTimeout(\n () => start(listen, failures + 1),\n Math.min(30_000, 1000 * 2 ** failures),\n );\n\n (retry as { unref?: () => void }).unref?.();\n });\n}\n\n/** Something said a version may have moved: ask now, and end any ask a store is holding. */\nfunction signal(): void {\n const state = wakers();\n\n state.pending = true;\n wake?.();\n for (const sleeper of [...state.sleepers]) sleeper();\n}\n\nfunction startWakers(): void {\n const state = wakers();\n\n if (state.started) return;\n state.started = true;\n\n // Set in the environment, not guessed: a broadcast server to listen to.\n const url = env(\"RSC_BROADCAST_URL\");\n const key = env(\"RSC_BROADCAST_KEY\");\n\n if (url && key) state.listens.push(listenToBroadcast({ url, key }));\n\n for (const listen of state.listens) start(listen);\n}\n\nasync function loop(): Promise<void> {\n running = true;\n startWakers();\n\n try {\n while (streams.size > 0) {\n const started = Date.now();\n const state = wakers();\n\n state.pending = false;\n\n try {\n const moved = await versionSource().changed(\n sinceAll(),\n CHANGES_WAIT_MS,\n );\n\n for (const [name, version] of Object.entries(moved))\n observe(name, version);\n } catch (error) {\n // A backend blip is not the end of watching. Said once, not per interval.\n if (!warned) {\n warned = true;\n console.warn(\n \"[rsc-kit] asking the backend for name versions failed: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n\n // A source that waited used the interval; one that answered at once is\n // asked again after it - or, with something to wake it, only as a\n // safety net. A stream opening, or a wake, ends the wait early; a wake\n // that came during the ask is answered at once.\n const interval =\n state.listens.length > 0 ? LISTENING_POLL_MS : CHANGES_INTERVAL_MS;\n const remaining = state.pending ? 0 : interval - (Date.now() - started);\n\n if (remaining > 0 && streams.size > 0) {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, remaining);\n\n (timer as { unref?: () => void }).unref?.();\n wake = () => {\n clearTimeout(timer);\n resolve();\n };\n });\n wake = null;\n }\n }\n } finally {\n running = false;\n // A stream that opened as the loop was ending starts it again.\n if (streams.size > 0) void loop();\n }\n}\n\nfunction parseWatch(\n url: URL,\n): { name: string; version: number; signature: string }[] | null {\n const raw = url.searchParams.get(\"w\");\n\n if (!raw) return null;\n\n let entries: unknown;\n\n try {\n entries = JSON.parse(raw);\n } catch {\n return null;\n }\n\n if (!Array.isArray(entries) || entries.length === 0 || entries.length > 200)\n return null;\n\n const parsed: { name: string; version: number; signature: string }[] = [];\n\n for (const entry of entries) {\n if (!Array.isArray(entry) || entry.length !== 3) return null;\n\n const [name, version, signature] = entry as unknown[];\n\n if (\n typeof name !== \"string\" ||\n typeof version !== \"number\" ||\n typeof signature !== \"string\"\n )\n return null;\n\n parsed.push({ name, version, signature });\n }\n\n return parsed;\n}\n\n/**\n * The stream a tab watches its names on: `GET /_rsc/changes?w=[[name, version, signature], …]`.\n *\n * One `data:` line per version that moved, `{ name, version }`, from the moment\n * the stream opens - a name that moved between the render and now is reported\n * at once, so nothing that happened in the gap is missed. Keepalives as an\n * events() route sends them; ends when the browser goes away.\n */\nexport async function changes(request: Request): Promise<Response> {\n const entries = parseWatch(new URL(request.url));\n\n if (!entries) return new Response(\"Bad watch request.\", { status: 400 });\n\n for (const { name, signature } of entries) {\n if (!(await verify(name, signature))) {\n return new Response(\"Not a name this page was rendered with.\", {\n status: 403,\n });\n }\n }\n\n const since: Record<string, number> = {};\n\n for (const { name, version } of entries) since[name] = version;\n\n const encoder = new TextEncoder();\n let stream: Stream | null = null;\n\n const body = new ReadableStream<Uint8Array>({\n start(sink) {\n const write = (text: string) => {\n try {\n sink.enqueue(encoder.encode(text));\n } catch {\n // Closed under us; the cancel below ends the rest.\n }\n };\n\n write(\"retry: 2000\\n\\n\");\n\n const keepalive = setInterval(\n () => write(\": keepalive\\n\\n\"),\n keepaliveMs(),\n );\n\n (keepalive as { unref?: () => void }).unref?.();\n\n const me: Stream = {\n names: new Set(Object.keys(since)),\n send: (name, version) => write(frame({ name, version })),\n };\n\n stream = me;\n streams.add(me);\n\n const end = () => {\n clearInterval(keepalive);\n close(me);\n\n try {\n sink.close();\n } catch {\n // Already closed.\n }\n };\n\n request.signal.addEventListener(\"abort\", end, { once: true });\n\n // What is known already answers at once; what is not is seeded with\n // what this tab holds, so the shared ask compares against it.\n for (const [name, version] of Object.entries(since)) {\n const seen = known.get(name);\n\n if (seen === undefined) known.set(name, version);\n else if (seen !== version) me.send(name, seen);\n }\n\n // This tab's own first ask, holding as long as the source will: the\n // shared ask may be mid-wait on an older set of names, and a name moving\n // in the seconds before this one joins it must not go unnoticed.\n void versionSource()\n .changed(since, CHANGES_WAIT_MS)\n .then((moved) => {\n for (const [name, version] of Object.entries(moved))\n observe(name, version);\n })\n .catch(() => {});\n\n if (!running) void loop();\n else wake?.();\n },\n cancel() {\n if (stream) close(stream);\n },\n });\n\n return new Response(body, {\n headers: {\n \"Content-Type\": \"text/event-stream; charset=utf-8\",\n // no-transform: a proxy or CDN in front must not compress or buffer\n // it either - Cloudflare compresses text unless told not to.\n \"Cache-Control\": \"no-store, no-transform\",\n \"X-Accel-Buffering\": \"no\",\n },\n });\n}\n\n/** For tests: forget every stream and version this process has seen. */\n/** For tests: how many names this process remembers for its open streams. */\nexport function rememberedNames(): number {\n return known.size;\n}\n\nexport function resetChanges(): void {\n warnedHub = false;\n delete globals[WAKERS];\n streams.clear();\n known.clear();\n warned = false;\n delete globals[LOCAL_SOURCE];\n}\n\n/** The url a tab opens to watch, for the client. */\nexport const CHANGES_PATH = HEADER.changesPath;\n\n// ── The hub ──────────────────────────────────────────────────────────────────\n//\n// On Workers each isolate watches for the tabs it happens to hold, which is\n// often one: an ask per tab per interval, a listener per isolate. A Durable\n// Object is one place every isolate can reach. With RSC_CHANGES_HUB naming\n// its binding, every tab's stream is forwarded to one instance of it, which\n// runs the shared ask above for all of them - one ask an interval for the\n// whole deployment, one listener, and a changed() anywhere wakes it at once.\n//\n// Opt-in, by name: the binding is the app's, declared in its wrangler config,\n// and nothing here guesses that a Durable Object is there to use.\n\n/** Marks a request the hub sent itself; its value is signed, so a browser cannot. */\nconst HUB_HEADER = \"x-rsc-changes-hub\";\n/** The one instance every isolate's streams go to. */\nconst HUB_INSTANCE = \"rsc-kit-changes\";\n/** What the header's value is the signature of. */\nconst HUB_PROOF = \"rsc-kit:changes-hub\";\n\ninterface HubNamespace {\n idFromName(name: string): unknown;\n get(id: unknown): { fetch(request: Request): Promise<Response> };\n}\n\nlet warnedHub = false;\n\n/** The hub's stub, when RSC_CHANGES_HUB names a Durable Object binding; null otherwise. */\nasync function hubStub(\n request?: Request,\n): Promise<{ fetch(request: Request): Promise<Response> } | null> {\n const binding = env(\"RSC_CHANGES_HUB\");\n\n if (!binding) return null;\n\n let bindings = (\n request as { runtime?: { cloudflare?: { env?: Record<string, unknown> } } } | undefined\n )?.runtime?.cloudflare?.env;\n\n // Nitro's Workers entry keeps the bindings here for code with no request -\n // changed() from a webhook's handler.\n bindings ??= (globalThis as { __env__?: Record<string, unknown> }).__env__;\n\n if (!bindings) {\n try {\n // Computed, so neither the bundler nor tsc looks for a module only the\n // Workers runtime has.\n const specifier = \"cloudflare:workers\";\n\n bindings = ((await import(/* @vite-ignore */ specifier)) as { env: Record<string, unknown> }).env;\n } catch {\n bindings = undefined;\n }\n }\n\n const namespace = bindings?.[binding] as HubNamespace | undefined;\n\n if (!namespace || typeof namespace.idFromName !== \"function\") {\n if (!warnedHub) {\n warnedHub = true;\n console.warn(\n `[rsc-kit] RSC_CHANGES_HUB names ${JSON.stringify(binding)}, which is not a Durable Object binding ` +\n \"here: each isolate watches for its own tabs. Declare the binding in wrangler config: \" +\n \"https://docs.rsc-kit.dev/guides/live-data#one-hub-on-workers\",\n );\n }\n\n return null;\n }\n\n return namespace.get(namespace.idFromName(HUB_INSTANCE));\n}\n\n/** Whether this request came from an isolate forwarding to the hub. */\nasync function fromIsolate(request: Request): Promise<boolean> {\n const proof = request.headers.get(HUB_HEADER);\n\n return proof !== null && (await verify(HUB_PROOF, proof));\n}\n\n/** Tell the hub something changed, so the tabs it holds hear at once. */\nasync function pokeHub(): Promise<void> {\n let stub: Awaited<ReturnType<typeof hubStub>>;\n\n try {\n stub = await hubStub();\n } catch {\n return;\n }\n\n if (!stub) return;\n\n try {\n await stub.fetch(\n new Request(\"https://hub\" + HEADER.changesPath, {\n method: \"POST\",\n headers: { [HUB_HEADER]: await sign(HUB_PROOF) },\n }),\n );\n } catch (error) {\n // The change is in the store; the hub reads it at its next ask.\n if (!warnedHub) {\n warnedHub = true;\n console.warn(\n \"[rsc-kit] telling the changes hub failed; its tabs hear at its next read: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n}\n\n/**\n * The changes endpoint: a tab's stream here, or - with a hub - in the hub,\n * where every tab's is. The hub itself answers what isolates forward to it:\n * a stream to hold, or a poke to ask now.\n */\nexport async function serveChanges(request: Request): Promise<Response> {\n // Forwarded, but not with this key: never forwarded again, which would be\n // a loop - the hub reaching itself - and never served as if from the hub.\n if (request.headers.has(HUB_HEADER) && !(await fromIsolate(request))) {\n return new Response(\"Not from this deployment's isolates.\", { status: 403 });\n }\n\n if (request.headers.has(HUB_HEADER)) {\n if (request.method === \"POST\") {\n signal();\n\n return new Response(null, { status: 204 });\n }\n\n return await changes(request);\n }\n\n if (request.method !== \"GET\") return new Response(\"Method not allowed.\", { status: 405 });\n\n const stub = await hubStub(request);\n\n if (!stub) return await changes(request);\n\n const headers = new Headers(request.headers);\n\n headers.set(HUB_HEADER, await sign(HUB_PROOF));\n\n const held = await stub.fetch(new Request(request.url, { method: \"GET\", headers, signal: request.signal }));\n\n // A stub's response has immutable headers, and the response is still the\n // app's to finish - the server adds its own on the way out.\n return new Response(held.body, held);\n}\n"]}
|
package/dist/conformance.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ export interface ConformanceOptions {
|
|
|
9
9
|
secret: string;
|
|
10
10
|
/** The adapter's rsc-host.json, parsed or as a path: its types are checked against what arrives. */
|
|
11
11
|
manifest?: string | {
|
|
12
|
+
actions?: unknown;
|
|
12
13
|
functions?: string[];
|
|
13
14
|
types?: Record<string, {
|
|
14
15
|
result?: Schema;
|
|
@@ -43,7 +44,11 @@ export declare const CASES: {
|
|
|
43
44
|
readonly 'Conformance.revalidate': 'Mark the region "orders" stale, and return "ok".';
|
|
44
45
|
readonly 'Conformance.fail': 'Fail unexpectedly: an ordinary error, not a refusal.';
|
|
45
46
|
readonly 'Conformance.authorization': "Return the request's Authorization header, as the renderer forwarded it.";
|
|
46
|
-
readonly '
|
|
47
|
+
readonly 'Conformance.cookie': "Return the request's Cookie header, as the renderer forwarded it.";
|
|
48
|
+
readonly 'Conformance.login': 'Set a cookie named "conformance_login" on the response, the way a login sets its session cookie, and return "ok".';
|
|
49
|
+
readonly 'Conformance.double': 'Take one integer and return it doubled. Arguments that do not fit - a string, none - fail it: a 500, not a refusal.';
|
|
50
|
+
readonly 'Conformance.invalidNested': 'Refuse the input with errors on the nested field "address.city" and on the form itself, under "".';
|
|
51
|
+
readonly '__rsc.middleware': string;
|
|
47
52
|
readonly 'Conformance.change': 'Say the name "conformance:changed" changed, the way the adapter does from a webhook, and return "ok".';
|
|
48
53
|
readonly '__rsc.changed': string;
|
|
49
54
|
};
|
|
@@ -57,6 +62,14 @@ export declare function conformance(call: ConformanceCall, options: {
|
|
|
57
62
|
revalidated: string[][];
|
|
58
63
|
manifest?: ConformanceOptions['manifest'];
|
|
59
64
|
wrongSecret?: ConformanceCall;
|
|
65
|
+
/**
|
|
66
|
+
* A POST straight to the endpoint, for what the client never sends:
|
|
67
|
+
* malformed bodies, an oversized batch, no secret at all. `secret: false`
|
|
68
|
+
* leaves the header off.
|
|
69
|
+
*/
|
|
70
|
+
raw?: (body: string, options?: {
|
|
71
|
+
secret?: boolean;
|
|
72
|
+
}) => Promise<Response>;
|
|
60
73
|
}): Promise<ConformanceResult[]>;
|
|
61
74
|
/** Run the suite against an adapter's endpoint. */
|
|
62
75
|
export declare function runConformance(options: ConformanceOptions): Promise<ConformanceResult[]>;
|