@craftainer/crud-sdk 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,6 +25,37 @@ function tanstackCachePolicy(resource, overrides = {}) {
25
25
  });
26
26
  }
27
27
  //#endregion
28
+ //#region src/reset-once.ts
29
+ const ledger = /* @__PURE__ */ new WeakMap();
30
+ /**
31
+ * Runs `reset` unless `owner`/`key` was already reset on `connection`; resolves
32
+ * when that reset is done, whoever started it. A failed reset is forgotten so
33
+ * a later subscriber can retry.
34
+ */
35
+ function resetOnce(connection, owner, key, reset) {
36
+ let owners = ledger.get(connection);
37
+ if (owners === void 0) {
38
+ owners = /* @__PURE__ */ new WeakMap();
39
+ ledger.set(connection, owners);
40
+ }
41
+ let keys = owners.get(owner);
42
+ if (keys === void 0) {
43
+ keys = /* @__PURE__ */ new Map();
44
+ owners.set(owner, keys);
45
+ }
46
+ const done = keys.get(key);
47
+ if (done !== void 0) return done;
48
+ const started = (async () => {
49
+ await reset();
50
+ })();
51
+ keys.set(key, started);
52
+ const forget = keys;
53
+ started.catch(() => {
54
+ forget.delete(key);
55
+ });
56
+ return started;
57
+ }
58
+ //#endregion
28
59
  //#region node_modules/.pnpm/eventsource-parser@4.1.2/node_modules/eventsource-parser/dist/errors.js
29
60
  /**
30
61
  * Error thrown when encountering an issue during parsing.
@@ -403,17 +434,67 @@ function isPotentialField(line, field) {
403
434
  * covered even without replay. A stream silent for three keep-alive
404
435
  * intervals is dead and is reconnected with exponential backoff and jitter.
405
436
  * Events invalidate; they never apply snapshots.
437
+ *
438
+ * A hub is shared by every subscriber of the same (fetch, url) and the first
439
+ * subscriber's options win: the keep-alive, resume parameter, replay mode and
440
+ * resource label of later subscribers are ignored. In development
441
+ * (`process.env.NODE_ENV !== "production"`) a later subscriber whose options
442
+ * differ gets a `console.warn` naming the URL and the fields.
443
+ *
444
+ * Every connection has an identity (an opaque {@link EventConnection}) that
445
+ * the hub passes to `onReset` (for the connect reset) and to `onStatus(true)`.
446
+ * A subscriber that joins an already connected hub, or during the handshake's
447
+ * reset fan-out, gets no connect reset; it sees `onStatus(true)` with a
448
+ * connection it was never reset for and resets itself (see `invalidateOnEvents`
449
+ * and `bridgeEvents`).
406
450
  */
407
451
  const BACKOFF_START_MS = 1e3;
408
452
  const BACKOFF_MAX_MS = 3e4;
409
453
  const DEFAULT_KEEPALIVE_S = 15;
410
454
  const DEAD_AFTER_KEEPALIVES = 3;
455
+ /** `setTimeout` clamps a longer delay to 1 ms, which would declare the stream dead at once. */
456
+ const MAX_TIMER_MS = 2 ** 31 - 1;
411
457
  const ACTIONS = /* @__PURE__ */ new Set([
412
458
  "create",
413
459
  "update",
414
460
  "delete",
415
461
  "restore"
416
462
  ]);
463
+ /**
464
+ * The keep-alive interval in seconds. Zero, negative and non-finite values
465
+ * are invalid and treated as unset, so the default applies (as the WHATWG SSE
466
+ * spec ignores an invalid `retry` value instead of acting on it); otherwise a
467
+ * dead-stream deadline of 0 would reconnect forever.
468
+ */
469
+ function keepaliveSeconds(events) {
470
+ const value = events.keepalive_seconds;
471
+ return value !== void 0 && Number.isFinite(value) && value > 0 ? value : DEFAULT_KEEPALIVE_S;
472
+ }
473
+ /** The `events` fields that change what a hub does, with defaults applied. */
474
+ function hubSettings(events) {
475
+ return {
476
+ resource: events.resource,
477
+ resume_param: events.resume_param ?? "subscriber_id",
478
+ replay: events.replay,
479
+ keepalive_seconds: keepaliveSeconds(events)
480
+ };
481
+ }
482
+ /** `process.env.NODE_ENV` is replaced by bundlers; without it (no `process`) assume development. */
483
+ function inDevelopment() {
484
+ try {
485
+ return process.env.NODE_ENV !== "production";
486
+ } catch {
487
+ return true;
488
+ }
489
+ }
490
+ /** Warns, in development, that a later subscriber's options differ from the hub's. */
491
+ function warnOnDifferingOptions(hub, later) {
492
+ if (!inDevelopment()) return;
493
+ const first = hubSettings(hub.events);
494
+ const next = hubSettings(later.events);
495
+ const differing = Object.keys(first).filter((key) => first[key] !== next[key]);
496
+ if (differing.length > 0) console.warn(`crud-sdk: the event hub for ${hub.url} was opened with other events options; the first subscriber's win and these are ignored: ${differing.join(", ")}`);
497
+ }
417
498
  const registry = /* @__PURE__ */ new WeakMap();
