@somewhere-cloud/cli 0.38.30 → 0.38.32

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.
@@ -1667,120 +1667,6 @@ function __sw_runtimeErrorMetadata(error) {
1667
1667
  // worker/src/utils/database-plane-bindings.ts
1668
1668
  var LEGACY_DATABASE_LAYOUT = Object.freeze({ layout: "legacy" });
1669
1669
 
1670
- // worker/src/runtime/live-client.ts
1671
- var LIVE_CLIENT_MODULE_JS = `
1672
- export function watchLive(load, render) {
1673
- if (typeof load !== 'function' || typeof render !== 'function') {
1674
- throw new TypeError('watchLive takes exactly (load, render)');
1675
- }
1676
- let stopped = false;
1677
- let socket = null;
1678
- let socketGeneration = 0;
1679
- let liveKey = null;
1680
- let inFlight = null;
1681
- let dirty = false;
1682
- let reconnectRequested = false;
1683
- let debounceTimer = null;
1684
- let retryTimer = null;
1685
- let retryFailures = 0;
1686
-
1687
- function connect(live) {
1688
- if (!live || live.state !== 'ready' || typeof live.subscribe_url !== 'string') return;
1689
- if (retryTimer !== null) return;
1690
- const nextKey = String(live.release_id) + ':' + String(live.fingerprint);
1691
- const generation = ++socketGeneration;
1692
- if (socket) { try { socket.close(1000, 'refresh'); } catch (_) {} }
1693
- liveKey = nextKey;
1694
- socket = new WebSocket(live.subscribe_url);
1695
- socket.onmessage = function (message) {
1696
- if (stopped || generation !== socketGeneration) return;
1697
- let frame = null;
1698
- try { frame = JSON.parse(message.data); } catch (_) { return; }
1699
- if (frame && frame.type === 'live_control') {
1700
- schedule(frame.event === 'release_changed', 100);
1701
- }
1702
- };
1703
- let failed = false;
1704
- socket.onopen = function () {
1705
- if (stopped || generation !== socketGeneration) return;
1706
- retryFailures = 0;
1707
- if (retryTimer !== null) { clearTimeout(retryTimer); retryTimer = null; }
1708
- };
1709
- function scheduleRetry() {
1710
- if (stopped || generation !== socketGeneration || retryTimer !== null) return;
1711
- const delay = Math.min(500 * Math.pow(2, retryFailures), 30000);
1712
- retryFailures = Math.min(retryFailures + 1, 6);
1713
- retryTimer = setTimeout(function () {
1714
- retryTimer = null;
1715
- if (!stopped && generation === socketGeneration) refresh(true).catch(scheduleRetry);
1716
- }, delay);
1717
- }
1718
- function retry() {
1719
- if (stopped || generation !== socketGeneration || failed) return;
1720
- failed = true;
1721
- scheduleRetry();
1722
- }
1723
- socket.onclose = retry;
1724
- socket.onerror = retry;
1725
- }
1726
-
1727
- function refresh(reconnect) {
1728
- if (stopped) return Promise.resolve(null);
1729
- if (inFlight) {
1730
- dirty = true;
1731
- reconnectRequested = reconnectRequested || reconnect;
1732
- return inFlight;
1733
- }
1734
- inFlight = Promise.resolve().then(load).then(function (snapshot) {
1735
- if (stopped) return snapshot;
1736
- render(snapshot && snapshot.data, snapshot);
1737
- const live = snapshot && snapshot.live;
1738
- const nextKey = live && String(live.release_id) + ':' + String(live.fingerprint);
1739
- if (reconnect || !socket || nextKey !== liveKey) connect(live);
1740
- return snapshot;
1741
- }).finally(function () {
1742
- inFlight = null;
1743
- if (dirty && !stopped) {
1744
- const reconnectAfter = reconnectRequested;
1745
- dirty = false;
1746
- reconnectRequested = false;
1747
- schedule(reconnectAfter, 0);
1748
- }
1749
- });
1750
- return inFlight;
1751
- }
1752
-
1753
- function schedule(reconnect, delay) {
1754
- if (stopped) return;
1755
- reconnectRequested = reconnectRequested || reconnect;
1756
- if (debounceTimer !== null) return;
1757
- debounceTimer = setTimeout(function () {
1758
- debounceTimer = null;
1759
- const reconnectNow = reconnectRequested;
1760
- reconnectRequested = false;
1761
- refresh(reconnectNow);
1762
- }, delay);
1763
- }
1764
-
1765
- function onVisibility() {
1766
- if (document.visibilityState === 'visible') schedule(false, 0);
1767
- }
1768
- document.addEventListener('visibilitychange', onVisibility);
1769
- const periodic = setInterval(function () { schedule(false, 0); }, 30000);
1770
- refresh(true);
1771
-
1772
- return function stop() {
1773
- stopped = true;
1774
- socketGeneration++;
1775
- if (debounceTimer !== null) clearTimeout(debounceTimer);
1776
- if (retryTimer !== null) clearTimeout(retryTimer);
1777
- clearInterval(periodic);
1778
- document.removeEventListener('visibilitychange', onVisibility);
1779
- if (socket) { try { socket.close(1000, 'stopped'); } catch (_) {} }
1780
- };
1781
- }
1782
- `.trim();
1783
-
1784
1670
  // worker/src/runtime/runtime-console-capture.ts
1785
1671
  var RUNTIME_CONSOLE_MAX_ENTRIES = 200;
1786
1672
  var RUNTIME_CONSOLE_MAX_BYTES = 64 * 1024;
@@ -2355,6 +2241,9 @@ function __sw_parseTraceparent(raw) {
2355
2241
  // sw.rooms -> its platform-private door half (the browser ticket door). Module
2356
2242
  // scope: customer modules cannot name it, and nothing is stored on sw.
2357
2243
  const __sw_roomsDoor = new WeakMap();
2244
+ // sw.db namespace -> its live-list declare (sw.rooms.live delegates to it): the
2245
+ // composed-read brands live in the db closure. Module scope, never on sw.
2246
+ const __sw_liveDoor = new WeakMap();
2358
2247
  const __sw_FS_OPS = { move: 1, copy: 1, restore: 1, stat: 1, versions: 1, diff: 1, glob: 1, search: 1, replace: 1, sign: 1, 'public-url': 1, visibility: 1 };
2359
2248
  const __sw_FS_METHOD_OPS = { GET: 'sw.fs.get', HEAD: 'sw.fs.get', PUT: 'sw.fs.write', DELETE: 'sw.fs.delete', POST: 'sw.fs.post' };
2360
2249
  function __sw_traceOpName(path, method) {
@@ -4753,7 +4642,7 @@ var DB_STRUCTURED_EXECUTION_JS = ` async function __sw_structExec(label, ir
4753
4642
  // delta. A failure cannot undo the committed write; clients repair
4754
4643
  // through their mandatory function refresh policy.
4755
4644
  // Only group keys and (user, group) pairs leave the returned rows.
4756
- liveDelivery = await __sw_publishStructuredLiveInvalidation(ir, mutation, principalId, __sw_liveGroupEvidenceFor(ir, mutation, rows));
4645
+ liveDelivery = await __sw_publishStructuredLiveInvalidation(ir, mutation, principalId, __sw_liveGroupEvidenceFor(ir, mutation, rows), __sw_liveOwnersFor(ir, mutation, rows, principalId));
4757
4646
  }
4758
4647
  const result = {
4759
4648
  data: __sw_structDecodeRows(ir, rows, !!mutation),
@@ -7351,15 +7240,82 @@ var DB_LIVE_INVALIDATION_JS = ` function __sw_liveInvalidation(table) {
7351
7240
  return evidence;
7352
7241
  }
7353
7242
 
7354
- async function __sw_publishStructuredLiveInvalidation(ir, mutation, principalId, evidence) {
7243
+ // Owner lists: the owners (old and new) of the rows a write touched. A
7244
+ // write in the owner's own scope can only touch the writer's rows; any
7245
+ // other write (server, job, another scope) is attributed from its own
7246
+ // returned rows, plus the owner its filter pinned when it moves a row.
7247
+ // Missing evidence is reported, never guessed.
7248
+ function __sw_liveOwnersFor(ir, mutation, rows, principalId) {
7249
+ if (!mutation) return null;
7250
+ const written = (ir.values || []).concat(ir.increments || []).map(function (item) { return String(item.column).toLowerCase(); });
7251
+ const candidates = __sw_liveCandidates(__sw_liveInvalidation(mutation.table), mutation.op, written);
7252
+ const wanted = String(mutation.table || '').toLowerCase();
7253
+ let column = null, mixed = false;
7254
+ for (let i = 0; i < candidates.length; i++) {
7255
+ const view = __sw_liveViewByName(candidates[i]);
7256
+ const deps = (view && view.dependencies) || [];
7257
+ for (let j = 0; j < deps.length; j++) {
7258
+ const dep = deps[j];
7259
+ if (!dep || dep.table !== wanted || !dep.scope || dep.scope.mode !== 'user') continue;
7260
+ const c = String(dep.scope.ownerColumn).toLowerCase();
7261
+ if (column !== null && column !== c) mixed = true;
7262
+ column = c;
7263
+ }
7264
+ }
7265
+ if (column === null) return null;
7266
+ const subjectOf = function (value) {
7267
+ const id = typeof value === 'number' ? value : String(value);
7268
+ return { kind: /^anon_[a-zA-Z0-9_-]{8,}$/.test(String(value)) ? 'visitor' : 'app_user', id: id };
7269
+ };
7270
+ if (ir.scope && ir.scope.mode === 'user' && principalId !== undefined && principalId !== null) {
7271
+ return { owners: [subjectOf(principalId)], complete: !mixed };
7272
+ }
7273
+ const scalar = function (value) {
7274
+ return (typeof value === 'string' && value.length > 0 && value.length <= 200) || (typeof value === 'number' && Number.isSafeInteger(value));
7275
+ };
7276
+ const seen = new Set();
7277
+ const owners = [];
7278
+ let complete = !mixed;
7279
+ const add = function (value) {
7280
+ if (value === null || value === undefined) return;
7281
+ if (!scalar(value)) { complete = false; return; }
7282
+ const key = typeof value + ':' + String(value);
7283
+ if (seen.has(key)) return;
7284
+ seen.add(key);
7285
+ owners.push(subjectOf(value));
7286
+ };
7287
+ const list = rows || [];
7288
+ for (let i = 0; i < list.length; i++) {
7289
+ const row = list[i];
7290
+ let found = false;
7291
+ if (row && typeof row === 'object') {
7292
+ const keys = Object.keys(row);
7293
+ for (let k = 0; k < keys.length; k++) if (keys[k].toLowerCase() === column) { found = true; add(row[keys[k]]); }
7294
+ }
7295
+ if (!found) complete = false;
7296
+ }
7297
+ if (mutation.op === 'update' && written.indexOf(column) !== -1) {
7298
+ let pinned = false;
7299
+ const where = ir.where || [];
7300
+ for (let i = 0; i < where.length; i++) {
7301
+ const p = where[i];
7302
+ if (p && p.op === 'eq' && String(p.column).toLowerCase() === column && scalar(p.value)) { add(p.value); pinned = true; }
7303
+ }
7304
+ if (!pinned) complete = false;
7305
+ }
7306
+ if (owners.length > 100) return { owners: owners.slice(0, 100), complete: false };
7307
+ return { owners: owners, complete: complete };
7308
+ }
7309
+
7310
+ async function __sw_publishStructuredLiveInvalidation(ir, mutation, principalId, evidence, owned) {
7355
7311
  if (isDraftExecution || !env.SW_RELEASE_ID) return null;
7356
7312
  const entry = __sw_liveInvalidation(mutation.table);
7357
7313
  const written = (ir.values || []).concat(ir.increments || []).map(function (item) { return String(item.column).toLowerCase(); });
7358
7314
  const candidates = __sw_liveCandidates(entry, mutation.op, written);
7359
7315
  if (!candidates.length) return null;
7360
7316
  // A group list's table or membership table is attributed by its group
7361
- // evidence, not by the writer; a server-only membership write has no subject.
7362
- const subject = __sw_liveSubject(ir, principalId) || (evidence ? { kind: 'shared', id: null } : null);
7317
+ // evidence and an owner list by its owners, not by the writer.
7318
+ const subject = __sw_liveSubject(ir, principalId) || (evidence || owned ? { kind: 'shared', id: null } : null);
7363
7319
  if (!subject) return { delivery: 'resync_required', reason: 'LIVE_SCOPE_NOT_SUBSCRIBABLE' };
7364
7320
  const body = {
7365
7321
  projectId: projectId,
@@ -7371,17 +7327,32 @@ var DB_LIVE_INVALIDATION_JS = ` function __sw_liveInvalidation(table) {
7371
7327
  };
7372
7328
  if (evidence && evidence.groups) body.groups = evidence.groups;
7373
7329
  if (evidence && evidence.memberships) body.memberships = evidence.memberships;
7374
- try {
7375
- const response = await platformFetch('/v1/live/invalidate', {
7376
- method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
7377
- });
7378
- if (!response.ok) return { delivery: 'resync_required', reason: 'DELIVERY_UNAVAILABLE' };
7379
- if (evidence && !evidence.complete) return { delivery: 'resync_required', reason: 'LIVE_GROUP_EVIDENCE_INCOMPLETE' };
7380
- return { delivery: 'invalidated' };
7381
- } catch (error) {
7382
- console.warn('[SW_LIVE_INVALIDATION] delivery failed: ' + ((error && error.message) || String(error)));
7383
- return { delivery: 'resync_required', reason: 'DELIVERY_UNAVAILABLE' };
7330
+ if (owned) body.owners = owned.owners;
7331
+ // Bounded retry: three attempts over about a second. The write has
7332
+ // already committed; a final failure is logged and reported, never thrown.
7333
+ let lastReason = 'DELIVERY_UNAVAILABLE';
7334
+ for (let attempt = 0; attempt < 3; attempt++) {
7335
+ if (attempt > 0) await new Promise(function (resolve) { setTimeout(resolve, attempt * 300); });
7336
+ try {
7337
+ const response = await platformFetch('/v1/live/invalidate', {
7338
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
7339
+ });
7340
+ if (response.ok) {
7341
+ if (evidence && !evidence.complete) return { delivery: 'resync_required', reason: 'LIVE_GROUP_EVIDENCE_INCOMPLETE' };
7342
+ if (owned && !owned.complete) {
7343
+ console.warn('[SW_LIVE_INVALIDATION] ' + body.table + ': not every owner was named in the write result; those owner lists catch up on their next refresh.');
7344
+ return { delivery: 'resync_required', reason: 'LIVE_OWNER_EVIDENCE_INCOMPLETE' };
7345
+ }
7346
+ return { delivery: 'invalidated' };
7347
+ }
7348
+ lastReason = 'DELIVERY_UNAVAILABLE';
7349
+ if (response.status < 500) { lastReason = 'DELIVERY_REFUSED_' + response.status; break; }
7350
+ } catch (error) {
7351
+ lastReason = 'DELIVERY_UNAVAILABLE';
7352
+ }
7384
7353
  }
7354
+ console.error('[SW_LIVE_INVALIDATION] ' + body.table + ' ' + body.op + ': the change committed, but live lists were not notified (' + lastReason + '). Open lists catch up on reconnect, focus or within 60 s.');
7355
+ return { delivery: 'resync_required', reason: lastReason };
7385
7356
  }
7386
7357
 
7387
7358
  `;
@@ -9320,19 +9291,19 @@ ${DB_RENDER_IR_JS}
9320
9291
  async function __sw_liveDeclare(name, read) {
9321
9292
  const result = await read;
9322
9293
  if (typeof name !== 'string' || !name || arguments.length !== 2) {
9323
- __sw_structThrow('sw.db.live takes exactly (name, read).');
9294
+ __sw_structThrow('sw.rooms.live takes exactly (name, read).');
9324
9295
  }
9325
9296
  const view = __sw_liveViewByName(name);
9326
9297
  if (!view) {
9327
- __sw_structThrow403('LIVE_VIEW_NOT_DECLARED', 'sw.db.live("' + name + '") is not declared by this release. Declare the exact composed read directly in sw.db.live(name, sw.db.from(...)) and deploy.');
9298
+ __sw_structThrow403('LIVE_VIEW_NOT_DECLARED', 'sw.rooms.live("' + name + '") is not declared by this release. Declare the exact composed read directly in sw.rooms.live(name, sw.db.from(...)) and deploy.');
9328
9299
  }
9329
9300
  const brand = result && typeof result === 'object' ? __sw_liveReadBrands.get(result) : null;
9330
9301
  if (!brand || brand.fingerprint !== view.fingerprint) {
9331
- __sw_structThrow403('LIVE_READ_NOT_COMPOSED', 'sw.db.live requires the exact successful sw.db.from result declared for this name. A raw query, cloned result, failed read, or different composed shape cannot mint a subscription.');
9302
+ __sw_structThrow403('LIVE_READ_NOT_COMPOSED', 'sw.rooms.live requires the exact successful sw.db.from result declared for this name. A raw query, cloned result, failed read, or different composed shape cannot mint a subscription.');
9332
9303
  }
9333
9304
  const dependency = view.dependencies && view.dependencies.find(function (item) { return item.kind === 'rows'; });
9334
9305
  if (!dependency || (dependency.scope.mode === 'policy' && !(dependency.scope.policy && (dependency.scope.policy.k === 'g' || __sw_liveRoleChain(dependency.scope.policy) || __sw_liveGroupChain(dependency.scope.policy))))) {
9335
- __sw_structThrow403('LIVE_VIEW_POLICY_SCOPE_UNSUPPORTED', 'sw.db.live does not subscribe policy-scoped tables yet.');
9306
+ __sw_structThrow403('LIVE_VIEW_POLICY_SCOPE_UNSUPPORTED', 'sw.rooms.live does not subscribe policy-scoped tables yet.');
9336
9307
  }
9337
9308
  const subject = __sw_liveSubject(brand.ir, brand.principalId);
9338
9309
  if (!subject) {
@@ -9436,10 +9407,6 @@ ${DB_AGGREGATE_JS}
9436
9407
  // sw.db.delete is a trivial alias of sw.db.remove (both call the same
9437
9408
  // composer). A scope argument fails loudly, never silently.
9438
9409
  from(table, opts, legacyScope) { __sw_structNoScopeArg(legacyScope, 'from'); return __sw_structFrom(table, opts); },
9439
- live(name, read) {
9440
- if (arguments.length !== 2) __sw_structThrow('sw.db.live takes exactly (name, read).');
9441
- return __sw_liveDeclare(name, read);
9442
- },
9443
9410
  count(table, opts, legacyScope) { __sw_structNoScopeArg(legacyScope, 'count'); return __sw_structCount(table, opts); },
9444
9411
  // Composed aggregates (tsk_d3edbf2b) \u2014 count/sum/avg/min/max with
9445
9412
  // group-by over the rows the caller is allowed to read.
@@ -9501,6 +9468,7 @@ ${DB_AGGREGATE_JS}
9501
9468
  };
9502
9469
  })(),
9503
9470
  };
9471
+ __sw_liveDoor.set(__sw_dbNamespace, __sw_liveDeclare);
9504
9472
  return __sw_registerGeneratedOwnerRead(__sw_dbNamespace);`;
9505
9473
 
9506
9474
  // worker/src/runtime/db-raw.ts
@@ -9602,6 +9570,19 @@ var DB_RAW_JS = ` var __sw_rawReadDbInstance = null;
9602
9570
  });
9603
9571
  __sw_pendingBackground.push(pending);
9604
9572
  }
9573
+ // A raw SQL write names no rows the platform can attribute, so it cannot
9574
+ // notify a live list. Say so once per table per request instead of
9575
+ // leaving the list silently stale (structured writes notify).
9576
+ var __sw_rawLiveWarned;
9577
+ function __sw_rawLiveWarn(sql) {
9578
+ const mut = __sw_mutationOf(sql);
9579
+ if (!mut || !__sw_liveInvalidation(mut.table)) return;
9580
+ __sw_rawLiveWarned = __sw_rawLiveWarned || new Set();
9581
+ const table = String(mut.table).toLowerCase();
9582
+ if (__sw_rawLiveWarned.has(table)) return;
9583
+ __sw_rawLiveWarned.add(table);
9584
+ console.warn('[SW_LIVE] A raw SQL ' + mut.op + ' on ' + table + ' does not notify its live lists; open lists catch up on reconnect, focus or within 60 s. Write it with sw.db.insert/update/remove to update them at once.');
9585
+ }
9605
9586
  function __sw_rawResultWrote(results) {
9606
9587
  const list = __sw_arrayIsArray(results) ? results : [results];
9607
9588
  return list.some(function (r) {
@@ -9635,6 +9616,7 @@ var DB_RAW_JS = ` var __sw_rawReadDbInstance = null;
9635
9616
  const rows = r.results || [];
9636
9617
  const mut = __sw_mutationOf(sql);
9637
9618
  if (mut || __sw_rawResultWrote(r)) __sw_publicDataInvalidate();
9619
+ if (mut) __sw_rawLiveWarn(sql);
9638
9620
  if (mut) {
9639
9621
  __sw_deferDbSizeObservation(r);
9640
9622
  }
@@ -9676,6 +9658,7 @@ var DB_RAW_JS = ` var __sw_rawReadDbInstance = null;
9676
9658
  throw error;
9677
9659
  }
9678
9660
  if (batchMutates || __sw_rawResultWrote(results)) __sw_publicDataInvalidate();
9661
+ if (batchMutates) for (const s of statements) __sw_rawLiveWarn(s.sql);
9679
9662
  if (batchMutates) {
9680
9663
  __sw_deferDbSizeObservation(results);
9681
9664
  }
@@ -16011,11 +15994,10 @@ var ROOMS_JS = ` rooms: (function () {
16011
15994
  if (!visitor && issueVisitor && typeof __sw_resolveVisitorIdentity === 'function') {
16012
15995
  // The ticket door gives a first-time anonymous visitor a session when the
16013
15996
  // app declares visitor identity, so the person is the same on reconnect.
16014
- try { await __sw_resolveVisitorIdentity(); visitor = __sw_roomsVisitorToken(); }
16015
- catch (err) { if (!err || err.code !== 'VISITOR_IDENTITY_UNAVAILABLE') throw err; }
15997
+ await __sw_resolveVisitorIdentity(); visitor = __sw_roomsVisitorToken();
16016
15998
  }
16017
15999
  if (visitor) return { 'X-Somewhere-Rooms-Authority': 'visitor', 'X-Sw-Visitor-Session': visitor };
16018
- return { 'X-Somewhere-Rooms-Authority': 'none' };
16000
+ throw __sw_roomsError('AUTH_REQUIRED', 'Rooms require a signed-in or visitor session.', 401);
16019
16001
  }
16020
16002
  async function __sw_roomsCall(path, headers, body) {
16021
16003
  const r = await platformFetch(path, {
@@ -16093,6 +16075,14 @@ var ROOMS_JS = ` rooms: (function () {
16093
16075
  const __sw_rooms = Object.assign(__sw_roomsOps('sw.rooms', '/v1/rooms/', function (label) { return __sw_roomsCallerHeaders(label, false); }), {
16094
16076
  server: Object.freeze(__sw_roomsOps('sw.rooms.server', '/v1/rooms/server/', __sw_roomsServerHeaders)),
16095
16077
  event: __sw_roomsEvent,
16078
+ // A live list: the declared composed read plus a refresh subscription
16079
+ // (worker/src/runtime/db.ts __sw_liveDeclare). Rows stay in the read.
16080
+ live: function live(name, read) {
16081
+ if (arguments.length !== 2) throw __sw_roomsError('VALIDATION_ERROR', 'sw.rooms.live takes exactly (name, read): a declared name and sw.db.from(...).', 400);
16082
+ const declare = __sw_liveDoor.get(sw.db);
16083
+ if (typeof declare !== 'function') throw __sw_roomsError('ROOMS_LIVE_UNAVAILABLE', 'Live lists are unavailable in this runtime.', 500);
16084
+ return declare(name, read);
16085
+ },
16096
16086
  });
16097
16087
  Object.freeze(__sw_rooms);
16098
16088
  // Platform-private: the browser ticket door (/__sw/rooms/ticket) asks for a
@@ -16117,7 +16107,7 @@ var CONTEXT_TAIL_JS = ` };
16117
16107
  // teaches nothing (pfb_3645abbfa717). One thrower, mounted on both the
16118
16108
  // standard sw and the draft proxy, so the answer is identical either way.
16119
16109
  function __sw_realtimeRetired() {
16120
- const err = new Error('sw.realtime is not part of the runtime. For browser live updates, declare the read in a function with sw.db.live(name, sw.db.from(...)) and subscribe with watchLive from /__sw/live/client.js. For durable events and history, write rows with sw.db.');
16110
+ const err = new Error('sw.realtime is not part of the runtime. For browser live updates, declare the read in a function with sw.rooms.live(name, sw.db.from(...)) and subscribe with watchLive from /__sw/rooms/client.js. For durable events and history, write rows with sw.db.');
16121
16111
  err.code = 'REALTIME_RETIRED';
16122
16112
  err.status = 410;
16123
16113
  throw __sw_markExpected(err);
@@ -16226,7 +16216,13 @@ var CONTEXT_TAIL_JS = ` };
16226
16216
  throw err;
16227
16217
  }
16228
16218
  const draftRoomsOps = { act: draftRoomsUnavailable, set: draftRoomsUnavailable, send: draftRoomsUnavailable, get: draftRoomsUnavailable };
16229
- const draftRooms = Object.freeze(Object.assign({}, draftRoomsOps, { server: Object.freeze(Object.assign({}, draftRoomsOps)), event: draftRoomsUnavailable }));
16219
+ // A preview still shows a live list's rows; only the subscription is unavailable.
16220
+ async function draftRoomsLive(name, read) {
16221
+ if (arguments.length !== 2) draftRoomsUnavailable();
16222
+ const result = await read;
16223
+ return Object.assign({}, result, { live: { name: name, state: 'unavailable', reason: 'ROOMS_DRAFT_UNAVAILABLE' } });
16224
+ }
16225
+ const draftRooms = Object.freeze(Object.assign({}, draftRoomsOps, { server: Object.freeze(Object.assign({}, draftRoomsOps)), event: draftRoomsUnavailable, live: draftRoomsLive }));
16230
16226
  const draftSafe = new Set([
16231
16227
  'project_id', 'subdomain', 'tier', 'env', 'request_id', 'params',
16232
16228
  // Groups stays discoverable only to return its draft refusal before transport.
@@ -17687,6 +17683,185 @@ async function __sw_handlePushDoor(request, sw, env) {
17687
17683
  }
17688
17684
  `;
17689
17685
 
17686
+ // worker/src/runtime/live-client.ts
17687
+ var LIVE_CLIENT_MODULE_JS = `
17688
+ const LIVE_PING_FRAME = '{"type":"sw_ping"}';
17689
+ const LIVE_PING_MS = 25000;
17690
+ const LIVE_PONG_TIMEOUT_MS = 10000;
17691
+ const LIVE_SAFETY_REFRESH_MS = 60000;
17692
+ const LIVE_RETRY_LIMIT = 6;
17693
+
17694
+ function liveError(code, message, cause) {
17695
+ const err = new Error(message);
17696
+ err.code = code;
17697
+ if (cause !== undefined) err.cause = cause;
17698
+ return err;
17699
+ }
17700
+
17701
+ export function watchLive(load, render, onError) {
17702
+ if (typeof load !== 'function' || typeof render !== 'function' || (onError !== undefined && typeof onError !== 'function')) {
17703
+ throw new TypeError('watchLive(load, render, onError?): load and render are functions; onError is an optional function');
17704
+ }
17705
+ let stopped = false;
17706
+ let socket = null;
17707
+ let socketGeneration = 0;
17708
+ let liveKey = null;
17709
+ let inFlight = null;
17710
+ let dirty = false;
17711
+ let reconnectRequested = false;
17712
+ let retryTimer = null;
17713
+ let failures = 0;
17714
+ let pingTimer = null;
17715
+ let pongTimer = null;
17716
+ let reconnectTimer = null;
17717
+ let drops = 0;
17718
+
17719
+ function report(err) {
17720
+ const retrying = failures <= LIVE_RETRY_LIMIT;
17721
+ const info = { attempt: failures, retrying: retrying };
17722
+ if (onError) {
17723
+ try { onError(err, info); } catch (handlerError) { console.error('[watchLive] onError threw', handlerError); }
17724
+ } else {
17725
+ console.error('[watchLive] ' + (err && err.code ? err.code + ': ' : '') + ((err && err.message) || String(err)) + (retrying ? ' (retrying)' : ' (gave up; the list refreshes again on reconnect, focus or within 60 s)'), err);
17726
+ }
17727
+ }
17728
+
17729
+ function scheduleRetry(reconnect) {
17730
+ if (stopped || retryTimer !== null || failures > LIVE_RETRY_LIMIT) return;
17731
+ const delay = Math.min(500 * Math.pow(2, failures - 1), 15000);
17732
+ retryTimer = setTimeout(function () { retryTimer = null; refresh(reconnect); }, delay);
17733
+ }
17734
+
17735
+ function fail(err, reconnect) {
17736
+ failures += 1;
17737
+ report(err);
17738
+ scheduleRetry(reconnect);
17739
+ }
17740
+
17741
+ function stopPing() {
17742
+ if (pingTimer !== null) { clearInterval(pingTimer); pingTimer = null; }
17743
+ if (pongTimer !== null) { clearTimeout(pongTimer); pongTimer = null; }
17744
+ }
17745
+
17746
+ function connect(live) {
17747
+ const nextKey = String(live.release_id) + ':' + String(live.fingerprint);
17748
+ const generation = ++socketGeneration;
17749
+ stopPing();
17750
+ if (socket) { try { socket.close(1000, 'refresh'); } catch (_) {} }
17751
+ liveKey = nextKey;
17752
+ let ws;
17753
+ try { ws = new WebSocket(live.subscribe_url); } catch (err) { socket = null; fail(liveError('LIVE_CONNECT_FAILED', 'The live connection could not be opened.', err), true); return; }
17754
+ socket = ws;
17755
+ let closed = false;
17756
+ ws.onmessage = function (message) {
17757
+ if (stopped || generation !== socketGeneration) return;
17758
+ if (pongTimer !== null) { clearTimeout(pongTimer); pongTimer = null; }
17759
+ drops = 0;
17760
+ let frame = null;
17761
+ try { frame = JSON.parse(message.data); } catch (_) { return; }
17762
+ if (!frame || frame.type !== 'live_control') return;
17763
+ // resync_required: rows changed, or this socket just went live.
17764
+ // release_changed / access_revoked / reauthorize_required: the socket
17765
+ // closes next; the close handler reconnects through a fresh load.
17766
+ if (frame.event === 'resync_required') refresh(false);
17767
+ };
17768
+ ws.onopen = function () {
17769
+ if (stopped || generation !== socketGeneration) return;
17770
+ pingTimer = setInterval(function () {
17771
+ if (stopped || generation !== socketGeneration) return;
17772
+ try { ws.send(LIVE_PING_FRAME); } catch (_) { return; }
17773
+ if (pongTimer === null) pongTimer = setTimeout(function () {
17774
+ pongTimer = null;
17775
+ if (generation === socketGeneration) { try { ws.close(4000, 'no_pong'); } catch (_) {} onClose(); }
17776
+ }, LIVE_PONG_TIMEOUT_MS);
17777
+ }, LIVE_PING_MS);
17778
+ };
17779
+ function onClose() {
17780
+ if (closed || stopped || generation !== socketGeneration) return;
17781
+ closed = true;
17782
+ stopPing();
17783
+ // An error may leave the socket half-open; close it explicitly so no stale
17784
+ // connection lingers behind the replacement.
17785
+ try { ws.close(1000, 'replaced'); } catch (_) {}
17786
+ socket = null;
17787
+ liveKey = null;
17788
+ // A fresh load re-checks access and mints a new ticket; it also shows
17789
+ // anything that changed while the socket was down. The first drop
17790
+ // reconnects at once; repeated drops back off and are reported.
17791
+ drops += 1;
17792
+ if (drops > 3) report(liveError('LIVE_DISCONNECTED', 'The live connection keeps closing; reconnecting.'));
17793
+ if (reconnectTimer !== null) return;
17794
+ const delay = drops === 1 ? 0 : Math.min(500 * Math.pow(2, drops - 2), 15000);
17795
+ reconnectTimer = setTimeout(function () { reconnectTimer = null; refresh(true); }, delay);
17796
+ }
17797
+ ws.onclose = onClose;
17798
+ ws.onerror = onClose;
17799
+ }
17800
+
17801
+ function refresh(reconnect) {
17802
+ if (stopped) return Promise.resolve(null);
17803
+ if (inFlight) {
17804
+ dirty = true;
17805
+ reconnectRequested = reconnectRequested || !!reconnect;
17806
+ return inFlight;
17807
+ }
17808
+ if (retryTimer !== null) { clearTimeout(retryTimer); retryTimer = null; }
17809
+ if (reconnect && reconnectTimer !== null) { clearTimeout(reconnectTimer); reconnectTimer = null; }
17810
+ let snapshot = null;
17811
+ inFlight = Promise.resolve().then(load).then(function (value) {
17812
+ snapshot = value;
17813
+ if (stopped) return;
17814
+ render(snapshot && snapshot.data, snapshot);
17815
+ const live = snapshot && snapshot.live;
17816
+ if (!live || live.state !== 'ready' || typeof live.subscribe_url !== 'string') {
17817
+ // The rows rendered, but nothing will tell this page about changes.
17818
+ throw liveError((live && live.reason) || 'LIVE_NOT_DECLARED',
17819
+ live ? 'The list loaded, but it could not subscribe to changes (' + (live.reason || live.state) + ').'
17820
+ : 'load() must return the JSON of a function that returns sw.rooms.live(name, read).');
17821
+ }
17822
+ failures = 0;
17823
+ const nextKey = String(live.release_id) + ':' + String(live.fingerprint);
17824
+ if (reconnect || !socket || nextKey !== liveKey) connect(live);
17825
+ }).catch(function (err) {
17826
+ if (!stopped) fail(err && err.code ? err : liveError('LIVE_REFRESH_FAILED', 'Refreshing the live list failed: ' + ((err && err.message) || String(err)), err), reconnect || !socket);
17827
+ }).then(function () {
17828
+ inFlight = null;
17829
+ if (dirty && !stopped) {
17830
+ const again = reconnectRequested;
17831
+ dirty = false;
17832
+ reconnectRequested = false;
17833
+ refresh(again);
17834
+ }
17835
+ return snapshot;
17836
+ });
17837
+ return inFlight;
17838
+ }
17839
+
17840
+ function repair() {
17841
+ if (stopped) return;
17842
+ failures = Math.min(failures, LIVE_RETRY_LIMIT);
17843
+ refresh(!socket && reconnectTimer === null);
17844
+ }
17845
+ function onVisibility() { if (document.visibilityState === 'visible') repair(); }
17846
+ document.addEventListener('visibilitychange', onVisibility);
17847
+ if (typeof window !== 'undefined') window.addEventListener('online', repair);
17848
+ const safety = setInterval(function () { if (document.visibilityState !== 'hidden') repair(); }, LIVE_SAFETY_REFRESH_MS);
17849
+ refresh(true);
17850
+
17851
+ return function stop() {
17852
+ stopped = true;
17853
+ socketGeneration++;
17854
+ stopPing();
17855
+ if (retryTimer !== null) clearTimeout(retryTimer);
17856
+ if (reconnectTimer !== null) clearTimeout(reconnectTimer);
17857
+ clearInterval(safety);
17858
+ document.removeEventListener('visibilitychange', onVisibility);
17859
+ if (typeof window !== 'undefined') window.removeEventListener('online', repair);
17860
+ if (socket) { try { socket.close(1000, 'stopped'); } catch (_) {} }
17861
+ };
17862
+ }
17863
+ `.trim();
17864
+
17690
17865
  // worker/src/runtime/rooms-client.ts
17691
17866
  var ROOMS_CLIENT_MODULE_JS = `
17692
17867
  const TICKET_PATH = '/__sw/rooms/ticket';
@@ -18082,7 +18257,7 @@ export async function joinRoom(table, id) {
18082
18257
  if (!(typeof id === 'string' && id) && !Number.isSafeInteger(id)) throw new TypeError('joinRoom(table, id): id is the row id');
18083
18258
  return new Room(table, id)._start();
18084
18259
  }
18085
- `.trim();
18260
+ `.trim() + "\n\n" + LIVE_CLIENT_MODULE_JS;
18086
18261
  var ROOMS_DOOR_RUNTIME_JS = String.raw`
18087
18262
  const __SW_ROOMS_CLIENT_MODULE = ${JSON.stringify(ROOMS_CLIENT_MODULE_JS)};
18088
18263
  function __sw_roomsDoorMatch(url) {