418
499
  function sleep(ms, signal) {
419
500
  return new Promise((resolve) => {
@@ -436,23 +517,25 @@ var Hub = class {
436
517
  onEmpty;
437
518
  controller;
438
519
  connected = false;
520
+ connection;
439
521
  subscriberId;
440
522
  attempt = 0;
441
523
  constructor(options, onEmpty) {
442
524
  this.options = options;
443
525
  this.onEmpty = onEmpty;
444
526
  }
445
- subscribe(handlers) {
527
+ subscribe(handlers, requested) {
528
+ if (this.handlers.size > 0) warnOnDifferingOptions(this.options, requested);
446
529
  const entry = {
447
530
  onEvent: (event) => handlers.onEvent(event),
448
- onReset: () => handlers.onReset?.(),
449
- onStatus: (connected) => handlers.onStatus?.(connected)
531
+ onReset: (connection) => handlers.onReset?.(connection),
532
+ onStatus: (connected, connection) => handlers.onStatus?.(connected, connection)
450
533
  };
451
534
  this.handlers.add(entry);
452
535
  if (this.controller === void 0) {
453
536
  this.controller = new AbortController();
454
537
  this.run(this.controller.signal);
455
- } else if (this.connected) this.guard(() => entry.onStatus?.(true));
538
+ } else if (this.connected) this.guard(() => entry.onStatus?.(true, this.connection));
456
539
  return () => {
457
540
  if (!this.handlers.delete(entry)) return;
458
541
  this.guard(() => entry.onStatus?.(false));
@@ -469,12 +552,13 @@ var Hub = class {
469
552
  } catch {}
470
553
  }
471
554
  async fan(call) {
472
- for (const handlers of Array.from(this.handlers)) await this.guard(() => call(handlers));
555
+ for (const handlers of Array.from(this.handlers)) if (this.handlers.has(handlers)) await this.guard(() => call(handlers));
473
556
  }
474
- async setConnected(connected) {
557
+ async setConnected(connected, connection) {
475
558
  if (this.connected === connected) return;
476
559
  this.connected = connected;
477
- await this.fan((handlers) => handlers.onStatus?.(connected));
560
+ this.connection = connected ? connection : void 0;
561
+ await this.fan((handlers) => handlers.onStatus?.(connected, connection));
478
562
  }
479
563
  backoff() {
480
564
  const base = Math.min(BACKOFF_START_MS * 2 ** this.attempt, BACKOFF_MAX_MS);
@@ -503,7 +587,7 @@ var Hub = class {
503
587
  return `${url}${url.includes("?") ? "&" : "?"}${encodeURIComponent(param)}=${encodeURIComponent(this.subscriberId)}`;
504
588
  }
505
589
  async readOnce(signal) {
506
- const deadMs = (this.options.events.keepalive_seconds ?? DEFAULT_KEEPALIVE_S) * DEAD_AFTER_KEEPALIVES * 1e3;
590
+ const deadMs = Math.min(keepaliveSeconds(this.options.events) * DEAD_AFTER_KEEPALIVES * 1e3, MAX_TIMER_MS);
507
591
  const conn = new AbortController();
508
592
  const abortConn = () => {
509
593
  conn.abort();
@@ -530,9 +614,10 @@ var Hub = class {
530
614
  for (;;) {
531
615
  const { done, value } = await reader.read();
532
616
  if (done) return;
533
- arm();
534
617
  parser.feed(decoder.decode(value, { stream: true }));
618
+ clearTimeout(timer);
535
619
  for (const message of pending.splice(0)) await this.handle(message);
620
+ arm();
536
621
  }
537
622
  } finally {
538
623
  clearTimeout(timer);
@@ -552,8 +637,13 @@ var Hub = class {
552
637
  if ("subscriber_id" in record) {
553
638
  this.subscriberId = String(record["subscriber_id"]);
554
639
  this.attempt = 0;
555
- await this.fan((handlers) => handlers.onReset?.());
556
- await this.setConnected(true);
640
+ const connection = {};
641
+ const present = new Set(this.handlers);
642
+ await this.fan((handlers) => handlers.onReset?.(connection));
643
+ if (this.connected) {
644
+ this.connection = connection;
645
+ for (const handlers of Array.from(this.handlers)) if (!present.has(handlers)) await this.guard(() => handlers.onStatus?.(true, connection));
646
+ } else await this.setConnected(true, connection);
557
647
  return;
558
648
  }
559
649
  if (record["resource"] !== this.options.events.resource) return;
@@ -577,6 +667,12 @@ var Hub = class {
577
667
  /**
578
668
  * The shared hub for `(fetch, url)`: the first subscriber opens the stream,
579
669
  * the last one aborts it. A later subscribe after that opens a fresh one.
670
+ *
671
+ * The first subscriber's `events` options win while the hub lives. A later
672
+ * subscriber whose `resource`, `resume_param`, `replay` or `keepalive_seconds`
673
+ * differ is served by the same stream with the first's values, and in
674
+ * development (`process.env.NODE_ENV !== "production"`) gets a `console.warn`
675
+ * naming the URL and the differing fields.
580
676
  */
581
677
  function getEventHub(options) {
582
678
  return { subscribe(handlers) {
@@ -593,7 +689,7 @@ function getEventHub(options) {
593
689
  });
594
690
  byUrl.set(options.url, hub);
595
691
  }
596
- return hub.subscribe(handlers);
692
+ return hub.subscribe(handlers, options);
597
693
  } };
598
694
  }
599
695
  /**
@@ -611,6 +707,6 @@ function subscribeEvents(options) {
611
707
  };
612
708
  }
613
709
  //#endregion
614
- export { tanstackCachePolicy as i, subscribeEvents as n, cachePolicyFromManifest as r, getEventHub as t };
710
+ export { tanstackCachePolicy as a, cachePolicyFromManifest as i, subscribeEvents as n, resetOnce as r, getEventHub as t };
615
711
 
616
- //# sourceMappingURL=events-Cqj9Rbon.mjs.map
712
+ //# sourceMappingURL=events-Dfz-rzC8.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events-Dfz-rzC8.mjs","names":[],"sources":["../src/cache/policy.ts","../src/reset-once.ts","../node_modules/.pnpm/eventsource-parser@4.1.2/node_modules/eventsource-parser/dist/errors.js","../node_modules/.pnpm/eventsource-parser@4.1.2/node_modules/eventsource-parser/dist/parse.js","../src/events.ts"],"sourcesContent":["/** Per-resource cache policy, defaulted from the manifest `cache` hints. */\n\n/**\n * How one resource is cached. Times are seconds. `maxAge` and\n * `staleWhileRevalidate` only take effect while the resource's SSE stream is\n * running; without it every read revalidates. `statsTtl` bounds the staleness\n * of `stats`/`predict` on its own, as the server caches those bodies for the\n * same time. `revalidateOnly` means no fresh window and no\n * stale-while-revalidate.\n */\nexport interface CachePolicy {\n readonly enabled: boolean;\n readonly maxAge: number;\n readonly statsTtl: number;\n readonly staleWhileRevalidate: number;\n readonly etag: boolean;\n readonly revalidateOnly: boolean;\n}\n\n/** The manifest resource members a policy reads (I1); everything else is ignored. */\nexport interface ManifestCacheHints {\n readonly cache?: {\n readonly max_age?: unknown;\n readonly stats_ttl?: unknown;\n readonly stale_while_revalidate?: unknown;\n readonly etag?: unknown;\n readonly revalidate_only?: unknown;\n } | null;\n}\n\nfunction seconds(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value)\n ? Math.max(value, 0)\n : 0;\n}\n\n/** Build a policy from a manifest resource object; `overrides` win over the hints. */\nexport function cachePolicyFromManifest(\n resource: ManifestCacheHints,\n overrides: Partial<CachePolicy> = {},\n): CachePolicy {\n const hints = resource.cache ?? {};\n return {\n enabled: overrides.enabled ?? true,\n maxAge: overrides.maxAge ?? seconds(hints.max_age),\n statsTtl: overrides.statsTtl ?? seconds(hints.stats_ttl),\n staleWhileRevalidate:\n overrides.staleWhileRevalidate ?? seconds(hints.stale_while_revalidate),\n etag: overrides.etag ?? hints.etag !== false,\n revalidateOnly: overrides.revalidateOnly ?? hints.revalidate_only === true,\n };\n}\n\n/**\n * The policy to use under TanStack Query: its `staleTime` decides freshness,\n * so the SDK cache only revalidates (ETag/304) unless told otherwise.\n */\nexport function tanstackCachePolicy(\n resource: ManifestCacheHints,\n overrides: Partial<CachePolicy> = {},\n): CachePolicy {\n return cachePolicyFromManifest(resource, {\n revalidateOnly: true,\n ...overrides,\n });\n}\n","/**\n * \"Reset once per target per connection\" (ADR 0002). A subscriber that is told\n * about a connection runs its reset through here; a second subscriber with the\n * same target (the same cache, or the same QueryClient, and resource) on the\n * same connection joins the first one's reset instead of running another.\n */\nimport type { EventConnection } from \"./events.ts\";\n\nconst ledger = new WeakMap<\n EventConnection,\n WeakMap<object, Map<string, Promise<void>>>\n>();\n\n/**\n * Runs `reset` unless `owner`/`key` was already reset on `connection`; resolves\n * when that reset is done, whoever started it. A failed reset is forgotten so\n * a later subscriber can retry.\n */\nexport function resetOnce(\n connection: EventConnection,\n owner: object,\n key: string,\n reset: () => Promise<void> | void,\n): Promise<void> {\n let owners = ledger.get(connection);\n if (owners === undefined) {\n owners = new WeakMap();\n ledger.set(connection, owners);\n }\n let keys = owners.get(owner);\n if (keys === undefined) {\n keys = new Map();\n owners.set(owner, keys);\n }\n const done = keys.get(key);\n if (done !== undefined) {\n return done;\n }\n const started = (async (): Promise<void> => {\n await reset();\n })();\n keys.set(key, started);\n const forget = keys;\n started.catch(() => {\n forget.delete(key);\n });\n return started;\n}\n","/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n constructor(message, options) {\n super(message);\n this.name = 'ParseError';\n this.type = options.type;\n this.field = options.field;\n this.value = options.value;\n this.line = options.line;\n }\n}\n//# sourceMappingURL=errors.js.map","/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport { ParseError } from './errors.js';\n// ASCII codes used in the hot parsing paths.\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nconst MAX_FIELD_PREFIX_LENGTH = 6;\n/**\n * Creates a new EventSource parser.\n *\n * @param config - Parser configuration. Accepts callbacks (see {@link ParserCallbacks})\n * and options like `maxBufferSize` (see {@link ParserConfig}).\n *\n * @returns A new EventSource parser, with `feed` and `reset` methods.\n * @public\n */\nexport function createParser(config) {\n if (typeof config === 'function') {\n throw new TypeError('`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?');\n }\n const { maxBufferSize, onComment, onError, onEvent, onId, onRetry } = config;\n // Trailing bytes from prior `feed()` calls that did not yet form a complete line.\n // Stored as an array of fragments and only joined when a line terminator arrives.\n // Concatenating per-feed (`prefix + chunk`) is O(N²) when a single SSE line spans\n // many chunks (e.g. a large `data:` payload streamed in tiny slices, or an MCP-style\n // server that emits one giant content block). Buffering as fragments + joining once\n // makes the same workload linear.\n const pendingFragments = [];\n // Running total of `pendingFragments` lengths, kept in sync with the array so the\n // `maxBufferSize` check doesn't have to walk the fragment list on every feed.\n let pendingFragmentsLength = 0;\n // Empty or partial leading BOM; undefined once the BOM check is complete.\n let bomPrefix = '';\n let id;\n let data = '';\n let dataLines = 0;\n let eventType;\n // Set after a `maxBufferSize` overflow. Once tripped, `feed()` throws until\n // `reset()` is called — see the comment on `maxBufferSize` in `ParserConfig`.\n let terminated = false;\n let skippingLine = false;\n // Set when a line (parsed or discarded) was terminated by a trailing `\\r` at the very\n // end of a chunk. That `\\r` is ambiguous: it may be a bare-CR terminator or the first\n // half of a `\\r\\n` whose `\\n` lands in the next chunk. The line itself is complete\n // either way, but we must remember to swallow a single leading `\\n` from the next\n // chunk so the pair is treated as one terminator rather than a blank line (which\n // would dispatch an event prematurely).\n let skipNextLineFeed = false;\n /**\n * Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do\n * not yet form a complete line are held back and prepended to the next chunk,\n * so callers can pass arbitrary slices of the stream without worrying about\n * line boundaries.\n *\n * Per the SSE spec, one leading UTF-8 BOM is stripped before parsing,\n * even when split across chunks. This handles both the raw 3-byte form (0xEF 0xBB\n * 0xBF) and a single decoded U+FEFF, so a leading BOM is ignored regardless of\n * how the caller decoded the bytes.\n *\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream\n */\n function feed(chunk) {\n if (terminated) {\n throw new Error('Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.');\n }\n if (bomPrefix !== undefined) {\n chunk = bomPrefix + chunk;\n // Wait only while the input could still be a raw BOM. Empty chunks must\n // not finish the check, and a mismatched prefix must remain ordinary input.\n if (chunk === '' || chunk === '\\xEF' || chunk === '\\xEF\\xBB') {\n bomPrefix = chunk;\n return;\n }\n bomPrefix = undefined;\n // Strip exactly one leading BOM, in decoded or raw byte-valued form.\n chunk = chunk.replace(/^(?:\\uFEFF|\\xEF\\xBB\\xBF)/, '');\n }\n // Rare resume states from a prior chunk boundary: a pending `\\r\\n` split or a\n // line being discarded. Single combined check keeps the hot path to one branch;\n // the actual handling lives out-of-line in `resumeAfterSkip`.\n if (skippingLine || skipNextLineFeed) {\n chunk = resumeAfterSkip(chunk);\n if (!chunk) {\n return;\n }\n }\n // Hot path: no buffered prefix from a prior partial line. Hand the chunk\n // straight to `processLines`, exactly like the original implementation.\n // Zero new work in the common case (every chunk ends with `\\n\\n`).\n if (!pendingFragments.length) {\n const trailing = processLines(chunk);\n if (trailing !== '') {\n storeTrailing(trailing);\n }\n checkForBufferOverflow();\n return;\n }\n // We have a buffered prefix. If this chunk also has no terminator, append\n // to the buffer without concatenating — that's the O(N²) trap we're\n // avoiding (large single `data:` payload split across many tiny chunks).\n if (chunk.indexOf('\\n') === -1 && chunk.indexOf('\\r') === -1) {\n if (pendingFragmentsLength < MAX_FIELD_PREFIX_LENGTH) {\n const head = pendingFragments.join('') +\n chunk.slice(0, MAX_FIELD_PREFIX_LENGTH - pendingFragmentsLength);\n if (!shouldBufferTrailing(head)) {\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n skippingLine = true;\n return;\n }\n }\n pendingFragments.push(chunk);\n pendingFragmentsLength += chunk.length;\n checkForBufferOverflow();\n return;\n }\n // Terminator arrived. Join the accumulated fragments + this chunk once,\n // process, and buffer any new trailing partial line.\n pendingFragments.push(chunk);\n const input = pendingFragments.join('');\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n storeTrailing(processLines(input));\n checkForBufferOverflow();\n }\n // Out-of-line handler for the rare post-boundary states. `skipNextLineFeed` means a\n // line (parsed or discarded) ended with a trailing `\\r` at the previous chunk boundary,\n // so a single leading `\\n` must be swallowed to consume a split `\\r\\n` as one terminator.\n // `skippingLine` means we are discarding an invalid line until its terminator arrives.\n // The two states are mutually exclusive. Returns the remaining chunk to parse ('' if\n // this chunk was fully consumed).\n function resumeAfterSkip(chunk) {\n if (chunk.length === 0) {\n return chunk;\n }\n if (skipNextLineFeed) {\n skipNextLineFeed = false;\n return chunk.charCodeAt(0) === LF ? chunk.slice(1) : chunk;\n }\n const crIndex = chunk.indexOf('\\r');\n const lfIndex = chunk.indexOf('\\n');\n const lineEnd = crIndex === -1 ? lfIndex : lfIndex === -1 ? crIndex : crIndex < lfIndex ? crIndex : lfIndex;\n if (lineEnd === -1) {\n return '';\n }\n // Trailing `\\r` at the very end of the chunk: defer the CRLF/CR decision to the\n // next chunk (see `skipNextLineFeed`) rather than greedily consuming just the `\\r`.\n if (lineEnd === chunk.length - 1 && chunk.charCodeAt(lineEnd) === CR) {\n skippingLine = false;\n skipNextLineFeed = true;\n return '';\n }\n skippingLine = false;\n return chunk.slice(lineEnd + (chunk.charCodeAt(lineEnd) === CR && chunk.charCodeAt(lineEnd + 1) === LF ? 2 : 1));\n }\n function storeTrailing(trailing) {\n if (!trailing)\n return;\n // A trailing that ends with `\\r` is not a partial line: the `\\r` terminates it,\n // and only the CRLF-vs-CR ambiguity remains (the matching `\\n` may start the next\n // chunk). Parse the completed line now — buffering it could grow unbounded through\n // the no-terminator append path, and discarding it would eat the terminator and\n // make skip mode swallow the next line.\n if (trailing.charCodeAt(trailing.length - 1) === CR) {\n parseLine(trailing, 0, trailing.length - 1);\n if (checkForBufferOverflow())\n return;\n skipNextLineFeed = true;\n return;\n }\n if (shouldBufferTrailing(trailing)) {\n pendingFragments.push(trailing);\n pendingFragmentsLength = trailing.length;\n return;\n }\n skippingLine = true;\n }\n function shouldBufferTrailing(trailing) {\n const firstCharCode = trailing.charCodeAt(0);\n return ((firstCharCode === 58 && !!onComment) ||\n (firstCharCode === 100 && isPotentialField(trailing, 'data')) ||\n (firstCharCode === 101 && isPotentialField(trailing, 'event')) ||\n (firstCharCode === 105 && isPotentialField(trailing, 'id')) ||\n (firstCharCode === 114 && isPotentialField(trailing, 'retry')));\n }\n // Returns true when parsing must stop for the current chunk (the parser was already\n // terminated or has just overflowed), and false when processing can continue.\n function checkForBufferOverflow() {\n if (terminated)\n return true;\n if (maxBufferSize === undefined)\n return false;\n if (pendingFragmentsLength + data.length <= maxBufferSize)\n return false;\n terminated = true;\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n skippingLine = false;\n skipNextLineFeed = false;\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n type: 'max-buffer-size-exceeded',\n }));\n return true;\n }\n /**\n * Splits `chunk` into SSE lines and dispatches each to the appropriate handler.\n * Returns any trailing bytes that did not terminate with a line break, so the\n * caller can prepend them to the next chunk.\n *\n * The SSE spec permits three line terminators: `\\n`, `\\r`, and `\\r\\n`. Real-world\n * streams almost always use plain `\\n`, so we take a fast path when no `\\r` is\n * present in the chunk. The slow path is spec-correct but does more work per line.\n */\n function processLines(chunk) {\n let searchIndex = 0;\n // Fast path: LF-only chunk (the common case for typical SSE servers).\n // We can scan forward with a single `indexOf('\\n')` per line and inline\n // the hot-path branches for `data:` and `event:` without the CR bookkeeping\n // the slow path needs.\n if (chunk.indexOf('\\r') === -1) {\n let lfIndex = chunk.indexOf('\\n', searchIndex);\n while (lfIndex !== -1) {\n // Blank line: end-of-event marker. Dispatch the accumulated event (if any)\n // and reset the buffered fields. This is hoisted out of `parseLine` because\n // it's the single most common line shape after `data:` lines.\n if (searchIndex === lfIndex) {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n if (dataLines > 0) {\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({ id, event: eventType, data });\n }\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n searchIndex = lfIndex + 1;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n continue;\n }\n const firstCharCode = chunk.charCodeAt(searchIndex);\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n // `data:` line — append the value to the event's data buffer.\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5;\n const value = chunk.slice(valueStart, lfIndex);\n // Fast path within a fast path: if this is the first data line AND the\n // next char is another LF (i.e. `data:foo\\n\\n`), dispatch immediately\n // without ever writing to the `data` buffer. This is the shape of a\n // typical single-line SSE event (ChatGPT-style streams, etc.) and is\n // hot enough to be worth the duplication.\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({ id, event: eventType, data: value });\n id = undefined;\n data = '';\n eventType = undefined;\n searchIndex = lfIndex + 2;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n continue;\n }\n // Multi-line data: concatenate with newline separator per spec.\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n }\n else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {\n // `event:` line — set the event type for the next dispatch. Per spec,\n // an empty value resets `event type` to its default (undefined here).\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || undefined;\n }\n else {\n // Everything else: `id:`, `retry:`, comment lines (`:` prefix), unknown\n // fields, or malformed lines. These are rarer and go through the full\n // per-line parser, which handles the SSE field grammar in detail.\n parseLine(chunk, searchIndex, lfIndex);\n }\n if (checkForBufferOverflow())\n return '';\n searchIndex = lfIndex + 1;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n }\n return chunk.slice(searchIndex);\n }\n // Slow path: the chunk contains at least one `\\r`, so lines may be terminated\n // by `\\r`, `\\n`, or `\\r\\n`. We locate the next terminator by looking at both\n // the nearest `\\r` and `\\n` and picking whichever comes first.\n while (searchIndex < chunk.length) {\n const crIndex = chunk.indexOf('\\r', searchIndex);\n const lfIndex = chunk.indexOf('\\n', searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1) {\n lineEnd = crIndex < lfIndex ? crIndex : lfIndex;\n }\n else if (crIndex !== -1) {\n // A trailing `\\r` at the very end of the chunk is ambiguous: it could be\n // a bare-CR terminator, or the first half of a `\\r\\n` whose `\\n` arrives\n // in the next chunk. Defer until we see more input.\n if (crIndex === chunk.length - 1) {\n lineEnd = -1;\n }\n else {\n lineEnd = crIndex;\n }\n }\n else if (lfIndex !== -1) {\n lineEnd = lfIndex;\n }\n if (lineEnd === -1) {\n break;\n }\n parseLine(chunk, searchIndex, lineEnd);\n if (checkForBufferOverflow())\n return '';\n searchIndex = lineEnd + 1;\n // If we just consumed a `\\r` and the next char is `\\n`, skip it so the\n // pair is treated as a single terminator rather than an empty line.\n if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {\n searchIndex++;\n }\n }\n return chunk.slice(searchIndex);\n }\n function parseLine(chunk, start, end) {\n if (start === end) {\n dispatchEvent();\n return;\n }\n const firstCharCode = chunk.charCodeAt(start);\n if (isDataPrefix(chunk, start, firstCharCode)) {\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5;\n const value = chunk.slice(valueStart, end);\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n return;\n }\n if (isEventPrefix(chunk, start, firstCharCode)) {\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined;\n return;\n }\n // Fast path for \"id:\" — 'i' = 105, 'd' = 100, ':' = 58\n if (firstCharCode === 105 &&\n chunk.charCodeAt(start + 1) === 100 &&\n chunk.charCodeAt(start + 2) === 58) {\n // 'id:'.length === 3, 'id: '.length === 4\n const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n if (!value.includes('\\0'))\n id = value;\n return;\n }\n // Comment line — ':' = 58\n if (firstCharCode === 58) {\n if (onComment) {\n const line = chunk.slice(start, end);\n // skip ':' (+1), or ': ' (+2) when a space follows\n onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n }\n return;\n }\n const line = chunk.slice(start, end);\n const fieldSeparatorIndex = line.indexOf(':');\n if (fieldSeparatorIndex === -1) {\n processField(line, '', line);\n return;\n }\n const field = line.slice(0, fieldSeparatorIndex);\n // skip ':' (+1), or ': ' (+2) when a space follows\n const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;\n const value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n }\n function processField(field, value, line) {\n // Field names must be compared literally, with no case folding performed.\n switch (field) {\n case 'event':\n // Set the `event type` buffer to field value\n eventType = value || undefined;\n break;\n case 'data':\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n break;\n case 'id':\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n if (!value.includes('\\0'))\n id = value;\n break;\n case 'retry':\n // If the field value consists of only ASCII digits, then interpret the field value as an\n // integer in base ten, and set the event stream's reconnection time to that integer.\n // Otherwise, ignore the field.\n if (/^\\d+$/.test(value)) {\n onRetry === null || onRetry === void 0 ? void 0 : onRetry(parseInt(value, 10));\n }\n else {\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: 'invalid-retry',\n value,\n line,\n }));\n }\n break;\n default:\n // Otherwise, the field is ignored.\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`, { type: 'unknown-field', field, value, line }));\n break;\n }\n }\n function dispatchEvent() {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n if (dataLines > 0) {\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({\n id,\n event: eventType,\n data,\n });\n }\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n }\n function reset(options = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join('');\n parseLine(incompleteLine, 0, incompleteLine.length);\n }\n bomPrefix = '';\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n terminated = false;\n skippingLine = false;\n skipNextLineFeed = false;\n }\n return { feed, reset };\n}\n/**\n * Checks if `chunk` starts with the literal `data:` at index `i`.\n *\n * Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this\n * hand-unrolled char-code comparison is ~20% faster on common event types.\n * The caller passes `firstCharCode` (the code at `i`) so it can be reused\n * across prefix checks.\n *\n * ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58\n */\nfunction isDataPrefix(chunk, i, firstCharCode) {\n return (firstCharCode === 100 &&\n chunk.charCodeAt(i + 1) === 97 &&\n chunk.charCodeAt(i + 2) === 116 &&\n chunk.charCodeAt(i + 3) === 97 &&\n chunk.charCodeAt(i + 4) === 58);\n}\n/**\n * Checks if `chunk` starts with the literal `event:` at index `i`.\n *\n * See {@link isDataPrefix} for why this is hand-unrolled rather than using\n * `String.prototype.startsWith`.\n *\n * ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58\n */\nfunction isEventPrefix(chunk, i, firstCharCode) {\n return (firstCharCode === 101 &&\n chunk.charCodeAt(i + 1) === 118 &&\n chunk.charCodeAt(i + 2) === 101 &&\n chunk.charCodeAt(i + 3) === 110 &&\n chunk.charCodeAt(i + 4) === 116 &&\n chunk.charCodeAt(i + 5) === 58);\n}\nfunction isPotentialField(line, field) {\n let i = 1;\n while (i < line.length && i < field.length) {\n if (line.charCodeAt(i) !== field.charCodeAt(i)) {\n return false;\n }\n i++;\n }\n return line.length <= field.length || line.charCodeAt(field.length) === 58;\n}\n//# sourceMappingURL=parse.js.map","/**\n * SSE subscriber that turns `GET {base_path}/events` into callbacks.\n *\n * One connection per (fetch, url), reference-counted and fanned out to every\n * subscriber. The caller passes an already authenticated `fetch`: this is\n * fetch streaming, not `EventSource`, because `EventSource` cannot send an\n * Authorization header. Frames carry no `event:` name: the first has\n * `id: 0` and `{\"subscriber_id\": ...}`; later ones are record events. A\n * reconnect passes `?{resume_param}=<subscriber_id>` explicitly (never\n * `Last-Event-ID`, which the server would read as a subscriber id) when the\n * stream replays, and always tells subscribers to reset, so the gap is\n * covered even without replay. A stream silent for three keep-alive\n * intervals is dead and is reconnected with exponential backoff and jitter.\n * Events invalidate; they never apply snapshots.\n *\n * A hub is shared by every subscriber of the same (fetch, url) and the first\n * subscriber's options win: the keep-alive, resume parameter, replay mode and\n * resource label of later subscribers are ignored. In development\n * (`process.env.NODE_ENV !== \"production\"`) a later subscriber whose options\n * differ gets a `console.warn` naming the URL and the fields.\n *\n * Every connection has an identity (an opaque {@link EventConnection}) that\n * the hub passes to `onReset` (for the connect reset) and to `onStatus(true)`.\n * A subscriber that joins an already connected hub, or during the handshake's\n * reset fan-out, gets no connect reset; it sees `onStatus(true)` with a\n * connection it was never reset for and resets itself (see `invalidateOnEvents`\n * and `bridgeEvents`).\n */\nimport { createParser } from \"eventsource-parser\";\nimport type { EventSourceMessage } from \"eventsource-parser\";\nimport type { CrudEvent, MaybePromise } from \"./interfaces.ts\";\n\n/** The manifest's `capabilities.events` object (I1), plain. */\nexport interface EventsConfig {\n /** The server's event label, not the manifest name. */\n readonly resource: string;\n readonly path?: string;\n readonly resume_param?: string;\n /** `persistent` resumes by subscriber id; anything else (`none`) does not. A plain string, as on the wire. */\n readonly replay?: string;\n readonly keepalive_seconds?: number;\n}\n\n/** Opaque identity of one connection of a hub; a new one per connect. */\nexport type EventConnection = object;\n\n/**\n * What a subscriber wants to hear. A handler that throws must not kill the\n * stream, so errors are swallowed; handlers run one after another, in order.\n */\nexport interface EventHandlers {\n onEvent(event: CrudEvent): MaybePromise<void>;\n /**\n * After every connect (the first included), and for an event with no usable\n * record id: clear the resource. `connection` is set for the connect reset\n * only, and is the same object `onStatus(true)` then receives.\n */\n onReset?(connection?: EventConnection): MaybePromise<void>;\n /**\n * `true` when the stream is connected, `false` on any loss, exit or\n * unsubscribe. `connection` identifies the connection when `connected`.\n * A subscriber that joined after the connect reset gets `true` without\n * having been sent `onReset` for that connection.\n */\n onStatus?(\n connected: boolean,\n connection?: EventConnection,\n ): MaybePromise<void>;\n}\n\n/** A shared event stream: `subscribe` returns the (idempotent) unsubscribe. */\nexport interface EventHub {\n subscribe(handlers: EventHandlers): () => void;\n}\n\nexport interface EventHubOptions {\n /** Authenticated; shared hubs are keyed by this function and `url`. */\n readonly fetch: typeof fetch;\n /** Absolute URL of the events endpoint. */\n readonly url: string;\n /**\n * Used only by the first subscriber of a hub (first wins): a later\n * subscriber's differing `resource`, `resume_param`, `replay` or\n * `keepalive_seconds` is ignored, with a development `console.warn`.\n */\n readonly events: EventsConfig;\n /** Jitter source in `[0, 1)`; defaults to `Math.random`. */\n readonly random?: () => number;\n}\n\nexport interface SubscribeEventsOptions extends EventHubOptions, EventHandlers {\n /** Aborting unsubscribes. */\n readonly signal?: AbortSignal;\n}\n\nconst BACKOFF_START_MS = 1000;\nconst BACKOFF_MAX_MS = 30_000;\nconst DEFAULT_KEEPALIVE_S = 15;\nconst DEAD_AFTER_KEEPALIVES = 3;\n/** `setTimeout` clamps a longer delay to 1 ms, which would declare the stream dead at once. */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\nconst ACTIONS: ReadonlySet<unknown> = new Set([\n \"create\",\n \"update\",\n \"delete\",\n \"restore\",\n]);\n\n/**\n * The keep-alive interval in seconds. Zero, negative and non-finite values\n * are invalid and treated as unset, so the default applies (as the WHATWG SSE\n * spec ignores an invalid `retry` value instead of acting on it); otherwise a\n * dead-stream deadline of 0 would reconnect forever.\n */\nfunction keepaliveSeconds(events: EventsConfig): number {\n const value = events.keepalive_seconds;\n return value !== undefined && Number.isFinite(value) && value > 0\n ? value\n : DEFAULT_KEEPALIVE_S;\n}\n\n/** The `events` fields that change what a hub does, with defaults applied. */\nfunction hubSettings(events: EventsConfig): Record<string, unknown> {\n return {\n resource: events.resource,\n resume_param: events.resume_param ?? \"subscriber_id\",\n replay: events.replay,\n keepalive_seconds: keepaliveSeconds(events),\n };\n}\n\n/** `process.env.NODE_ENV` is replaced by bundlers; without it (no `process`) assume development. */\nfunction inDevelopment(): boolean {\n try {\n return process.env.NODE_ENV !== \"production\";\n } catch {\n return true;\n }\n}\n\n/** Warns, in development, that a later subscriber's options differ from the hub's. */\nfunction warnOnDifferingOptions(\n hub: EventHubOptions,\n later: EventHubOptions,\n): void {\n if (!inDevelopment()) {\n return;\n }\n const first = hubSettings(hub.events);\n const next = hubSettings(later.events);\n const differing = Object.keys(first).filter(\n (key) => first[key] !== next[key],\n );\n if (differing.length > 0) {\n console.warn(\n `crud-sdk: the event hub for ${hub.url} was opened with other events options; ` +\n `the first subscriber's win and these are ignored: ${differing.join(\", \")}`,\n );\n }\n}\n\nconst registry = new WeakMap<typeof fetch, Map<string, Hub>>();\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n const done = (): void => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, ms);\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n\nclass Hub {\n private readonly handlers = new Set<EventHandlers>();\n private readonly options: EventHubOptions;\n private readonly onEmpty: () => void;\n private controller: AbortController | undefined;\n private connected = false;\n private connection: EventConnection | undefined;\n private subscriberId: string | undefined;\n private attempt = 0;\n\n constructor(options: EventHubOptions, onEmpty: () => void) {\n this.options = options;\n this.onEmpty = onEmpty;\n }\n\n subscribe(handlers: EventHandlers, requested: EventHubOptions): () => void {\n if (this.handlers.size > 0) {\n warnOnDifferingOptions(this.options, requested);\n }\n // The same object may subscribe twice; give each subscription its own identity.\n const entry: EventHandlers = {\n onEvent: (event) => handlers.onEvent(event),\n onReset: (connection) => handlers.onReset?.(connection),\n onStatus: (connected, connection) =>\n handlers.onStatus?.(connected, connection),\n };\n this.handlers.add(entry);\n if (this.controller === undefined) {\n this.controller = new AbortController();\n void this.run(this.controller.signal);\n } else if (this.connected) {\n void this.guard(() => entry.onStatus?.(true, this.connection));\n }\n return () => {\n if (!this.handlers.delete(entry)) {\n return;\n }\n void this.guard(() => entry.onStatus?.(false));\n if (this.handlers.size === 0) {\n // Abort the live stream instead of waiting for the next frame.\n this.controller?.abort();\n this.controller = undefined;\n this.onEmpty();\n }\n };\n }\n\n private async guard(\n call: () => MaybePromise<void> | undefined,\n ): Promise<void> {\n try {\n await call();\n } catch {\n // A failing subscriber must not take the stream down.\n }\n }\n\n private async fan(\n call: (handlers: EventHandlers) => MaybePromise<void> | undefined,\n ): Promise<void> {\n // A snapshot, so a subscriber added during dispatch waits for the next\n // one; one removed meanwhile (its unsubscribe already ran) is skipped.\n for (const handlers of Array.from(this.handlers)) {\n if (this.handlers.has(handlers)) {\n await this.guard(() => call(handlers));\n }\n }\n }\n\n private async setConnected(\n connected: boolean,\n connection?: EventConnection,\n ): Promise<void> {\n if (this.connected === connected) {\n return;\n }\n this.connected = connected;\n this.connection = connected ? connection : undefined;\n await this.fan((handlers) => handlers.onStatus?.(connected, connection));\n }\n\n private backoff(): number {\n const base = Math.min(BACKOFF_START_MS * 2 ** this.attempt, BACKOFF_MAX_MS);\n this.attempt += 1;\n const jitter = (this.options.random ?? Math.random)();\n return Math.min(base * (1 + 0.5 * jitter), BACKOFF_MAX_MS);\n }\n\n /** Connect, read and reconnect until aborted. */\n private async run(signal: AbortSignal): Promise<void> {\n try {\n while (!signal.aborted) {\n try {\n await this.readOnce(signal);\n } catch {\n // Lost, refused or dead: reconnect below.\n }\n await this.setConnected(false);\n await sleep(this.backoff(), signal);\n }\n } finally {\n // On any exit, tell the subscribers so the freshness gate closes.\n await this.setConnected(false);\n }\n }\n\n private resumeUrl(): string {\n const { url, events } = this.options;\n if (events.replay !== \"persistent\" || this.subscriberId === undefined) {\n return url;\n }\n const param = events.resume_param ?? \"subscriber_id\";\n const separator = url.includes(\"?\") ? \"&\" : \"?\";\n return `${url}${separator}${encodeURIComponent(param)}=${encodeURIComponent(this.subscriberId)}`;\n }\n\n private async readOnce(signal: AbortSignal): Promise<void> {\n const deadMs = Math.min(\n keepaliveSeconds(this.options.events) * DEAD_AFTER_KEEPALIVES * 1000,\n MAX_TIMER_MS,\n );\n const conn = new AbortController();\n const abortConn = (): void => {\n conn.abort();\n };\n signal.addEventListener(\"abort\", abortConn, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const arm = (): void => {\n clearTimeout(timer);\n timer = setTimeout(abortConn, deadMs);\n };\n try {\n arm();\n const response = await this.options.fetch(this.resumeUrl(), {\n headers: { accept: \"text/event-stream\" },\n signal: conn.signal,\n });\n if (!response.ok || response.body === null) {\n throw new Error(`event stream refused: HTTP ${response.status}`);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const pending: EventSourceMessage[] = [];\n const parser = createParser({\n onEvent: (message) => {\n pending.push(message);\n },\n });\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n parser.feed(decoder.decode(value, { stream: true }));\n // Any byte, keep-alive comments included, proves the stream is alive.\n // Handlers may be slow and nothing is read meanwhile, so the timer is\n // paused while they run and restarts once they are done.\n clearTimeout(timer);\n for (const message of pending.splice(0)) {\n await this.handle(message);\n }\n arm();\n }\n } finally {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", abortConn);\n conn.abort(); // release the connection on every way out\n }\n }\n\n private async handle(message: EventSourceMessage): Promise<void> {\n let data: unknown;\n try {\n data = JSON.parse(message.data);\n } catch {\n return;\n }\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n return;\n }\n const record = data as Record<string, unknown>;\n if (\"subscriber_id\" in record) {\n this.subscriberId = String(record[\"subscriber_id\"]);\n this.attempt = 0;\n // Every connect, the first included: entries stored before this stream\n // (an earlier page session, a persisted store) may predate server changes.\n // A subscriber that joins while this fans out is not in it; it gets\n // `onStatus(true)` with this connection and resets itself.\n const connection: EventConnection = {};\n const present = new Set(this.handlers);\n await this.fan((handlers) => handlers.onReset?.(connection));\n if (this.connected) {\n // A repeated handshake on a live stream: whoever joined during the\n // fan-out was told about the old connection only.\n this.connection = connection;\n for (const handlers of Array.from(this.handlers)) {\n if (!present.has(handlers)) {\n await this.guard(() => handlers.onStatus?.(true, connection));\n }\n }\n } else {\n await this.setConnected(true, connection);\n }\n return;\n }\n if (record[\"resource\"] !== this.options.events.resource) {\n return;\n }\n const action = record[\"action\"];\n const recordId = record[\"record_id\"];\n if (!ACTIONS.has(action) || !Number.isInteger(recordId)) {\n await this.fan((handlers) => handlers.onReset?.());\n return;\n }\n const snapshot = record[\"snapshot\"];\n const event: CrudEvent = {\n resource: String(record[\"resource\"]),\n recordId: recordId as number,\n action: action as CrudEvent[\"action\"],\n snapshot:\n typeof snapshot === \"object\" && snapshot !== null\n ? (snapshot as Record<string, unknown>)\n : {},\n timestamp: String(record[\"timestamp\"] ?? \"\"),\n };\n await this.fan((handlers) => handlers.onEvent(event));\n }\n}\n\n/**\n * The shared hub for `(fetch, url)`: the first subscriber opens the stream,\n * the last one aborts it. A later subscribe after that opens a fresh one.\n *\n * The first subscriber's `events` options win while the hub lives. A later\n * subscriber whose `resource`, `resume_param`, `replay` or `keepalive_seconds`\n * differ is served by the same stream with the first's values, and in\n * development (`process.env.NODE_ENV !== \"production\"`) gets a `console.warn`\n * naming the URL and the differing fields.\n */\nexport function getEventHub(options: EventHubOptions): EventHub {\n return {\n subscribe(handlers) {\n let hubs = registry.get(options.fetch);\n if (hubs === undefined) {\n hubs = new Map();\n registry.set(options.fetch, hubs);\n }\n const byUrl = hubs;\n let hub = byUrl.get(options.url);\n if (hub === undefined) {\n hub = new Hub(options, () => {\n byUrl.delete(options.url);\n });\n byUrl.set(options.url, hub);\n }\n return hub.subscribe(handlers, options);\n },\n };\n}\n\n/**\n * Subscribe to one resource's event stream. Returns the unsubscribe; the\n * last unsubscribe aborts the stream. `signal` aborting unsubscribes too.\n */\nexport function subscribeEvents(options: SubscribeEventsOptions): () => void {\n const { signal } = options;\n if (signal?.aborted === true) {\n return () => undefined;\n }\n const unsubscribe = getEventHub(options).subscribe(options);\n signal?.addEventListener(\"abort\", unsubscribe, { once: true });\n return () => {\n signal?.removeEventListener(\"abort\", unsubscribe);\n unsubscribe();\n };\n}\n"],"ignoreList":[2,3],"mappings":";AA8BA,SAAS,QAAQ,OAAwB;CACvC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IACrD,KAAK,IAAI,OAAO,CAAC,IACjB;AACN;;AAGA,SAAgB,wBACd,UACA,YAAkC,CAAC,GACtB;CACb,MAAM,QAAQ,SAAS,SAAS,CAAC;CACjC,OAAO;EACL,SAAS,UAAU,WAAW;EAC9B,QAAQ,UAAU,UAAU,QAAQ,MAAM,OAAO;EACjD,UAAU,UAAU,YAAY,QAAQ,MAAM,SAAS;EACvD,sBACE,UAAU,wBAAwB,QAAQ,MAAM,sBAAsB;EACxE,MAAM,UAAU,QAAQ,MAAM,SAAS;EACvC,gBAAgB,UAAU,kBAAkB,MAAM,oBAAoB;CACxE;AACF;;;;;AAMA,SAAgB,oBACd,UACA,YAAkC,CAAC,GACtB;CACb,OAAO,wBAAwB,UAAU;EACvC,gBAAgB;EAChB,GAAG;CACL,CAAC;AACH;;;ACzDA,MAAM,yBAAS,IAAI,QAGjB;;;;;;AAOF,SAAgB,UACd,YACA,OACA,KACA,OACe;CACf,IAAI,SAAS,OAAO,IAAI,UAAU;CAClC,IAAI,WAAW,KAAA,GAAW;EACxB,yBAAS,IAAI,QAAQ;EACrB,OAAO,IAAI,YAAY,MAAM;CAC/B;CACA,IAAI,OAAO,OAAO,IAAI,KAAK;CAC3B,IAAI,SAAS,KAAA,GAAW;EACtB,uBAAO,IAAI,IAAI;EACf,OAAO,IAAI,OAAO,IAAI;CACxB;CACA,MAAM,OAAO,KAAK,IAAI,GAAG;CACzB,IAAI,SAAS,KAAA,GACX,OAAO;CAET,MAAM,WAAW,YAA2B;EAC1C,MAAM,MAAM;CACd,EAAA,CAAG;CACH,KAAK,IAAI,KAAK,OAAO;CACrB,MAAM,SAAS;CACf,QAAQ,YA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,OAAO,UAAU,QAAQ,GAAG;GACvD,MAAM,KAAK,KAAK,aAAa,SAAS,UAAU,CAAC;GACjD;EACF;EACA,MAAM,WAAW,OAAO;EACxB,MAAM,QAAmB;GACvB,UAAU,OAAO,OAAO,WAAW;GACzB;GACF;GACR,UACE,OAAO,aAAa,YAAY,aAAa,OACxC,WACD,CAAC;GACP,WAAW,OAAO,OAAO,gBAAgB,EAAE;EAC7C;EACA,MAAM,KAAK,KAAK,aAAa,SAAS,QAAQ,KAAK,CAAC;CACtD;AACF;;;;;;;;;;;AAYA,SAAgB,YAAY,SAAoC;CAC9D,OAAO,EACL,UAAU,UAAU;EAClB,IAAI,OAAO,SAAS,IAAI,QAAQ,KAAK;EACrC,IAAI,SAAS,KAAA,GAAW;GACtB,uBAAO,IAAI,IAAI;GACf,SAAS,IAAI,QAAQ,OAAO,IAAI;EAClC;EACA,MAAM,QAAQ;EACd,IAAI,MAAM,MAAM,IAAI,QAAQ,GAAG;EAC/B,IAAI,QAAQ,KAAA,GAAW;GACrB,MAAM,IAAI,IAAI,eAAe;IAC3B,MAAM,OAAO,QAAQ,GAAG;GAC1B,CAAC;GACD,MAAM,IAAI,QAAQ,KAAK,GAAG;EAC5B;EACA,OAAO,IAAI,UAAU,UAAU,OAAO;CACxC,EACF;AACF;;;;;AAMA,SAAgB,gBAAgB,SAA6C;CAC3E,MAAM,EAAE,WAAW;CACnB,IAAI,QAAQ,YAAY,MACtB,aAAa,KAAA;CAEf,MAAM,cAAc,YAAY,OAAO,CAAC,CAAC,UAAU,OAAO;CAC1D,QAAQ,iBAAiB,SAAS,aAAa,EAAE,MAAM,KAAK,CAAC;CAC7D,aAAa;EACX,QAAQ,oBAAoB,SAAS,WAAW;EAChD,YAAY;CACd;AACF"}
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as Middleware, c as RequestContext, i as MaybePromise, l as TokenProvider, n as CacheStore, o as Next, r as CrudEvent, s as Op, t as CacheEntry, u as composeMiddleware } from "./interfaces-s73cVfIF.mjs";
2
- import { A as Pagination, C as Capabilities, D as JsonObject, E as GetJson, F as manifestUrlFromCatalog, I as parseManifest, M as Schemas, N as findResource, O as Manifest, P as loadManifest, S as CacheHints, T as FieldSpec, _ as encodeParams, a as PredictOptions, b as AuthSpec, c as RestoreOptions, d as createClient, f as Filters, g as buildQuery, h as Sort, i as ListOptions, j as Resource, k as PROFILE, l as StatsOptions, m as QueryParams, n as ClientOptions, o as RequestOptions, p as QueryField, r as CrudClient, s as ResourceClient, t as BulkResult, u as WriteOptions, v as formatScalar, w as EventsSpec, x as CATALOG_PATH, y as quote } from "./client-BU9rPr8h.mjs";
2
+ import { A as Pagination, C as Capabilities, D as JsonObject, E as GetJson, F as manifestUrlFromCatalog, I as parseManifest, M as Schemas, N as findResource, O as Manifest, P as loadManifest, S as CacheHints, T as FieldSpec, _ as encodeParams, a as PredictOptions, b as AuthSpec, c as RestoreOptions, d as createClient, f as Filters, g as buildQuery, h as Sort, i as ListOptions, j as Resource, k as PROFILE, l as StatsOptions, m as QueryParams, n as ClientOptions, o as RequestOptions, p as QueryField, r as CrudClient, s as ResourceClient, t as BulkResult, u as WriteOptions, v as formatScalar, w as EventsSpec, x as CATALOG_PATH, y as quote } from "./client-Drvc7htU.mjs";
3
3
  //#region src/auth.d.ts
4
4
  /** The scope of an anonymous caller. */
5
5
  export declare const ANON = "anon";
@@ -28,6 +28,12 @@ export declare class ClientError extends CrudError {}
28
28
  export declare class CapabilityError extends ClientError {}
29
29
  /** A filter, sort or paging argument is not valid for the resource. */
30
30
  export declare class InvalidQueryError extends ClientError {}
31
+ /**
32
+ * A request carrying an `Authorization` header was about to go over plain
33
+ * `http:` to a non-loopback host. Nothing was sent. Use `https:`, or opt in
34
+ * with `allowInsecureHttp`.
35
+ */
36
+ export declare class InsecureTransportError extends ClientError {}
31
37
  /** The discovery document or the manifest is missing, unusable or of an unknown version. */
32
38
  export declare class ManifestError extends ClientError {}
33
39
  /** The manifest lists no such resource for this caller. */
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { A as UnknownResourceError, C as NotFound, D as ResponseError, E as RateLimited, M as problemFromResponse, N as composeMiddleware, O as ServerError, S as ManifestError, T as ProblemError, _ as ConnectionFailed, a as encodeParams, b as InvalidQueryError, c as CATALOG_PATH, d as loadManifest, f as manifestUrlFromCatalog, g as ClientError, h as CapabilityError, i as buildQuery, j as ValidationFailed, k as Unauthorized, l as PROFILE, m as BadRequest, n as ResourceClient, o as formatScalar, p as parseManifest, r as createClient, s as quote, t as CrudClient, u as findResource, v as CrudError, w as PreconditionFailed, x as Locked, y as Forbidden } from "./client-DJkbw9_q.mjs";
2
- import { n as cacheScope, r as staticToken, t as ANON } from "./auth-DwtNEKrw.mjs";
3
- export { ANON, BadRequest, CATALOG_PATH, CapabilityError, ClientError, ConnectionFailed, CrudClient, CrudError, Forbidden, InvalidQueryError, Locked, ManifestError, NotFound, PROFILE, PreconditionFailed, ProblemError, RateLimited, ResourceClient, ResponseError, ServerError, Unauthorized, UnknownResourceError, ValidationFailed, buildQuery, cacheScope, composeMiddleware, createClient, encodeParams, findResource, formatScalar, loadManifest, manifestUrlFromCatalog, parseManifest, problemFromResponse, quote, staticToken };
1
+ import { A as Unauthorized, C as ManifestError, D as RateLimited, E as ProblemError, M as ValidationFailed, N as problemFromResponse, O as ResponseError, P as composeMiddleware, S as Locked, T as PreconditionFailed, _ as ConnectionFailed, a as encodeParams, b as InsecureTransportError, c as CATALOG_PATH, d as loadManifest, f as manifestUrlFromCatalog, g as ClientError, h as CapabilityError, i as buildQuery, j as UnknownResourceError, k as ServerError, l as PROFILE, m as BadRequest, n as ResourceClient, o as formatScalar, p as parseManifest, r as createClient, s as quote, t as CrudClient, u as findResource, v as CrudError, w as NotFound, x as InvalidQueryError, y as Forbidden } from "./client-nciUfgwW.mjs";
2
+ import { i as staticToken, n as cacheScope, t as ANON } from "./auth-C5__H0Ln.mjs";
3
+ export { ANON, BadRequest, CATALOG_PATH, CapabilityError, ClientError, ConnectionFailed, CrudClient, CrudError, Forbidden, InsecureTransportError, InvalidQueryError, Locked, ManifestError, NotFound, PROFILE, PreconditionFailed, ProblemError, RateLimited, ResourceClient, ResponseError, ServerError, Unauthorized, UnknownResourceError, ValidationFailed, buildQuery, cacheScope, composeMiddleware, createClient, encodeParams, findResource, formatScalar, loadManifest, manifestUrlFromCatalog, parseManifest, problemFromResponse, quote, staticToken };
@@ -1,6 +1,6 @@
1
1
  import { r as CrudEvent } from "../interfaces-s73cVfIF.mjs";
2
- import { a as SubscribeEventsOptions, c as CachePolicy, d as tanstackCachePolicy, i as EventsConfig, l as ManifestCacheHints, n as EventHub, o as getEventHub, r as EventHubOptions, s as subscribeEvents, t as EventHandlers } from "../events-DpSWzSN9.mjs";
3
- import { D as JsonObject, O as Manifest, r as CrudClient, s as ResourceClient } from "../client-BU9rPr8h.mjs";
2
+ import { a as EventsConfig, c as subscribeEvents, f as tanstackCachePolicy, i as EventHubOptions, l as CachePolicy, n as EventHandlers, o as SubscribeEventsOptions, r as EventHub, s as getEventHub, t as EventConnection, u as ManifestCacheHints } from "../events-DdT0AkNE.mjs";
3
+ import { D as JsonObject, O as Manifest, r as CrudClient, s as ResourceClient } from "../client-Drvc7htU.mjs";
4
4
  import { DataTag, QueryClient } from "@tanstack/query-core";
5
5
  //#region src/tanstack/adapter.d.ts
6
6
  type Init = {
@@ -208,19 +208,30 @@ export declare function invalidateRecord(queryClient: Pick<QueryClient, "invalid
208
208
  export interface CreateMutationOptions<T, C> {
209
209
  readonly mutationKey: readonly ["crud", string, string, string, "create"];
210
210
  readonly mutationFn: (body: C) => Promise<T>;
211
- readonly onSuccess: () => Promise<void>;
211
+ /** Invalidates lists, stats and predict, whether the write succeeded or failed. */
212
+ readonly onSettled: (data: T | undefined, error: unknown) => Promise<void>;
212
213
  }
213
214
  export interface UpdateMutationOptions<T, P> {
214
215
  readonly mutationKey: readonly ["crud", string, string, string, "update"];
215
216
  readonly mutationFn: (variables: UpdateVariables<P>) => Promise<T>;
217
+ /** Sets the caller's record query from the PATCH response. */
216
218
  readonly onSuccess: (record: T, variables: UpdateVariables<P>) => Promise<void>;
219
+ /** Invalidates collections, other scopes' records and revisions, whether the write succeeded or failed. */
220
+ readonly onSettled: (data: T | undefined, error: unknown, variables: UpdateVariables<P>) => Promise<void>;
217
221
  }
218
222
  export interface DeleteMutationOptions {
219
223
  readonly mutationKey: readonly ["crud", string, string, string, "delete"];
220
224
  readonly mutationFn: (id: number) => Promise<unknown>;
225
+ /** Drops the deleted record's query. */
221
226
  readonly onSuccess: (result: unknown, id: number) => Promise<void>;
227
+ /** Invalidates collections and the record's revisions, whether the write succeeded or failed. */
228
+ readonly onSettled: (data: unknown, error: unknown, id: number) => Promise<void>;
222
229
  }
223
- /** Create: invalidate lists, stats and predict. */
230
+ /**
231
+ * Create: `onSettled` invalidates lists, stats and predict after success or
232
+ * failure (a `5xx` or a dropped connection may have applied the write, so
233
+ * TanStack's "always refetch after error or success").
234
+ */
224
235
  export declare function createMutationOptions<T, C>(queryClient: Invalidator, ns: CrudNamespace, resource: string, api: CreateApi<T, C>): CreateMutationOptions<T, C>;
225
236
  export interface UpdateVariables<P> {
226
237
  readonly id: number;
@@ -228,18 +239,29 @@ export interface UpdateVariables<P> {
228
239
  /** Sent as `If-Match`; a stale one fails with 412. */
229
240
  readonly ifMatch?: string;
230
241
  }
231
- /** Update: `setQueryData` from the PATCH response, invalidate lists, stats, predict and revisions. */
242
+ /**
243
+ * Update: `onSuccess` sets the record query from the PATCH response;
244
+ * `onSettled` invalidates lists, stats, predict and revisions after success or
245
+ * failure. After a failure the caller's own record is invalidated too (it was
246
+ * not set, and a `412` means it is stale).
247
+ */
232
248
  export declare function updateMutationOptions<T, P>(queryClient: Invalidator, ns: CrudNamespace, resource: string, api: UpdateApi<T, P>): UpdateMutationOptions<T, P>;
233
- /** Delete: drop the record query, invalidate lists, stats, predict and revisions. */
249
+ /**
250
+ * Delete: `onSuccess` drops the record query; `onSettled` invalidates lists,
251
+ * stats, predict and the record's revisions after success or failure. After a
252
+ * failure the record query is invalidated too (the row still exists).
253
+ */
234
254
  export declare function deleteMutationOptions(queryClient: Invalidator, ns: CrudNamespace, resource: string, api: DeleteApi): DeleteMutationOptions;
235
255
  /**
236
256
  * Invalidate TanStack queries from the resource's event stream. Events
237
257
  * invalidate and never apply snapshots: `create` invalidates lists, stats and
238
258
  * predict; `update`/`delete`/`restore` also the record and its revisions; a
239
259
  * reconnect (or an event with no usable record id) invalidates the resource.
240
- * Returns the unsubscribe.
260
+ * A bridge that joins an already connected hub (or during the handshake)
261
+ * invalidates the resource once on subscribing, unless this `queryClient` was
262
+ * already reset for the resource on that connection. Returns the unsubscribe.
241
263
  */
242
264
  export declare function bridgeEvents(queryClient: Pick<QueryClient, "invalidateQueries">, hub: EventHub, target: CrudTarget): () => void;
243
265
  //#endregion
244
- export { type CachePolicy, type CrudEvent, type EventHandlers, type EventHub, type EventHubOptions, type EventsConfig, type ManifestCacheHints, type SubscribeEventsOptions, type TanstackApi, getEventHub, subscribeEvents, tanstackCachePolicy };
266
+ export { type CachePolicy, type CrudEvent, type EventConnection, type EventHandlers, type EventHub, type EventHubOptions, type EventsConfig, type ManifestCacheHints, type SubscribeEventsOptions, type TanstackApi, getEventHub, subscribeEvents, tanstackCachePolicy };
245
267
  //# sourceMappingURL=index.d.mts.map
@@ -1,4 +1,4 @@
1
- import { i as tanstackCachePolicy, n as subscribeEvents, t as getEventHub } from "../events-Cqj9Rbon.mjs";
1
+ import { a as tanstackCachePolicy, n as subscribeEvents, r as resetOnce, t as getEventHub } from "../events-Dfz-rzC8.mjs";
2
2
  //#region src/tanstack/adapter.ts
3
3
  /**
4
4
  * A query is the client's `ListOptions`, `StatsOptions` or `PredictOptions`
@@ -210,7 +210,11 @@ function invalidateRecord(queryClient, { client, resource }, id) {
210
210
  id
211
211
  }));
212
212
  }
213
- /** Create: invalidate lists, stats and predict. */
213
+ /**
214
+ * Create: `onSettled` invalidates lists, stats and predict after success or
215
+ * failure (a `5xx` or a dropped connection may have applied the write, so
216
+ * TanStack's "always refetch after error or success").
217
+ */
214
218
  function createMutationOptions(queryClient, ns, resource, api) {
215
219
  return {
216
220
  mutationKey: [
@@ -221,13 +225,18 @@ function createMutationOptions(queryClient, ns, resource, api) {
221
225
  "create"
222
226
  ],
223
227
  mutationFn: (body) => api.create(body),
224
- onSuccess: () => invalidateCollections(queryClient, {
228
+ onSettled: () => invalidateCollections(queryClient, {
225
229
  client: ns.client,
226
230
  resource
227
231
  })
228
232
  };
229
233
  }
230
- /** Update: `setQueryData` from the PATCH response, invalidate lists, stats, predict and revisions. */
234
+ /**
235
+ * Update: `onSuccess` sets the record query from the PATCH response;
236
+ * `onSettled` invalidates lists, stats, predict and revisions after success or
237
+ * failure. After a failure the caller's own record is invalidated too (it was
238
+ * not set, and a `412` means it is stale).
239
+ */
231
240
  function updateMutationOptions(queryClient, ns, resource, api) {
232
241
  return {
233
242
  mutationKey: [
@@ -238,23 +247,25 @@ function updateMutationOptions(queryClient, ns, resource, api) {
238
247
  "update"
239
248
  ],
240
249
  mutationFn: ({ id, patch, ifMatch }) => api.update(id, patch, ifMatch === void 0 ? {} : { ifMatch }),
241
- onSuccess: async (record, { id }) => {
250
+ onSuccess: (record, { id }) => {
242
251
  queryClient.setQueryData(crudKeys.record(ns, resource, id), record);
252
+ return Promise.resolve();
253
+ },
254
+ onSettled: async (_data, error, { id }) => {
255
+ const target = {
256
+ client: ns.client,
257
+ resource
258
+ };
243
259
  await Promise.all([
244
- invalidateCollections(queryClient, {
245
- client: ns.client,
246
- resource
247
- }),
260
+ invalidateCollections(queryClient, target),
248
261
  queryClient.invalidateQueries(crudKeys.filter({
249
- client: ns.client,
250
- resource,
251
- exceptScope: ns.scope,
262
+ ...target,
263
+ ...error === null || error === void 0 ? { exceptScope: ns.scope } : {},
252
264
  kinds: ["record"],
253
265
  id
254
266
  })),
255
267
  queryClient.invalidateQueries(crudKeys.filter({
256
- client: ns.client,
257
- resource,
268
+ ...target,
258
269
  kinds: ["revisions"],
259
270
  id
260
271
  }))
@@ -262,7 +273,11 @@ function updateMutationOptions(queryClient, ns, resource, api) {
262
273
  }
263
274
  };
264
275
  }
265
- /** Delete: drop the record query, invalidate lists, stats, predict and revisions. */
276
+ /**
277
+ * Delete: `onSuccess` drops the record query; `onSettled` invalidates lists,
278
+ * stats, predict and the record's revisions after success or failure. After a
279
+ * failure the record query is invalidated too (the row still exists).
280
+ */
266
281
  function deleteMutationOptions(queryClient, ns, resource, api) {
267
282
  return {
268
283
  mutationKey: [
@@ -273,22 +288,21 @@ function deleteMutationOptions(queryClient, ns, resource, api) {
273
288
  "delete"
274
289
  ],
275
290
  mutationFn: (id) => api.delete(id),
276
- onSuccess: async (_result, id) => {
291
+ onSuccess: (_result, id) => {
277
292
  queryClient.removeQueries(crudKeys.filter({
278
293
  client: ns.client,
279
294
  resource,
280
295
  kinds: ["record"],
281
296
  id
282
297
  }));
283
- await Promise.all([invalidateCollections(queryClient, {
298
+ return Promise.resolve();
299
+ },
300
+ onSettled: async (_data, _error, id) => {
301
+ const target = {
284
302
  client: ns.client,
285
303
  resource
286
- }), queryClient.invalidateQueries(crudKeys.filter({
287
- client: ns.client,
288
- resource,
289
- kinds: ["revisions"],
290
- id
291
- }))]);
304
+ };
305
+ await Promise.all([invalidateCollections(queryClient, target), invalidateRecord(queryClient, target, id)]);
292
306
  }
293
307
  };
294
308
  }
@@ -297,16 +311,22 @@ function deleteMutationOptions(queryClient, ns, resource, api) {
297
311
  * invalidate and never apply snapshots: `create` invalidates lists, stats and
298
312
  * predict; `update`/`delete`/`restore` also the record and its revisions; a
299
313
  * reconnect (or an event with no usable record id) invalidates the resource.
300
- * Returns the unsubscribe.
314
+ * A bridge that joins an already connected hub (or during the handshake)
315
+ * invalidates the resource once on subscribing, unless this `queryClient` was
316
+ * already reset for the resource on that connection. Returns the unsubscribe.
301
317
  */
302
318
  function bridgeEvents(queryClient, hub, target) {
319
+ const reset = (connection) => resetOnce(connection, queryClient, JSON.stringify([target.client, target.resource]), () => invalidateResource(queryClient, target));
303
320
  return hub.subscribe({
304
321
  onEvent: async (event) => {
305
322
  const pending = [invalidateCollections(queryClient, target)];
306
323
  if (event.action !== "create") pending.push(invalidateRecord(queryClient, target, event.recordId));
307
324
  await Promise.all(pending);
308
325
  },
309
- onReset: () => invalidateResource(queryClient, target)
326
+ onReset: (connection) => connection === void 0 ? invalidateResource(queryClient, target) : reset(connection),
327
+ onStatus: async (up, connection) => {
328
+ if (up && connection !== void 0) await reset(connection);
329
+ }
310
330
  });
311
331
  }
312
332
  //#endregion