@teyik0/furin 0.8.0-alpha.0 → 0.9.0-alpha.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.
Files changed (143) hide show
  1. package/README.md +37 -0
  2. package/dist/adapter/bun/app.d.ts +1 -0
  3. package/dist/adapter/bun.d.ts +3 -1
  4. package/dist/adapter/runtime-build.d.ts +8 -5
  5. package/dist/adapter/vercel.js +8 -8
  6. package/dist/build/client.d.ts +2 -2
  7. package/dist/build/discover-mounts-process.d.ts +1 -1
  8. package/dist/build/discover-pages-process.d.ts +1 -0
  9. package/dist/build/discover-pages.d.ts +11 -0
  10. package/dist/build/discovery-module.d.ts +3 -0
  11. package/dist/build/discovery-plugins.d.ts +34 -0
  12. package/dist/build/elysia-aot.d.ts +1 -1
  13. package/dist/build/entry-template.ts +6 -1
  14. package/dist/build/hydrate.d.ts +3 -2
  15. package/dist/build/index.js +7688 -8458
  16. package/dist/build/preload-manifest.d.ts +2 -2
  17. package/dist/build/route-metadata.d.ts +31 -0
  18. package/dist/build/route-types.d.ts +1 -1
  19. package/dist/build/shared.d.ts +2 -2
  20. package/dist/build/types.d.ts +11 -0
  21. package/dist/cli/dev-worker.d.ts +1 -0
  22. package/dist/cli/dev-worker.ts +123 -0
  23. package/dist/cli/dev.d.ts +1 -0
  24. package/dist/cli/index.js +7811 -8477
  25. package/dist/client/browser-events-runtime.d.ts +2 -2
  26. package/dist/client/browser-events.d.ts +2 -0
  27. package/dist/client/chunks/{client-brdfd773.js → client-rjhxgt64.js} +187 -4
  28. package/dist/client/dev-error-overlay.ts +18 -1
  29. package/dist/client/link.js +110 -156
  30. package/dist/client/query-store.d.ts +5 -0
  31. package/dist/client/router/navigation-controller.d.ts +2 -0
  32. package/dist/client/router/use-fetch-interception.d.ts +1 -1
  33. package/dist/client/router/use-sync-stream.d.ts +1 -1
  34. package/dist/client/{router/sync-catch-up.d.ts → sync-catch-up.d.ts} +5 -3
  35. package/dist/client/sync-client.d.ts +74 -0
  36. package/dist/client.d.ts +1 -0
  37. package/dist/client.js +533 -145
  38. package/dist/config.d.ts +6 -1
  39. package/dist/config.js +3 -1
  40. package/dist/define-route.d.ts +3 -3
  41. package/dist/furin.d.ts +2 -1
  42. package/dist/furin.js +1119 -346
  43. package/dist/plugin/index.js +5 -5
  44. package/dist/plugin/route-registry.d.ts +22 -2
  45. package/dist/rsc/build/index.d.ts +4 -3
  46. package/dist/server/dev/server-only-module.d.ts +5 -0
  47. package/dist/server/internal.js +201 -91
  48. package/dist/server/logging/ingest-plugin.d.ts +1 -2
  49. package/dist/server/production-server.js +36 -33
  50. package/dist/server/server-entry.d.ts +5 -0
  51. package/dist/server/server-entry.js +36 -0
  52. package/dist/server/static-export.js +201 -91
  53. package/dist/server/sync/adapter.d.ts +4 -3
  54. package/dist/server/sync/config.d.ts +7 -0
  55. package/dist/server/sync/connection.d.ts +13 -0
  56. package/dist/server/sync/drizzle/index.js +5 -4
  57. package/dist/server/sync/index.d.ts +3 -0
  58. package/dist/server/sync/index.js +1361 -243
  59. package/dist/server/sync/invalidate-sync.d.ts +6 -2
  60. package/dist/server/sync/local-client.d.ts +9 -0
  61. package/dist/server/sync/postgres/index.d.ts +1 -1
  62. package/dist/server/sync/postgres/index.js +2 -2
  63. package/dist/server/sync/prisma/index.js +2 -2
  64. package/dist/server/sync/redis/index.d.ts +1 -1
  65. package/dist/server/sync/redis/index.js +4 -3
  66. package/dist/server/sync/redis/scripts.d.ts +1 -1
  67. package/dist/server/sync/runtime.d.ts +3 -0
  68. package/dist/server/sync/sqlite/index.d.ts +1 -1
  69. package/dist/server/sync/sqlite/index.js +3 -2
  70. package/dist/shared/browser-events.d.ts +4 -0
  71. package/dist/sync-client.d.ts +3 -0
  72. package/dist/sync-client.js +1600 -0
  73. package/package.json +12 -7
  74. package/src/adapter/README.md +7 -0
  75. package/src/adapter/build.ts +34 -33
  76. package/src/adapter/bun/app.ts +5 -0
  77. package/src/adapter/bun/server.ts +2 -2
  78. package/src/adapter/bun.ts +18 -2
  79. package/src/adapter/furin-app.d.ts +1 -0
  80. package/src/adapter/package.ts +1 -0
  81. package/src/adapter/runtime-build.ts +18 -12
  82. package/src/adapter/static.ts +17 -13
  83. package/src/build/client.ts +7 -5
  84. package/src/build/discover-mounts-process.ts +5 -1
  85. package/src/build/discover-pages-process.ts +151 -0
  86. package/src/build/discover-pages.ts +69 -0
  87. package/src/build/discovery-module.ts +70 -0
  88. package/src/build/discovery-plugins.ts +101 -0
  89. package/src/build/elysia-aot-worker.ts +9 -8
  90. package/src/build/elysia-aot.ts +110 -75
  91. package/src/build/entry-template.ts +6 -1
  92. package/src/build/hydrate.ts +11 -8
  93. package/src/build/index.ts +6 -50
  94. package/src/build/preload-manifest.ts +3 -3
  95. package/src/build/route-metadata.ts +90 -0
  96. package/src/build/route-types.ts +1 -1
  97. package/src/build/shared.ts +6 -8
  98. package/src/build/types.ts +9 -0
  99. package/src/cli/config.ts +4 -0
  100. package/src/cli/dev-worker.ts +123 -0
  101. package/src/cli/dev.ts +91 -0
  102. package/src/cli/index.ts +24 -1
  103. package/src/client/browser-events-runtime.ts +97 -23
  104. package/src/client/browser-events.ts +8 -0
  105. package/src/client/dev-error-overlay.ts +18 -1
  106. package/src/client/query-store.ts +54 -3
  107. package/src/client/router/navigation-controller.ts +45 -12
  108. package/src/client/router/provider.tsx +6 -2
  109. package/src/client/router/use-fetch-interception.ts +1 -1
  110. package/src/client/router/use-sync-stream.ts +96 -44
  111. package/src/client/{router/sync-catch-up.ts → sync-catch-up.ts} +28 -12
  112. package/src/client/sync-client.ts +528 -0
  113. package/src/client/sync.ts +11 -4
  114. package/src/client.ts +10 -0
  115. package/src/config.ts +17 -10
  116. package/src/furin.ts +5 -0
  117. package/src/plugin/route-registry.ts +53 -7
  118. package/src/rsc/build/index.ts +6 -3
  119. package/src/server/browser-events/plugin.ts +79 -25
  120. package/src/server/dev/rewrite-module-specifiers.ts +2 -1
  121. package/src/server/dev/server-only-module.ts +23 -0
  122. package/src/server/dev/symbolicate.ts +4 -3
  123. package/src/server/dev-page-imports.ts +3 -1
  124. package/src/server/dev-page-plugin.ts +18 -1
  125. package/src/server/logging/ingest-plugin.ts +3 -9
  126. package/src/server/server-entry.ts +39 -0
  127. package/src/server/sync/adapter.ts +7 -3
  128. package/src/server/sync/config.ts +12 -6
  129. package/src/server/sync/connection.ts +71 -0
  130. package/src/server/sync/index.ts +3 -0
  131. package/src/server/sync/invalidate-sync.ts +30 -5
  132. package/src/server/sync/local-client.ts +84 -0
  133. package/src/server/sync/plugin.ts +27 -20
  134. package/src/server/sync/postgres/index.ts +9 -2
  135. package/src/server/sync/redis/index.ts +5 -1
  136. package/src/server/sync/redis/scripts.ts +1 -1
  137. package/src/server/sync/runtime.ts +56 -18
  138. package/src/server/sync/sqlite/index.ts +6 -2
  139. package/src/server/sync/stream.ts +17 -5
  140. package/src/shared/browser-events.ts +1 -1
  141. package/src/sync-client.ts +14 -0
  142. package/dist/server/logger.d.ts +0 -10
  143. package/src/server/logger.ts +0 -34
package/dist/furin.js CHANGED
@@ -4672,6 +4672,45 @@ class QueryStore {
4672
4672
  generation() {
4673
4673
  return this.epoch;
4674
4674
  }
4675
+ clear(preserveData) {
4676
+ this.epoch += 1;
4677
+ if (!preserveData) {
4678
+ this.session = undefined;
4679
+ }
4680
+ this.projections.clear();
4681
+ for (const entry of this.entries.values()) {
4682
+ if (!preserveData) {
4683
+ entry.base = undefined;
4684
+ entry.identity = undefined;
4685
+ }
4686
+ entry.promise = undefined;
4687
+ entry.stale = true;
4688
+ entry.version += 1;
4689
+ entry.snapshot = { data: entry.base, error: null, isFetching: false };
4690
+ this.publish(entry);
4691
+ }
4692
+ }
4693
+ dispose() {
4694
+ this.epoch += 1;
4695
+ for (const entry of this.entries.values()) {
4696
+ entry.listeners.clear();
4697
+ }
4698
+ this.entries.clear();
4699
+ this.requests = [];
4700
+ this.projections.clear();
4701
+ this.listeners.clear();
4702
+ }
4703
+ setError(url, error) {
4704
+ const entry = this.entry(url);
4705
+ entry.base = undefined;
4706
+ entry.stale = false;
4707
+ entry.version += 1;
4708
+ entry.snapshot = { data: undefined, error, isFetching: false };
4709
+ for (const projection of this.projections) {
4710
+ projection.transforms.delete(entry);
4711
+ }
4712
+ this.publish(entry);
4713
+ }
4675
4714
  version(url) {
4676
4715
  return this.entry(url).version;
4677
4716
  }
@@ -4713,7 +4752,7 @@ class QueryStore {
4713
4752
  const { epoch } = this;
4714
4753
  entry.snapshot = { ...entry.snapshot, isFetching: true };
4715
4754
  this.publish(entry);
4716
- entry.promise = Promise.resolve().then(() => entry.load?.()).then((result) => {
4755
+ const promise = Promise.resolve().then(() => entry.load?.()).then((result) => {
4717
4756
  if (!result || epoch !== this.epoch || version !== entry.version || this.pending(entry)) {
4718
4757
  return;
4719
4758
  }
@@ -4727,6 +4766,9 @@ class QueryStore {
4727
4766
  entry.snapshot = { ...entry.snapshot, error };
4728
4767
  }
4729
4768
  }).finally(() => {
4769
+ if (entry.promise !== promise) {
4770
+ return;
4771
+ }
4730
4772
  entry.promise = undefined;
4731
4773
  entry.snapshot = { ...entry.snapshot, isFetching: false };
4732
4774
  this.publish(entry);
@@ -4734,13 +4776,14 @@ class QueryStore {
4734
4776
  this.fetch(url);
4735
4777
  }
4736
4778
  });
4737
- return entry.promise;
4779
+ entry.promise = promise;
4780
+ return promise;
4738
4781
  }
4739
4782
  invalidate(identities) {
4740
4783
  const tags = new Set(identities.map(queryTag));
4741
4784
  let affected = false;
4742
4785
  for (const [url, entry] of this.entries) {
4743
- if (entry.identity && queryTags(entry.identity).some((tag) => tags.has(tag))) {
4786
+ if (entry.identity && queryTags(entry.identity).some((tag) => tags.has(tag)) || !entry.identity && entry.load && identities.length > 0) {
4744
4787
  affected = true;
4745
4788
  this.invalidateEntry(url, entry);
4746
4789
  }
@@ -5061,16 +5104,16 @@ var init_page_cache_state = __esm(() => {
5061
5104
  }));
5062
5105
  });
5063
5106
 
5064
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
5107
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/error-brand-D4i1NkSd.mjs
5065
5108
  function isEvlogError(error) {
5066
5109
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
5067
5110
  }
5068
5111
  var evlogErrorBrand;
5069
- var init_error_brand_D0_DCPvr = __esm(() => {
5112
+ var init_error_brand_D4i1NkSd = __esm(() => {
5070
5113
  evlogErrorBrand = Symbol.for("evlog.error.brand");
5071
5114
  });
5072
5115
 
5073
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/utils.mjs
5116
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/utils.mjs
5074
5117
  function elapsedMs(startTime) {
5075
5118
  return Math.max(0, Date.now() - startTime);
5076
5119
  }
@@ -5211,7 +5254,7 @@ function readErrorField(error, key) {
5211
5254
  }
5212
5255
  var LEVEL_ORDER, colors, levelColorMap, cssColors, cssLevelColorMap, SENSITIVE_HEADERS, SENSITIVE_HEADER_SET, patternCache, _isoDate, _isoCachedSecond = -1, _isoCachedPrefix = "";
5213
5256
  var init_utils = __esm(() => {
5214
- init_error_brand_D0_DCPvr();
5257
+ init_error_brand_D4i1NkSd();
5215
5258
  LEVEL_ORDER = {
5216
5259
  trace: 0,
5217
5260
  debug: 0,
@@ -5271,7 +5314,7 @@ var init_utils = __esm(() => {
5271
5314
  _isoDate = /* @__PURE__ */ new Date;
5272
5315
  });
5273
5316
 
5274
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/globalRegistry--27hBAWF.mjs
5317
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/globalRegistry-DxlJ7DCO.mjs
5275
5318
  function logPluginError(name, hook, err) {
5276
5319
  console.error(`[evlog/${name}] ${hook} failed:`, err);
5277
5320
  }
@@ -5434,7 +5477,7 @@ function getSharedStorage(id, create) {
5434
5477
  return storage;
5435
5478
  }
5436
5479
  var emptyRunner, EVLOG_MAJOR = 2, REGISTRY_KEY, MAJORS_KEY, globalConfig;
5437
- var init_globalRegistry_27hBAWF = __esm(() => {
5480
+ var init_globalRegistry_DxlJ7DCO = __esm(() => {
5438
5481
  init_utils();
5439
5482
  emptyRunner = createPluginRunner([]);
5440
5483
  REGISTRY_KEY = Symbol.for(`evlog.registry.v${EVLOG_MAJOR}`);
@@ -5442,7 +5485,7 @@ var init_globalRegistry_27hBAWF = __esm(() => {
5442
5485
  globalConfig = getRegistry().config;
5443
5486
  });
5444
5487
 
5445
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/pretty-error-CRPxjp4p.mjs
5488
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/pretty-error-DnkXIALi.mjs
5446
5489
  function pushTreeSpacer(children) {
5447
5490
  children.push(PRETTY_ERROR_TREE_SPACER);
5448
5491
  }
@@ -5734,14 +5777,14 @@ function buildErrorEntries(error, options = {}) {
5734
5777
  }];
5735
5778
  }
5736
5779
  var snippetReader = null, PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__", SKIP_PATH_RE, SKIP_FRAME_PATH_RE, SKIP_FRAME_FN_RE, GUIDANCE_WRAP_WIDTH = 76, GUIDANCE_CONTINUATION = " ";
5737
- var init_pretty_error_CRPxjp4p = __esm(() => {
5780
+ var init_pretty_error_DnkXIALi = __esm(() => {
5738
5781
  init_utils();
5739
5782
  SKIP_PATH_RE = /(?:^|[/\\])(?:node_modules|\.nuxt|\.next|\.output)(?:[/\\]|$)/;
5740
5783
  SKIP_FRAME_PATH_RE = /(?:^|[/\\])(?:packages[/\\]evlog|evlog[/\\](?:dist|src))(?:[/\\]|$)/;
5741
5784
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
5742
5785
  });
5743
5786
 
5744
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
5787
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/dev-terminal-CDXEC6Wl.mjs
5745
5788
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
5746
5789
  const compact = partial.compact ?? (inDev && pretty);
5747
5790
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -5776,7 +5819,7 @@ function resolveDevTerminal(input = {}) {
5776
5819
  };
5777
5820
  }
5778
5821
  var DEV_PRESETS;
5779
- var init_dev_terminal_Brarc6vc = __esm(() => {
5822
+ var init_dev_terminal_CDXEC6Wl = __esm(() => {
5780
5823
  init_utils();
5781
5824
  DEV_PRESETS = {
5782
5825
  evlog: {
@@ -5794,7 +5837,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
5794
5837
  };
5795
5838
  });
5796
5839
 
5797
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
5840
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/wideEventChannel-BABjYpvc.mjs
5798
5841
  function hasWideEventPublisher() {
5799
5842
  return publisher !== null;
5800
5843
  }
@@ -5808,9 +5851,9 @@ function publishWideEvent(event) {
5808
5851
  }
5809
5852
  }
5810
5853
  var publisher = null;
5811
- var init_wideEventChannel_BUDW48oP = () => {};
5854
+ var init_wideEventChannel_BABjYpvc = () => {};
5812
5855
 
5813
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/serialize-error-DHkLgVsh.mjs
5856
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/serialize-error-CHmRO35i.mjs
5814
5857
  function payloadFieldsHiddenBy(error) {
5815
5858
  const { toJSON } = error;
5816
5859
  if (typeof toJSON !== "function" || isEvlogError(error))
@@ -5910,8 +5953,12 @@ function createErrorSerializer(formatStack = (stack) => stack) {
5910
5953
  changed = true;
5911
5954
  }
5912
5955
  }
5913
- if (changed)
5956
+ if (changed) {
5957
+ const proto = Object.getPrototypeOf(value);
5914
5958
  copy = Object.fromEntries(entries);
5959
+ if (proto !== Object.prototype)
5960
+ Object.setPrototypeOf(copy, proto);
5961
+ }
5915
5962
  }
5916
5963
  ancestors.delete(value);
5917
5964
  return copy ?? value;
@@ -5922,8 +5969,8 @@ function createErrorSerializer(formatStack = (stack) => stack) {
5922
5969
  };
5923
5970
  }
5924
5971
  var ERROR_FIELDS, NONE, H3_INPUT_FIELDS;
5925
- var init_serialize_error_DHkLgVsh = __esm(() => {
5926
- init_error_brand_D0_DCPvr();
5972
+ var init_serialize_error_CHmRO35i = __esm(() => {
5973
+ init_error_brand_D4i1NkSd();
5927
5974
  init_utils();
5928
5975
  ERROR_FIELDS = [
5929
5976
  "code",
@@ -5951,7 +5998,7 @@ var init_serialize_error_DHkLgVsh = __esm(() => {
5951
5998
  };
5952
5999
  });
5953
6000
 
5954
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
6001
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/headers-DpB4nPAJ.mjs
5955
6002
  function extractSafeHeaders(headers) {
5956
6003
  const raw = {};
5957
6004
  headers.forEach((value, key) => {
@@ -5968,11 +6015,11 @@ function extractSafeNodeHeaders(headers) {
5968
6015
  }
5969
6016
  return filterSafeHeaders(raw);
5970
6017
  }
5971
- var init_headers_Bx1ieR_m = __esm(() => {
6018
+ var init_headers_DpB4nPAJ = __esm(() => {
5972
6019
  init_utils();
5973
6020
  });
5974
6021
 
5975
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/audit-C5ZK3s-B.mjs
6022
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/audit-D3F0XCdQ.mjs
5976
6023
  function normalizeRedactPathPattern(pattern) {
5977
6024
  if (!pattern.includes("*") && !pattern.includes("."))
5978
6025
  return `**.${pattern}`;
@@ -6122,7 +6169,8 @@ function resolveRedactConfig(input) {
6122
6169
  ...input,
6123
6170
  _pathMatchers: compileRedactPathMatchers(input.paths)
6124
6171
  };
6125
- const maskers = Array.isArray(input.builtins) ? input.builtins.filter((name) => (name in builtinPatterns)).map((name) => builtinPatterns[name]).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
6172
+ const { builtins } = input;
6173
+ const maskers = Array.isArray(builtins) ? Object.keys(builtinPatterns).filter((name) => builtins.includes(name)).map((name) => builtinPatterns[name]).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
6126
6174
  return {
6127
6175
  ...input,
6128
6176
  _maskers: maskers,
@@ -6289,8 +6337,6 @@ function setField(target, key, value) {
6289
6337
  }
6290
6338
  function writableChild(target, key) {
6291
6339
  const child = target[key];
6292
- if (!isPlainRecord(child))
6293
- return child;
6294
6340
  const copy = { ...child };
6295
6341
  const { toJSON } = child;
6296
6342
  if (typeof toJSON === "function" && !Object.hasOwn(copy, "toJSON"))
@@ -6311,7 +6357,7 @@ function mergeInto(target, source) {
6311
6357
  const targetVal = key === "__proto__" && !Object.hasOwn(target, key) ? undefined : target[key];
6312
6358
  if (sourceVal === targetVal)
6313
6359
  continue;
6314
- if (isPlainObject$1(sourceVal) && isPlainObject$1(targetVal))
6360
+ if (isPlainRecord(sourceVal) && isPlainRecord(targetVal))
6315
6361
  mergeInto(writableChild(target, key), sourceVal);
6316
6362
  else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
6317
6363
  setField(target, key, [...targetVal, ...sourceVal]);
@@ -6896,7 +6942,7 @@ function createLogger(initialContext = {}, internalOptions) {
6896
6942
  const deferDrain = internalOptions?._deferDrain ?? false;
6897
6943
  const waitUntil = internalOptions?.waitUntil;
6898
6944
  const startTime = Date.now();
6899
- const context = { ...initialContext };
6945
+ const context = { ...serializeErrorsIn(initialContext) };
6900
6946
  let hasError = false;
6901
6947
  let hasFatal = false;
6902
6948
  let hasWarn = false;
@@ -6918,7 +6964,7 @@ function createLogger(initialContext = {}, internalOptions) {
6918
6964
  return;
6919
6965
  }
6920
6966
  const fields = buildAuditFields(input);
6921
- if (!isPlainObject$1(context.audit))
6967
+ if (!isPlainRecord(context.audit))
6922
6968
  context.audit = fields;
6923
6969
  else
6924
6970
  mergeInto(writableChild(context, "audit"), fields);
@@ -6964,7 +7010,7 @@ function createLogger(initialContext = {}, internalOptions) {
6964
7010
  if (errorContext)
6965
7011
  mergeFields(context, errorContext);
6966
7012
  const errorObj = serializeError(err);
6967
- if (isPlainObject$1(context.error))
7013
+ if (isPlainRecord(context.error))
6968
7014
  mergeInto(writableChild(context, "error"), errorObj);
6969
7015
  else
6970
7016
  context.error = errorObj;
@@ -7053,7 +7099,7 @@ function createLogger(initialContext = {}, internalOptions) {
7053
7099
  return null;
7054
7100
  }
7055
7101
  if (overrides) {
7056
- const obj = overrides;
7102
+ const obj = serializeErrorsIn(overrides);
7057
7103
  for (const key in obj)
7058
7104
  if (key !== "_forceKeep" && key !== "_durationMs")
7059
7105
  context[key] = obj[key];
@@ -7183,14 +7229,25 @@ function finalizeAudit(event) {
7183
7229
  _testCollector?.(decorated, event);
7184
7230
  }
7185
7231
  var DEFAULT_REPLACEMENT = "[REDACTED]", builtinPatterns, SECRET_KEY, globallyRedacted, serializeError, serializeErrorsIn, nativeStdoutWrite, POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).", pendingDrainState, state, CAPTURED_LINE_MAX_LENGTH = 160, CAPTURED_MAX_LINES = 8, _log, noopLogger, _testCollector = null;
7186
- var init_audit_C5ZK3s_B = __esm(() => {
7232
+ var init_audit_D3F0XCdQ = __esm(() => {
7187
7233
  init_utils();
7188
- init_globalRegistry_27hBAWF();
7189
- init_pretty_error_CRPxjp4p();
7190
- init_dev_terminal_Brarc6vc();
7191
- init_wideEventChannel_BUDW48oP();
7192
- init_serialize_error_DHkLgVsh();
7234
+ init_globalRegistry_DxlJ7DCO();
7235
+ init_pretty_error_DnkXIALi();
7236
+ init_dev_terminal_CDXEC6Wl();
7237
+ init_wideEventChannel_BABjYpvc();
7238
+ init_serialize_error_CHmRO35i();
7193
7239
  builtinPatterns = {
7240
+ bearer: {
7241
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
7242
+ mask: () => "Bearer ***"
7243
+ },
7244
+ iban: {
7245
+ pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
7246
+ mask: (m) => {
7247
+ const clean = m.replace(/[\s-]/g, "");
7248
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
7249
+ }
7250
+ },
7194
7251
  creditCard: {
7195
7252
  pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
7196
7253
  mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
@@ -7224,17 +7281,6 @@ var init_audit_C5ZK3s_B = __esm(() => {
7224
7281
  jwt: {
7225
7282
  pattern: /\beyJ(?:(?!-eyJ)[\w-])*\.[\w-]*\.[\w-]*\b/g,
7226
7283
  mask: () => "eyJ***.***"
7227
- },
7228
- bearer: {
7229
- pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
7230
- mask: () => "Bearer ***"
7231
- },
7232
- iban: {
7233
- pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
7234
- mask: (m) => {
7235
- const clean = m.replace(/[\s-]/g, "");
7236
- return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
7237
- }
7238
7284
  }
7239
7285
  };
7240
7286
  SECRET_KEY = /(?:password|passwd|secret|token)$/i;
@@ -7272,12 +7318,12 @@ var init_audit_C5ZK3s_B = __esm(() => {
7272
7318
  initLogger(__EVLOG_CONFIG__);
7273
7319
  });
7274
7320
 
7275
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/index.mjs
7321
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/index.mjs
7276
7322
  var init_dist = __esm(() => {
7277
- init_audit_C5ZK3s_B();
7323
+ init_audit_D3F0XCdQ();
7278
7324
  });
7279
7325
 
7280
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/errors-CL8dDgIi.mjs
7326
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/errors-Cl1GMJa_.mjs
7281
7327
  function extractErrorStatus(error) {
7282
7328
  if (error === null || typeof error !== "object")
7283
7329
  return 500;
@@ -7285,9 +7331,9 @@ function extractErrorStatus(error) {
7285
7331
  const status = Number(raw);
7286
7332
  return Number.isFinite(status) ? status : 500;
7287
7333
  }
7288
- var init_errors_CL8dDgIi = () => {};
7334
+ var init_errors_Cl1GMJa_ = () => {};
7289
7335
 
7290
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/middleware-CmfmqXwL.mjs
7336
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/middleware-fmopETyt.mjs
7291
7337
  function shouldLog(path, include, exclude) {
7292
7338
  if (exclude && exclude.length > 0) {
7293
7339
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -7595,12 +7641,12 @@ function createMiddlewareLogger(options) {
7595
7641
  };
7596
7642
  }
7597
7643
  var noopResult, runnerCache;
7598
- var init_middleware_CmfmqXwL = __esm(() => {
7644
+ var init_middleware_fmopETyt = __esm(() => {
7599
7645
  init_utils();
7600
- init_audit_C5ZK3s_B();
7601
- init_globalRegistry_27hBAWF();
7602
- init_wideEventChannel_BUDW48oP();
7603
- init_errors_CL8dDgIi();
7646
+ init_audit_D3F0XCdQ();
7647
+ init_globalRegistry_DxlJ7DCO();
7648
+ init_wideEventChannel_BABjYpvc();
7649
+ init_errors_Cl1GMJa_();
7604
7650
  noopResult = {
7605
7651
  logger: noopLogger,
7606
7652
  finish: () => Promise.resolve(null),
@@ -7610,7 +7656,7 @@ var init_middleware_CmfmqXwL = __esm(() => {
7610
7656
  runnerCache = /* @__PURE__ */ new WeakMap;
7611
7657
  });
7612
7658
 
7613
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/integration-BDRiSZGp.mjs
7659
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/integration-D9IUwqvW.mjs
7614
7660
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
7615
7661
  parent.fork = (label, fn) => forkBackgroundLogger({
7616
7662
  storage,
@@ -7714,14 +7760,14 @@ function defineFrameworkIntegration(spec) {
7714
7760
  };
7715
7761
  } };
7716
7762
  }
7717
- var init_integration_BDRiSZGp = __esm(() => {
7718
- init_audit_C5ZK3s_B();
7719
- init_headers_Bx1ieR_m();
7720
- init_errors_CL8dDgIi();
7721
- init_middleware_CmfmqXwL();
7763
+ var init_integration_D9IUwqvW = __esm(() => {
7764
+ init_audit_D3F0XCdQ();
7765
+ init_headers_DpB4nPAJ();
7766
+ init_errors_Cl1GMJa_();
7767
+ init_middleware_fmopETyt();
7722
7768
  });
7723
7769
 
7724
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/toolkit/storage.mjs
7770
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/toolkit/storage.mjs
7725
7771
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
7726
7772
  function createLoggerStorage(contextHint, id = contextHint) {
7727
7773
  const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
@@ -7737,13 +7783,13 @@ function createLoggerStorage(contextHint, id = contextHint) {
7737
7783
  };
7738
7784
  }
7739
7785
  var init_storage = __esm(() => {
7740
- init_globalRegistry_27hBAWF();
7786
+ init_globalRegistry_DxlJ7DCO();
7741
7787
  });
7742
7788
 
7743
- // ../../node_modules/.bun/evlog@2.33.0+f0b9d80252a09446/node_modules/evlog/dist/toolkit.mjs
7789
+ // ../../node_modules/.bun/evlog@2.34.0+86bc96d63db325a2/node_modules/evlog/dist/toolkit.mjs
7744
7790
  var init_toolkit = __esm(() => {
7745
- init_middleware_CmfmqXwL();
7746
- init_integration_BDRiSZGp();
7791
+ init_middleware_fmopETyt();
7792
+ init_integration_D9IUwqvW();
7747
7793
  init_storage();
7748
7794
  });
7749
7795
 
@@ -8446,12 +8492,7 @@ function getSyncPath() {
8446
8492
  return currentInstance().syncPath;
8447
8493
  }
8448
8494
  function syncRuntimeOptions(sync) {
8449
- return {
8450
- adapter: sync.adapter,
8451
- notifier: sync.notifier,
8452
- principal: sync.principal,
8453
- secret: sync.secret
8454
- };
8495
+ return sync;
8455
8496
  }
8456
8497
  var SYNC_DEFAULT_PATH = "/_furin/sync";
8457
8498
  var init_config = __esm(() => {
@@ -10293,6 +10334,112 @@ function validateRouteChain(chain, root, pagePath) {
10293
10334
  }
10294
10335
  }
10295
10336
 
10337
+ // src/client/sync-catch-up.ts
10338
+ function changeInvalidations(change) {
10339
+ const paths = [];
10340
+ const queries = [...change.queries ?? []];
10341
+ for (const entry of change.invalidations) {
10342
+ if (typeof entry === "string") {
10343
+ const trimmed = entry.trim();
10344
+ const type = trimmed.endsWith(":layout") ? "layout" : "page";
10345
+ const path = trimmed.replace(LAYOUT_SUFFIX_RE, "");
10346
+ paths.push(encodeInvalidationEntry(path, type));
10347
+ } else if (entry.kind === "path") {
10348
+ paths.push(encodeInvalidationEntry(entry.path, entry.type));
10349
+ } else {
10350
+ for (const tag of entry.tags) {
10351
+ const identity = queryFromTag(tag);
10352
+ if (identity) {
10353
+ queries.push(identity);
10354
+ } else {
10355
+ paths.push("/:layout");
10356
+ }
10357
+ }
10358
+ }
10359
+ }
10360
+ return { paths, queries };
10361
+ }
10362
+ function createSyncCatchUp(options) {
10363
+ let currentCursor;
10364
+ let running;
10365
+ let requested = false;
10366
+ let lastReset = Number.NEGATIVE_INFINITY;
10367
+ let pendingReset;
10368
+ let closed = false;
10369
+ const refreshAfterReset = () => {
10370
+ pendingReset = undefined;
10371
+ lastReset = Date.now();
10372
+ options.onReset?.();
10373
+ options.onInvalidations(["/:layout"]);
10374
+ };
10375
+ const scheduleResetRefresh = () => {
10376
+ if (pendingReset) {
10377
+ return;
10378
+ }
10379
+ const wait = lastReset + RESET_REFRESH_INTERVAL_MS - Date.now();
10380
+ if (wait <= 0) {
10381
+ refreshAfterReset();
10382
+ } else {
10383
+ pendingReset = setTimeout(refreshAfterReset, wait);
10384
+ }
10385
+ };
10386
+ const readUntilCurrent = async () => {
10387
+ do {
10388
+ requested = false;
10389
+ let page;
10390
+ do {
10391
+ page = await options.fetchPage(currentCursor ?? "0");
10392
+ if (closed) {
10393
+ return;
10394
+ }
10395
+ if (page.reset) {
10396
+ currentCursor = page.cursor;
10397
+ scheduleResetRefresh();
10398
+ break;
10399
+ }
10400
+ for (const change of page.changes) {
10401
+ applyChange(change);
10402
+ }
10403
+ currentCursor = page.cursor;
10404
+ } while (page.hasMore);
10405
+ } while (requested && !closed);
10406
+ };
10407
+ const applyChange = (change) => {
10408
+ const { paths, queries } = changeInvalidations(change);
10409
+ options.onInvalidations(paths);
10410
+ if (queries.length > 0) {
10411
+ options.onQueries?.(queries);
10412
+ }
10413
+ };
10414
+ return {
10415
+ catchUp() {
10416
+ if (closed) {
10417
+ return Promise.resolve();
10418
+ }
10419
+ requested = true;
10420
+ if (!running) {
10421
+ running = readUntilCurrent().finally(() => {
10422
+ running = undefined;
10423
+ });
10424
+ }
10425
+ return running;
10426
+ },
10427
+ cursor: () => currentCursor,
10428
+ close() {
10429
+ closed = true;
10430
+ clearTimeout(pendingReset);
10431
+ },
10432
+ seed(cursor) {
10433
+ currentCursor ??= cursor;
10434
+ }
10435
+ };
10436
+ }
10437
+ var LAYOUT_SUFFIX_RE, RESET_REFRESH_INTERVAL_MS = 1000;
10438
+ var init_sync_catch_up = __esm(() => {
10439
+ init_invalidation_header();
10440
+ LAYOUT_SUFFIX_RE = /:layout$/;
10441
+ });
10442
+
10296
10443
  // src/shared/navigation-data.ts
10297
10444
  function stripNavigationDataSearch(search) {
10298
10445
  const entries = search.slice(1).split("&");
@@ -11152,7 +11299,7 @@ var resolveModuleHrefs = () => [], resolveNonce = () => {
11152
11299
  var init_client_module = () => {};
11153
11300
 
11154
11301
  // src/client/browser-events-runtime.ts
11155
- function installBrowserEventsRuntime(browser, moduleUrlValue, transport) {
11302
+ function installBrowserEventsRuntime(browser, moduleUrlValue, transport, sync) {
11156
11303
  const runtimeKey = Symbol.for("furin.browser-events.runtime");
11157
11304
  const runtimeWindow = browser;
11158
11305
  if (runtimeWindow[runtimeKey]) {
@@ -11171,7 +11318,8 @@ function installBrowserEventsRuntime(browser, moduleUrlValue, transport) {
11171
11318
  return false;
11172
11319
  }
11173
11320
  if (candidate.channel === "sync") {
11174
- return typeof candidate.data.cursor === "string";
11321
+ const data = candidate.data;
11322
+ return typeof data.cursor === "string" || data.context === "changed";
11175
11323
  }
11176
11324
  return candidate.channel === "diagnostic" || candidate.channel === "devtools";
11177
11325
  };
@@ -11203,6 +11351,9 @@ function installBrowserEventsRuntime(browser, moduleUrlValue, transport) {
11203
11351
  let eventSource;
11204
11352
  let status = "connecting";
11205
11353
  let suspended = false;
11354
+ let authPaused = false;
11355
+ let authorized = !sync;
11356
+ let authenticating;
11206
11357
  const updateStatus = (next) => {
11207
11358
  if (status === next) {
11208
11359
  return;
@@ -11240,7 +11391,63 @@ function installBrowserEventsRuntime(browser, moduleUrlValue, transport) {
11240
11391
  }
11241
11392
  } catch {}
11242
11393
  };
11394
+ const retry = () => {
11395
+ if (suspended || authPaused || reconnectTimer !== undefined) {
11396
+ return;
11397
+ }
11398
+ updateStatus("reconnecting");
11399
+ const baseDelay = Math.min(250 * 2 ** reconnectAttempt, maxReconnectDelayMs);
11400
+ const delay = transport === "sse" ? baseDelay : Math.min(Math.round(baseDelay * (0.8 + Math.random() * 0.4)), maxReconnectDelayMs);
11401
+ reconnectAttempt += 1;
11402
+ reconnectTimer = browser.setTimeout(() => {
11403
+ reconnectTimer = undefined;
11404
+ connect();
11405
+ }, delay);
11406
+ };
11407
+ const authenticate = async () => {
11408
+ if (authenticating) {
11409
+ return;
11410
+ }
11411
+ const current = new AbortController;
11412
+ authenticating = current;
11413
+ try {
11414
+ const response = await browser.fetch(eventsUrl(), {
11415
+ method: "HEAD",
11416
+ credentials: "same-origin",
11417
+ cache: "no-store",
11418
+ signal: current.signal
11419
+ });
11420
+ if (current.signal.aborted) {
11421
+ return;
11422
+ }
11423
+ if (response.status === 401 || response.status === 403) {
11424
+ dispatch({ channel: "sync", data: { context: "changed" }, version: protocolVersion });
11425
+ setSyncAuthentication(false);
11426
+ return;
11427
+ }
11428
+ if (!response.ok) {
11429
+ throw new Error(`Sync authentication failed: ${response.status}`);
11430
+ }
11431
+ authorized = true;
11432
+ connect();
11433
+ } catch {
11434
+ if (!current.signal.aborted) {
11435
+ retry();
11436
+ }
11437
+ } finally {
11438
+ if (authenticating === current) {
11439
+ authenticating = undefined;
11440
+ }
11441
+ }
11442
+ };
11243
11443
  const connect = () => {
11444
+ if (suspended || authPaused) {
11445
+ return;
11446
+ }
11447
+ if (!authorized) {
11448
+ authenticate();
11449
+ return;
11450
+ }
11244
11451
  if (transport === "sse") {
11245
11452
  if (suspended || eventSource !== undefined && eventSource.readyState !== runtimeWindow.EventSource.CLOSED) {
11246
11453
  return;
@@ -11261,12 +11468,8 @@ function installBrowserEventsRuntime(browser, moduleUrlValue, transport) {
11261
11468
  return;
11262
11469
  }
11263
11470
  eventSource = undefined;
11264
- const delay = Math.min(250 * 2 ** reconnectAttempt, maxReconnectDelayMs);
11265
- reconnectAttempt += 1;
11266
- reconnectTimer = browser.setTimeout(() => {
11267
- reconnectTimer = undefined;
11268
- connect();
11269
- }, delay);
11471
+ authorized = !sync;
11472
+ retry();
11270
11473
  });
11271
11474
  return;
11272
11475
  }
@@ -11288,19 +11491,16 @@ function installBrowserEventsRuntime(browser, moduleUrlValue, transport) {
11288
11491
  if (suspended || reconnectTimer !== undefined) {
11289
11492
  return;
11290
11493
  }
11291
- updateStatus("reconnecting");
11292
- const baseDelay = Math.min(250 * 2 ** reconnectAttempt, maxReconnectDelayMs);
11293
- const delay = Math.min(Math.round(baseDelay * (0.8 + Math.random() * 0.4)), maxReconnectDelayMs);
11294
- reconnectAttempt += 1;
11295
- reconnectTimer = browser.setTimeout(() => {
11296
- reconnectTimer = undefined;
11297
- connect();
11298
- }, delay);
11494
+ authorized = !sync;
11495
+ retry();
11299
11496
  });
11300
11497
  connection.addEventListener("error", () => connection.close());
11301
11498
  };
11302
11499
  const suspend = () => {
11303
11500
  suspended = true;
11501
+ authenticating?.abort();
11502
+ authenticating = undefined;
11503
+ authorized = !sync;
11304
11504
  if (reconnectTimer !== undefined) {
11305
11505
  browser.clearTimeout(reconnectTimer);
11306
11506
  reconnectTimer = undefined;
@@ -11311,16 +11511,32 @@ function installBrowserEventsRuntime(browser, moduleUrlValue, transport) {
11311
11511
  eventSource = undefined;
11312
11512
  };
11313
11513
  const resume = () => {
11514
+ if (authPaused) {
11515
+ return;
11516
+ }
11314
11517
  suspended = false;
11315
11518
  if (socket === undefined && eventSource === undefined) {
11316
11519
  updateStatus("connecting");
11317
11520
  }
11318
11521
  connect();
11319
11522
  };
11523
+ const setSyncAuthentication = (valid) => {
11524
+ if (valid) {
11525
+ if (authPaused) {
11526
+ authPaused = false;
11527
+ resume();
11528
+ }
11529
+ } else if (!authPaused) {
11530
+ authPaused = true;
11531
+ suspend();
11532
+ updateStatus("unauthorized");
11533
+ }
11534
+ };
11320
11535
  browser.addEventListener("pagehide", suspend);
11321
11536
  browser.addEventListener("pageshow", resume);
11322
11537
  connect();
11323
11538
  runtimeWindow[runtimeKey] = {
11539
+ setSyncAuthentication,
11324
11540
  subscribe(channel, listener) {
11325
11541
  const channelListeners = listeners[channel];
11326
11542
  channelListeners.add(listener);
@@ -11336,133 +11552,73 @@ function installBrowserEventsRuntime(browser, moduleUrlValue, transport) {
11336
11552
  }
11337
11553
  };
11338
11554
  }
11339
- function browserEventsClientSource() {
11340
- return `(${installBrowserEventsRuntime.toString()})(window, import.meta.url);
11555
+ function browserEventsClientSource(sync) {
11556
+ return `(${installBrowserEventsRuntime.toString()})(window, import.meta.url, undefined, ${sync === true});
11341
11557
  `;
11342
11558
  }
11343
11559
  function browserEventsSseClientSource() {
11344
- return `(${installBrowserEventsRuntime.toString()})(window, import.meta.url, "sse");
11560
+ return `(${installBrowserEventsRuntime.toString()})(window, import.meta.url, "sse", true);
11345
11561
  `;
11346
11562
  }
11347
11563
 
11348
11564
  // src/shared/browser-events.ts
11349
11565
  var BROWSER_EVENT_PROTOCOL_VERSION = 1;
11350
11566
 
11351
- // src/server/sync/principal-journal.ts
11352
- function configurePrincipalSecret(adapter, secret, development) {
11353
- if (secret !== undefined && (typeof secret !== "string" || secret.length < MIN_SECRET_LENGTH)) {
11354
- throw new Error(`[furin] sync.secret must be a string of at least ${MIN_SECRET_LENGTH} characters.`);
11355
- }
11356
- if (principalSecrets.has(adapter)) {
11357
- if (principalSecrets.get(adapter) !== secret) {
11358
- throw new Error("[furin] Sync runtimes sharing a SyncAdapter must use the same secret.");
11359
- }
11567
+ // src/server/sync/connection.ts
11568
+ async function verifiedSyncPrincipal(sync, context) {
11569
+ try {
11570
+ const principal = await sync.principal(context);
11571
+ return principal.length > 0 ? principal : undefined;
11572
+ } catch {
11360
11573
  return;
11361
11574
  }
11362
- principalSecrets.set(adapter, secret);
11363
- if (secret === undefined && !development) {
11364
- console.warn("[furin] sync.secret is not set: principal hashes sent to browsers and stored in the sync journal are unkeyed SHA-256 and can be reversed with a dictionary. Set sync.secret to a random value of at least 32 characters.");
11365
- }
11366
11575
  }
11367
- function principalHash(adapter, principal) {
11368
- const secret = principalSecrets.get(adapter);
11369
- const hasher = secret === undefined ? new Bun.CryptoHasher("sha256") : new Bun.CryptoHasher("sha256", secret);
11370
- return hasher.update(principal).digest("hex");
11371
- }
11372
- async function readPrincipalChanges(adapter, input, principal) {
11373
- if (principalJournals.has(adapter)) {
11374
- const page = await adapter.readChanges(input);
11375
- const hash = principalHash(adapter, principal);
11376
- if (page.changes.every((change) => changePrincipals.get(change) === hash)) {
11377
- return page;
11378
- }
11576
+ function releaseLease(lease) {
11577
+ try {
11578
+ lease?.release();
11579
+ } catch (error) {
11580
+ _log.warn({ action: "sync_connection_release_failed", error: String(error) });
11379
11581
  }
11380
- const cursor = await adapter.currentCursor();
11381
- return {
11382
- changes: [],
11383
- cursor,
11384
- hasMore: false,
11385
- reset: input.after !== undefined && input.after !== cursor
11386
- };
11387
11582
  }
11388
- var MIN_SECRET_LENGTH = 32, principalJournals, changePrincipals, principalSecrets;
11389
- var init_principal_journal = __esm(() => {
11390
- principalJournals = new WeakSet;
11391
- changePrincipals = new WeakMap;
11392
- principalSecrets = new WeakMap;
11393
- });
11394
-
11395
- // src/server/sync/queries.ts
11396
- function isMutationMethod(method) {
11397
- return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
11398
- }
11399
- function markInternalRead(request) {
11400
- internalReads.add(request);
11401
- }
11402
- function isInternalRead(request) {
11403
- return internalReads.has(request);
11404
- }
11405
- function sealInvalidations(request) {
11406
- sealed.add(request);
11407
- }
11408
- function requestInvalidate(request) {
11409
- return (target, params) => {
11410
- if (!isMutationMethod(request.method)) {
11411
- throw new Error(`[furin] invalidate() was called while handling a ${request.method}: only a mutation invalidates.`);
11412
- }
11413
- if (sealed.has(request)) {
11414
- if (IS_DEV) {
11415
- throw new Error("[furin] invalidate() was called after mutation() resolved: call it inside the mutation() callback to commit it with the transaction.");
11416
- }
11417
- return;
11418
- }
11419
- let invalidations = collected.get(request);
11420
- if (!invalidations) {
11421
- invalidations = { queries: [], rules: [] };
11422
- collected.set(request, invalidations);
11423
- }
11424
- if (typeof target !== "string") {
11425
- invalidations.rules.push(target);
11426
- return;
11583
+ function createSyncConnectionLifetime(sync, context, changed) {
11584
+ let closed = false;
11585
+ let lease;
11586
+ const onAbort = () => {
11587
+ if (!closed) {
11588
+ changed();
11427
11589
  }
11428
- const identity = { id: target, scope: params ?? {} };
11429
- queryTag(identity);
11430
- invalidations.queries.push(identity);
11431
11590
  };
11432
- }
11433
- function urlIdentity(context) {
11434
- const scope = Object.fromEntries(Object.entries(context.params ?? {}).filter(([, value]) => value !== undefined));
11435
- return { id: context.route ?? context.path, scope };
11436
- }
11437
- function resolveSyncInvalidations(context) {
11438
- const invalidations = collected.get(context.request);
11439
- return [
11440
- ...invalidations?.rules ?? [],
11441
- { tags: [...invalidations?.queries ?? [], urlIdentity(context)].map(queryTag) }
11442
- ];
11443
- }
11444
- function appendQueryInvalidations(input, context) {
11445
- if (input === undefined) {
11446
- return;
11447
- }
11448
- const queries = [];
11449
- for (const rule of Array.isArray(input) ? input : [input]) {
11450
- for (const tag of rule.tags ?? []) {
11451
- const identity = queryFromTag(tag);
11452
- if (identity) {
11453
- queries.push(identity);
11591
+ return {
11592
+ async acquire() {
11593
+ if (closed) {
11594
+ return;
11595
+ }
11596
+ const acquired = await sync.connection?.(context);
11597
+ if (closed) {
11598
+ releaseLease(acquired);
11599
+ return;
11600
+ }
11601
+ lease = acquired;
11602
+ lease?.signal.addEventListener("abort", onAbort, { once: true });
11603
+ if (lease?.signal.aborted) {
11604
+ onAbort();
11605
+ }
11606
+ },
11607
+ close() {
11608
+ if (closed) {
11609
+ return;
11454
11610
  }
11611
+ closed = true;
11612
+ lease?.signal.removeEventListener("abort", onAbort);
11613
+ releaseLease(lease);
11614
+ lease = undefined;
11455
11615
  }
11456
- }
11457
- if (queries.length > 0) {
11458
- context.set.headers["x-furin-queries"] = serializeQueryHeader(queries);
11459
- }
11616
+ };
11460
11617
  }
11461
- var collected, sealed, internalReads;
11462
- var init_queries = __esm(() => {
11463
- collected = new WeakMap;
11464
- sealed = new WeakSet;
11465
- internalReads = new WeakSet;
11618
+ var LOCAL_SYNC_CONNECTION;
11619
+ var init_connection = __esm(() => {
11620
+ init_dist();
11621
+ LOCAL_SYNC_CONNECTION = Symbol.for("furin.sync.local-connection.v1");
11466
11622
  });
11467
11623
 
11468
11624
  // src/server/sync/notifier.ts
@@ -11557,7 +11713,52 @@ class PollingSyncNotifier {
11557
11713
  }
11558
11714
  }
11559
11715
 
11716
+ // src/server/sync/principal-journal.ts
11717
+ function configurePrincipalSecret(adapter, secret, development) {
11718
+ if (secret !== undefined && (typeof secret !== "string" || secret.length < MIN_SECRET_LENGTH)) {
11719
+ throw new Error(`[furin] sync.secret must be a string of at least ${MIN_SECRET_LENGTH} characters.`);
11720
+ }
11721
+ if (principalSecrets.has(adapter)) {
11722
+ if (principalSecrets.get(adapter) !== secret) {
11723
+ throw new Error("[furin] Sync runtimes sharing a SyncAdapter must use the same secret.");
11724
+ }
11725
+ return;
11726
+ }
11727
+ principalSecrets.set(adapter, secret);
11728
+ if (secret === undefined && !development) {
11729
+ console.warn("[furin] sync.secret is not set: principal hashes sent to browsers and stored in the sync journal are unkeyed SHA-256 and can be reversed with a dictionary. Set sync.secret to a random value of at least 32 characters.");
11730
+ }
11731
+ }
11732
+ function principalHash(adapter, principal) {
11733
+ const secret = principalSecrets.get(adapter);
11734
+ const hasher = secret === undefined ? new Bun.CryptoHasher("sha256") : new Bun.CryptoHasher("sha256", secret);
11735
+ return hasher.update(principal).digest("hex");
11736
+ }
11737
+ async function readPrincipalChanges(adapter, input, principal) {
11738
+ if (principalJournals.has(adapter)) {
11739
+ const page = await adapter.readChanges(input);
11740
+ const hash = principalHash(adapter, principal);
11741
+ if (page.changes.every((change) => changePrincipals.get(change) === hash)) {
11742
+ return page;
11743
+ }
11744
+ }
11745
+ const cursor = await adapter.currentCursor();
11746
+ return {
11747
+ changes: [],
11748
+ cursor,
11749
+ hasMore: false,
11750
+ reset: input.after !== undefined && input.after !== cursor
11751
+ };
11752
+ }
11753
+ var MIN_SECRET_LENGTH = 32, principalJournals, changePrincipals, principalSecrets;
11754
+ var init_principal_journal = __esm(() => {
11755
+ principalJournals = new WeakSet;
11756
+ changePrincipals = new WeakMap;
11757
+ principalSecrets = new WeakMap;
11758
+ });
11759
+
11560
11760
  // src/server/sync/runtime.ts
11761
+ import { inAotBuild } from "elysia";
11561
11762
  function publishCursor(runtime, cursor) {
11562
11763
  const alreadyPublished = runtime.adapter.publishesNotifications !== false && runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
11563
11764
  if (!alreadyPublished) {
@@ -11566,32 +11767,135 @@ function publishCursor(runtime, cursor) {
11566
11767
  });
11567
11768
  }
11568
11769
  }
11569
- function resolveSyncRuntime(options, development) {
11570
- if (!development && options.adapter.scope === "process-local") {
11571
- throw new Error("[furin] Production sync cannot use a process-local SyncAdapter.");
11770
+ function prepareSyncRuntime(options, development) {
11771
+ if (inAotBuild()) {
11772
+ return;
11773
+ }
11774
+ if (typeof options.adapter === "function" && !factoryAdapters.has(options)) {
11775
+ const adapter = options.adapter();
11776
+ if (adapter instanceof Promise) {
11777
+ throw new Error("[furin] Sync adapter factories must return an adapter synchronously.");
11778
+ }
11779
+ factoryAdapters.set(options, adapter);
11780
+ }
11781
+ resolveSyncRuntime(options, development);
11782
+ }
11783
+ function resolveSyncRuntime(options, development) {
11784
+ if (inAotBuild()) {
11785
+ throw new Error("[furin] Sync runtime is unavailable during AOT compilation.");
11786
+ }
11787
+ const existingRuntime = runtimes.get(options)?.get(development);
11788
+ if (existingRuntime) {
11789
+ return existingRuntime;
11790
+ }
11791
+ const adapter = typeof options.adapter === "function" ? factoryAdapters.get(options) : options.adapter;
11792
+ if (!adapter) {
11793
+ throw new Error("[furin] Compose furinSync(sync) or furin({ sync }) before using a Sync adapter factory.");
11794
+ }
11795
+ if (!development && adapter.scope === "process-local") {
11796
+ throw new Error("[furin] Production sync cannot use a process-local SyncAdapter.");
11797
+ }
11798
+ configurePrincipalSecret(adapter, options.secret, development);
11799
+ if (options.notifier && adapter.notificationChannel !== undefined && options.notifier.notificationChannel !== undefined && adapter.notificationChannel !== options.notifier.notificationChannel) {
11800
+ throw new Error("[furin] SyncAdapter and SyncNotifier notification channels do not match.");
11801
+ }
11802
+ if (!(options.notifier || development) && adapter.scope === "distributed") {
11803
+ throw new Error("[furin] Distributed production sync requires an explicit SyncNotifier. Configure the adapter notifier or pass PollingSyncNotifier as a compatibility fallback.");
11804
+ }
11805
+ let notifier = options.notifier ?? pollingNotifiers.get(adapter);
11806
+ if (!notifier) {
11807
+ const polling = new PollingSyncNotifier(adapter, POLL_INTERVAL_MS);
11808
+ pollingNotifiers.set(adapter, polling);
11809
+ notifier = polling;
11810
+ }
11811
+ const runtime = { adapter, development, notifier };
11812
+ let modes = runtimes.get(options);
11813
+ if (!modes) {
11814
+ modes = new Map;
11815
+ runtimes.set(options, modes);
11816
+ }
11817
+ modes.set(development, runtime);
11818
+ return runtime;
11819
+ }
11820
+ var POLL_INTERVAL_MS = 250, pollingNotifiers, factoryAdapters, runtimes;
11821
+ var init_runtime = __esm(() => {
11822
+ init_principal_journal();
11823
+ pollingNotifiers = new WeakMap;
11824
+ factoryAdapters = new WeakMap;
11825
+ runtimes = new WeakMap;
11826
+ });
11827
+
11828
+ // src/server/sync/queries.ts
11829
+ function isMutationMethod(method) {
11830
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
11831
+ }
11832
+ function markInternalRead(request) {
11833
+ internalReads.add(request);
11834
+ }
11835
+ function isInternalRead(request) {
11836
+ return internalReads.has(request);
11837
+ }
11838
+ function sealInvalidations(request) {
11839
+ sealed.add(request);
11840
+ }
11841
+ function requestInvalidate(request) {
11842
+ return (target, params) => {
11843
+ if (!isMutationMethod(request.method)) {
11844
+ throw new Error(`[furin] invalidate() was called while handling a ${request.method}: only a mutation invalidates.`);
11845
+ }
11846
+ if (sealed.has(request)) {
11847
+ if (IS_DEV) {
11848
+ throw new Error("[furin] invalidate() was called after mutation() resolved: call it inside the mutation() callback to commit it with the transaction.");
11849
+ }
11850
+ return;
11851
+ }
11852
+ let invalidations = collected.get(request);
11853
+ if (!invalidations) {
11854
+ invalidations = { queries: [], rules: [] };
11855
+ collected.set(request, invalidations);
11856
+ }
11857
+ if (typeof target !== "string") {
11858
+ invalidations.rules.push(target);
11859
+ return;
11860
+ }
11861
+ const identity = { id: target, scope: params ?? {} };
11862
+ queryTag(identity);
11863
+ invalidations.queries.push(identity);
11864
+ };
11865
+ }
11866
+ function urlIdentity(context) {
11867
+ const scope = Object.fromEntries(Object.entries(context.params ?? {}).filter(([, value]) => value !== undefined));
11868
+ return { id: context.route ?? context.path, scope };
11869
+ }
11870
+ function resolveSyncInvalidations(context) {
11871
+ const invalidations = collected.get(context.request);
11872
+ return [
11873
+ ...invalidations?.rules ?? [],
11874
+ { tags: [...invalidations?.queries ?? [], urlIdentity(context)].map(queryTag) }
11875
+ ];
11876
+ }
11877
+ function appendQueryInvalidations(input, context) {
11878
+ if (input === undefined) {
11879
+ return;
11572
11880
  }
11573
- configurePrincipalSecret(options.adapter, options.secret, development);
11574
- if (options.notifier) {
11575
- if (options.adapter.notificationChannel !== undefined && options.notifier.notificationChannel !== undefined && options.adapter.notificationChannel !== options.notifier.notificationChannel) {
11576
- throw new Error("[furin] SyncAdapter and SyncNotifier notification channels do not match.");
11881
+ const queries = [];
11882
+ for (const rule of Array.isArray(input) ? input : [input]) {
11883
+ for (const tag of rule.tags ?? []) {
11884
+ const identity = queryFromTag(tag);
11885
+ if (identity) {
11886
+ queries.push(identity);
11887
+ }
11577
11888
  }
11578
- return { adapter: options.adapter, development, notifier: options.notifier };
11579
11889
  }
11580
- if (!development && options.adapter.scope === "distributed") {
11581
- throw new Error("[furin] Distributed production sync requires an explicit SyncNotifier. Configure the adapter notifier or pass PollingSyncNotifier as a compatibility fallback.");
11582
- }
11583
- const existing = pollingNotifiers.get(options.adapter);
11584
- if (existing) {
11585
- return { adapter: options.adapter, development, notifier: existing };
11890
+ if (queries.length > 0) {
11891
+ context.set.headers["x-furin-queries"] = serializeQueryHeader(queries);
11586
11892
  }
11587
- const notifier = new PollingSyncNotifier(options.adapter, POLL_INTERVAL_MS);
11588
- pollingNotifiers.set(options.adapter, notifier);
11589
- return { adapter: options.adapter, development, notifier };
11590
11893
  }
11591
- var POLL_INTERVAL_MS = 250, pollingNotifiers;
11592
- var init_runtime = __esm(() => {
11593
- init_principal_journal();
11594
- pollingNotifiers = new WeakMap;
11894
+ var collected, sealed, internalReads;
11895
+ var init_queries = __esm(() => {
11896
+ collected = new WeakMap;
11897
+ sealed = new WeakSet;
11898
+ internalReads = new WeakSet;
11595
11899
  });
11596
11900
 
11597
11901
  // src/server/sync/stream.ts
@@ -11724,8 +12028,9 @@ function createSyncChangesPlugin(options) {
11724
12028
  }
11725
12029
  function createRuntimeSyncChangesPlugin(options, development) {
11726
12030
  const syncPath = options.path ?? defaultSyncPath;
11727
- const runtime = resolveSyncRuntime(syncRuntimeOptions(options), development);
12031
+ prepareSyncRuntime(options, development);
11728
12032
  return new Elysia7({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async (context) => {
12033
+ const runtime = resolveSyncRuntime(options, development);
11729
12034
  const { request, set } = context;
11730
12035
  markInternalRead(request);
11731
12036
  set.headers["cache-control"] = "no-store";
@@ -11733,16 +12038,23 @@ function createRuntimeSyncChangesPlugin(options, development) {
11733
12038
  if ("error" in query) {
11734
12039
  return query.error;
11735
12040
  }
11736
- const principal = await options.principal(context);
11737
- if (principal.length === 0) {
12041
+ const principal = await verifiedSyncPrincipal(options, context);
12042
+ if (principal === undefined) {
11738
12043
  return new Response("Unauthorized", { status: 401 });
11739
12044
  }
12045
+ set.headers["x-furin-sync-session"] = principalHash(runtime.adapter, principal);
12046
+ const connect = request[LOCAL_SYNC_CONNECTION];
12047
+ if (connect) {
12048
+ await connect(context, options);
12049
+ return new Response(null, { status: 204 });
12050
+ }
11740
12051
  return readPrincipalChanges(runtime.adapter, query, principal);
11741
12052
  });
11742
12053
  }
11743
12054
  var BROADCAST_WINDOW_MS = 100, DEFAULT_CHANGE_LIMIT = 100, MAX_CHANGE_LIMIT = 500, MAX_CURSOR_LENGTH = 128, DEVELOPMENT_SAFETY_POLL_INTERVAL_MS = 250, PRODUCTION_SAFETY_POLL_INTERVAL_MS = 15000, UNSIGNED_INTEGER_PATTERN, defaultSyncPath = "/_furin/sync", noOpSubscription, cursorStates, resolvedStates, pendingUnsubscriptions, unsubscriptions;
11744
12055
  var init_stream = __esm(() => {
11745
12056
  init_config();
12057
+ init_connection();
11746
12058
  init_principal_journal();
11747
12059
  init_queries();
11748
12060
  init_runtime();
@@ -11817,12 +12129,6 @@ function createConnectionCapacity() {
11817
12129
  }
11818
12130
  };
11819
12131
  }
11820
- async function verifiedPrincipal(sync, context) {
11821
- try {
11822
- const principal = await sync.principal(context);
11823
- return principal.length > 0 ? principal : undefined;
11824
- } catch {}
11825
- }
11826
12132
  function peerAddressKey(request, server) {
11827
12133
  return `address:${server?.requestIP(request)?.address ?? "unknown"}`;
11828
12134
  }
@@ -11856,30 +12162,44 @@ function createBrowserEventsPlugin(options) {
11856
12162
  const capacity = createConnectionCapacity();
11857
12163
  const peers = new WeakMap;
11858
12164
  const { development, sources = [], sync } = options;
12165
+ if (sync) {
12166
+ prepareSyncRuntime(sync, development);
12167
+ }
12168
+ const clientSource = browserEventsClientSource(sync !== undefined);
12169
+ const authenticate = async (context) => {
12170
+ const forbidden = forbiddenBrowserRequest(context.request, context.server, development);
12171
+ if (forbidden) {
12172
+ return forbidden;
12173
+ }
12174
+ return new Response(null, {
12175
+ status: !sync || sources.length > 0 || await verifiedSyncPrincipal(sync, context) !== undefined ? 200 : 401,
12176
+ headers: { "cache-control": "no-store" }
12177
+ });
12178
+ };
11859
12179
  return new Elysia8({ name: "furin-browser-events" }).use(websocket()).get(CLIENT_PATH2, ({ request, server }) => {
11860
12180
  const forbidden = forbiddenBrowserRequest(request, server, development);
11861
12181
  if (forbidden) {
11862
12182
  return forbidden;
11863
12183
  }
11864
- return new Response(CLIENT_SOURCE, {
12184
+ return new Response(clientSource, {
11865
12185
  headers: {
11866
12186
  "cache-control": "no-store",
11867
12187
  "content-type": "text/javascript; charset=utf-8",
11868
12188
  "x-content-type-options": "nosniff"
11869
12189
  }
11870
12190
  });
11871
- }).ws(SOCKET_PATH, {
12191
+ }).head(SOCKET_PATH, (context) => authenticate(context)).ws(SOCKET_PATH, {
11872
12192
  async beforeHandle(context) {
11873
12193
  const { request, server } = context;
11874
12194
  const forbidden = forbiddenBrowserRequest(request, server, development);
11875
12195
  if (forbidden) {
11876
12196
  return forbidden;
11877
12197
  }
11878
- const principal = sync && await verifiedPrincipal(sync, context);
12198
+ const principal = sync && await verifiedSyncPrincipal(sync, context);
11879
12199
  if (sync && principal === undefined && sources.length === 0) {
11880
12200
  return new Response("Unauthorized", { status: 401 });
11881
12201
  }
11882
- const peer = principal ? { key: `principal:${principal}`, sync: true } : { key: peerAddressKey(request, server), sync: false };
12202
+ const peer = principal ? { key: `principal:${principal}`, sync: true, context } : { key: peerAddressKey(request, server), sync: false };
11883
12203
  if (capacity.full(peer.key)) {
11884
12204
  return Response.json({ code: "FURIN_BROWSER_EVENTS_CAPACITY" }, { status: 503 });
11885
12205
  }
@@ -11931,6 +12251,21 @@ function createBrowserEventsPlugin(options) {
11931
12251
  };
11932
12252
  try {
11933
12253
  if (sync !== undefined && peer.sync) {
12254
+ const access = createSyncConnectionLifetime(sync, peer.context, () => {
12255
+ send({
12256
+ channel: "sync",
12257
+ data: { context: "changed" },
12258
+ version: BROWSER_EVENT_PROTOCOL_VERSION
12259
+ });
12260
+ releaseConnection(state);
12261
+ connections.delete(ws.id);
12262
+ ws.close(4410, "Sync context changed");
12263
+ });
12264
+ keep({ unsubscribe: access.close });
12265
+ await access.acquire();
12266
+ if (state.closed) {
12267
+ return;
12268
+ }
11934
12269
  const subscription = await subscribeSyncCursor(sync, development, (cursor) => send({
11935
12270
  channel: "sync",
11936
12271
  data: { cursor },
@@ -11962,8 +12297,18 @@ function createSseBrowserEventsPlugin({
11962
12297
  development,
11963
12298
  sync
11964
12299
  }) {
12300
+ prepareSyncRuntime(sync, development);
11965
12301
  const capacity = createConnectionCapacity();
11966
- return new Elysia8({ name: "furin-browser-events-sse" }).get(CLIENT_PATH2, ({ request, server }) => {
12302
+ return new Elysia8({ name: "furin-browser-events-sse" }).head(SOCKET_PATH, async (context) => {
12303
+ const forbidden = forbiddenBrowserRequest(context.request, context.server, development);
12304
+ if (forbidden) {
12305
+ return forbidden;
12306
+ }
12307
+ return new Response(null, {
12308
+ status: await verifiedSyncPrincipal(sync, context) === undefined ? 401 : 200,
12309
+ headers: { "cache-control": "no-store" }
12310
+ });
12311
+ }).get(CLIENT_PATH2, ({ request, server }) => {
11967
12312
  const forbidden = forbiddenBrowserRequest(request, server, development);
11968
12313
  if (forbidden) {
11969
12314
  return forbidden;
@@ -11981,7 +12326,7 @@ function createSseBrowserEventsPlugin({
11981
12326
  if (forbidden) {
11982
12327
  return forbidden;
11983
12328
  }
11984
- const principal = await verifiedPrincipal(sync, context);
12329
+ const principal = await verifiedSyncPrincipal(sync, context);
11985
12330
  if (principal === undefined) {
11986
12331
  return new Response("Unauthorized", { status: 401 });
11987
12332
  }
@@ -12007,6 +12352,7 @@ function createSseBrowserEventsPlugin({
12007
12352
  let closed = false;
12008
12353
  let subscription;
12009
12354
  let lifetime;
12355
+ let access;
12010
12356
  const send = (event) => {
12011
12357
  if (!closed) {
12012
12358
  controller.enqueue(SSE_ENCODER.encode(`data: ${serialized(event)}
@@ -12041,6 +12387,7 @@ function createSseBrowserEventsPlugin({
12041
12387
  clearTimeout(lifetime);
12042
12388
  }
12043
12389
  request.signal.removeEventListener("abort", onAbort);
12390
+ access?.close();
12044
12391
  subscription?.unsubscribe();
12045
12392
  releaseCapacity();
12046
12393
  };
@@ -12054,7 +12401,22 @@ function createSseBrowserEventsPlugin({
12054
12401
  controller.enqueue(SSE_ENCODER.encode(`: connected
12055
12402
 
12056
12403
  `));
12057
- subscribeSyncCursor(sync, development, (cursor) => send({ channel: "sync", data: { cursor }, version: BROWSER_EVENT_PROTOCOL_VERSION })).then((next) => {
12404
+ access = createSyncConnectionLifetime(sync, context, () => {
12405
+ send({
12406
+ channel: "sync",
12407
+ data: { context: "changed" },
12408
+ version: BROWSER_EVENT_PROTOCOL_VERSION
12409
+ });
12410
+ finish();
12411
+ });
12412
+ access.acquire().then(() => closed ? undefined : subscribeSyncCursor(sync, development, (cursor) => send({
12413
+ channel: "sync",
12414
+ data: { cursor },
12415
+ version: BROWSER_EVENT_PROTOCOL_VERSION
12416
+ }))).then((next) => {
12417
+ if (!next) {
12418
+ return;
12419
+ }
12058
12420
  if (closed) {
12059
12421
  next.unsubscribe();
12060
12422
  } else {
@@ -12083,11 +12445,12 @@ function injectBrowserEventsClient(html, basePath) {
12083
12445
  }
12084
12446
  return html.includes("</head>") ? html.replace("</head>", `${script}</head>`) : `${script}${html}`;
12085
12447
  }
12086
- var CLIENT_PATH2 = "/_furin/events/client.js", SOCKET_PATH = "/_furin/events", HEARTBEAT_INTERVAL_MS = 30000, SSE_CONNECTION_LIFETIME_MS = 60000, MAX_BROWSER_EVENT_CONNECTIONS = 100, MAX_BROWSER_EVENT_CONNECTIONS_PER_PEER = 10, CLIENT_SOURCE, SSE_CLIENT_SOURCE, SSE_ENCODER;
12448
+ var CLIENT_PATH2 = "/_furin/events/client.js", SOCKET_PATH = "/_furin/events", HEARTBEAT_INTERVAL_MS = 30000, SSE_CONNECTION_LIFETIME_MS = 60000, MAX_BROWSER_EVENT_CONNECTIONS = 100, MAX_BROWSER_EVENT_CONNECTIONS_PER_PEER = 10, SSE_CLIENT_SOURCE, SSE_ENCODER;
12087
12449
  var init_plugin2 = __esm(() => {
12450
+ init_connection();
12451
+ init_runtime();
12088
12452
  init_stream();
12089
12453
  init_shutdown();
12090
- CLIENT_SOURCE = browserEventsClientSource();
12091
12454
  SSE_CLIENT_SOURCE = browserEventsSseClientSource();
12092
12455
  SSE_ENCODER = new TextEncoder;
12093
12456
  });
@@ -12592,7 +12955,7 @@ function parseGeneratedFrames(stack) {
12592
12955
  const frames = [];
12593
12956
  for (const line of stack.split(`
12594
12957
  `)) {
12595
- const match = STACK_FRAME_RE.exec(line);
12958
+ const match = STACK_FRAME_RE.exec(line) ?? WEBKIT_FRAME_RE.exec(line);
12596
12959
  if (!(match?.[2] && match[3] && match[4])) {
12597
12960
  continue;
12598
12961
  }
@@ -12683,11 +13046,12 @@ async function symbolicateStack(input) {
12683
13046
  location: applicationFrame?.original ?? applicationFrame?.generated
12684
13047
  };
12685
13048
  }
12686
- var STACK_FRAME_RE, SOURCE_MAP_RE, BUN_ROOT_CHUNK_RE, SOURCE_MAP_CACHE_LIMIT = 100, sourceMaps;
13049
+ var STACK_FRAME_RE, WEBKIT_FRAME_RE, SOURCE_MAP_RE, BUN_ROOT_CHUNK_RE, SOURCE_MAP_CACHE_LIMIT = 100, sourceMaps;
12687
13050
  var init_symbolicate = __esm(() => {
12688
13051
  init_trace_mapping();
12689
13052
  STACK_FRAME_RE = /^\s*at\s+(?:(.*?)\s+\()?((?:https?:\/\/|file:\/\/|bun:\/\/).+):(\d+):(\d+)\)?$/;
12690
- SOURCE_MAP_RE = /\/\/[#@]\s*sourceMappingURL=([^\s]+)/;
13053
+ WEBKIT_FRAME_RE = /^(.*?)@((?:https?:\/\/|file:\/\/|bun:\/\/).+):(\d+):(\d+)$/;
13054
+ SOURCE_MAP_RE = /^\s*\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/m;
12691
13055
  BUN_ROOT_CHUNK_RE = /^\/chunk-[^/]+\.js$/;
12692
13056
  sourceMaps = new Map;
12693
13057
  });
@@ -18417,35 +18781,6 @@ function parseSource(code, lang) {
18417
18781
  }
18418
18782
  var init_parser = () => {};
18419
18783
 
18420
- // src/shared/utils/ast-walk.ts
18421
- function isNode(value) {
18422
- return "type" in value && typeof value.type === "string";
18423
- }
18424
- function walkAST(node, visitor) {
18425
- if (!node || typeof node !== "object") {
18426
- return;
18427
- }
18428
- if (Array.isArray(node)) {
18429
- for (const child of node) {
18430
- walkAST(child, visitor);
18431
- }
18432
- return;
18433
- }
18434
- if (!isNode(node)) {
18435
- return;
18436
- }
18437
- visitor(node);
18438
- for (const [key, child] of Object.entries(node)) {
18439
- if (!SKIP_KEYS.has(key)) {
18440
- walkAST(child, visitor);
18441
- }
18442
- }
18443
- }
18444
- var SKIP_KEYS;
18445
- var init_ast_walk = __esm(() => {
18446
- SKIP_KEYS = new Set(["type", "start", "end", "comments"]);
18447
- });
18448
-
18449
18784
  // src/plugin/module-transform.ts
18450
18785
  function parseModule(code, filename) {
18451
18786
  const { diagnostics, program } = parseSource(code, detectLangFromPath(filename));
@@ -18478,6 +18813,35 @@ var init_module_transform = __esm(() => {
18478
18813
  init_parser();
18479
18814
  });
18480
18815
 
18816
+ // src/shared/utils/ast-walk.ts
18817
+ function isNode(value) {
18818
+ return "type" in value && typeof value.type === "string";
18819
+ }
18820
+ function walkAST(node, visitor) {
18821
+ if (!node || typeof node !== "object") {
18822
+ return;
18823
+ }
18824
+ if (Array.isArray(node)) {
18825
+ for (const child of node) {
18826
+ walkAST(child, visitor);
18827
+ }
18828
+ return;
18829
+ }
18830
+ if (!isNode(node)) {
18831
+ return;
18832
+ }
18833
+ visitor(node);
18834
+ for (const [key, child] of Object.entries(node)) {
18835
+ if (!SKIP_KEYS.has(key)) {
18836
+ walkAST(child, visitor);
18837
+ }
18838
+ }
18839
+ }
18840
+ var SKIP_KEYS;
18841
+ var init_ast_walk = __esm(() => {
18842
+ SKIP_KEYS = new Set(["type", "start", "end", "comments"]);
18843
+ });
18844
+
18481
18845
  // src/plugin/dead-code-elimination.ts
18482
18846
  function isTypeAssertion(node) {
18483
18847
  return TYPE_ASSERTION_NODES.has(node.type);
@@ -18791,7 +19155,7 @@ var init_dead_code_elimination = __esm(() => {
18791
19155
  WALK_SKIPPED_KEYS = new Set(["type", "start", "end"]);
18792
19156
  });
18793
19157
 
18794
- // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/aliases.js
19158
+ // ../../node_modules/.bun/yuku-ast@0.13.0/node_modules/yuku-ast/dist/aliases.js
18795
19159
  var ALIAS_GROUPS, ALIAS_NAMES;
18796
19160
  var init_aliases = __esm(() => {
18797
19161
  ALIAS_GROUPS = {
@@ -18950,7 +19314,7 @@ var init_aliases = __esm(() => {
18950
19314
  ALIAS_NAMES = Object.keys(ALIAS_GROUPS);
18951
19315
  });
18952
19316
 
18953
- // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/generated.js
19317
+ // ../../node_modules/.bun/yuku-ast@0.13.0/node_modules/yuku-ast/dist/generated.js
18954
19318
  function ck(type, keys) {
18955
19319
  const prev = KEYS[type];
18956
19320
  if (prev === undefined)
@@ -19325,7 +19689,7 @@ var init_generated = __esm(() => {
19325
19689
  NODE_TYPES = [...new Set(TYPES)];
19326
19690
  });
19327
19691
 
19328
- // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/context.js
19692
+ // ../../node_modules/.bun/yuku-ast@0.13.0/node_modules/yuku-ast/dist/context.js
19329
19693
  class WalkContext {
19330
19694
  _ancestors = [];
19331
19695
  _node = null;
@@ -19393,7 +19757,7 @@ class WalkContext {
19393
19757
  }
19394
19758
  }
19395
19759
 
19396
- // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/walk.js
19760
+ // ../../node_modules/.bun/yuku-ast@0.13.0/node_modules/yuku-ast/dist/walk.js
19397
19761
  function createDispatch(visitors) {
19398
19762
  let enter = null;
19399
19763
  let leave = null;
@@ -19535,7 +19899,7 @@ var init_walk = __esm(() => {
19535
19899
  init_generated();
19536
19900
  });
19537
19901
 
19538
- // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/index.js
19902
+ // ../../node_modules/.bun/yuku-ast@0.13.0/node_modules/yuku-ast/dist/index.js
19539
19903
  var init_dist3 = __esm(() => {
19540
19904
  init_walk();
19541
19905
  });
@@ -20740,6 +21104,28 @@ var init_error = __esm(() => {
20740
21104
  init_stack_location();
20741
21105
  });
20742
21106
 
21107
+ // src/server/dev/server-only-module.ts
21108
+ import { readFileSync as readFileSync5, statSync as statSync3 } from "fs";
21109
+ function isServerOnlyModule(path) {
21110
+ const stats = statSync3(path, { throwIfNoEntry: false });
21111
+ if (!stats) {
21112
+ return false;
21113
+ }
21114
+ const { mtimeMs } = stats;
21115
+ const cached = cache.get(path);
21116
+ if (cached?.mtimeMs === mtimeMs) {
21117
+ return cached.serverOnly;
21118
+ }
21119
+ const serverOnly = SERVER_ONLY_IMPORT.test(readFileSync5(path, "utf8"));
21120
+ cache.set(path, { mtimeMs, serverOnly });
21121
+ return serverOnly;
21122
+ }
21123
+ var SERVER_ONLY_IMPORT, cache;
21124
+ var init_server_only_module = __esm(() => {
21125
+ SERVER_ONLY_IMPORT = /^\s*import\s+["'](?:@teyik0\/)?furin\/server-only["'];?\s*$/m;
21126
+ cache = new Map;
21127
+ });
21128
+
20743
21129
  // src/server/dev/rewrite-module-specifiers.ts
20744
21130
  import { dirname as dirname6, resolve as resolve7 } from "path";
20745
21131
  function sourcePosition2(source, byteOffset) {
@@ -20764,7 +21150,7 @@ function relativeSpecifier(node) {
20764
21150
  function resolvedSpecifier(specifier, directory, versioned) {
20765
21151
  const path = versioned ? Bun.resolveSync(specifier, directory) : resolve7(directory, specifier);
20766
21152
  const normalized = path.replaceAll("\\", "/");
20767
- return versioned && SCRIPT_FILE_FILTER.test(normalized) ? `${normalized}?furin-server&t=${routeModuleSourceVersion(normalized)}` : normalized;
21153
+ return versioned && SCRIPT_FILE_FILTER.test(normalized) && !isServerOnlyModule(path) ? `${normalized}?furin-server&t=${routeModuleSourceVersion(normalized)}` : normalized;
20768
21154
  }
20769
21155
  function rewriteModuleSpecifiers(input) {
20770
21156
  const { diagnostics, program } = parseSource(input.code, detectLangFromPath(input.filePath));
@@ -20792,6 +21178,7 @@ var init_rewrite_module_specifiers = __esm(() => {
20792
21178
  init_ast_walk();
20793
21179
  init_lang_detect();
20794
21180
  init_source_version();
21181
+ init_server_only_module();
20795
21182
  });
20796
21183
 
20797
21184
  // src/server/dev-page-imports.ts
@@ -20854,7 +21241,7 @@ function rewriteBareImports(source, dir, loader) {
20854
21241
  } catch {
20855
21242
  return;
20856
21243
  }
20857
- if (WORKSPACE_SOURCE_FILTER.test(resolved) && specifier !== "furin" && !specifier.startsWith("furin/") && specifier !== "@teyik0/furin" && !specifier.startsWith("@teyik0/furin/")) {
21244
+ if (WORKSPACE_SOURCE_FILTER.test(resolved) && specifier !== "furin" && !specifier.startsWith("furin/") && specifier !== "@teyik0/furin" && !specifier.startsWith("@teyik0/furin/") && !isServerOnlyModule(resolved)) {
20858
21245
  resolved = `${resolved}?furin-server&t=${routeModuleSourceVersion(resolved)}`;
20859
21246
  }
20860
21247
  output.update(literal.start, literal.end, JSON.stringify(resolved));
@@ -20867,6 +21254,7 @@ var init_dev_page_imports = __esm(() => {
20867
21254
  init_parser();
20868
21255
  init_ast_walk();
20869
21256
  init_rewrite_module_specifiers();
21257
+ init_server_only_module();
20870
21258
  init_source_version();
20871
21259
  WORKSPACE_SOURCE_FILTER = /^(?!.*(?:[\\/]node_modules[\\/]|[\\/]\.bun[\\/]))(?!.*\.(?:test|spec)\.(?:[cm]?[jt]s|[jt]sx)$).*\.(?:m?[jt]s|[jt]sx)$/;
20872
21260
  SINGLETON_PKGS = [
@@ -20886,7 +21274,7 @@ var init_dev_page_imports = __esm(() => {
20886
21274
  });
20887
21275
 
20888
21276
  // src/server/dev-page-plugin.ts
20889
- import { statSync as statSync3 } from "fs";
21277
+ import { statSync as statSync4 } from "fs";
20890
21278
  import { dirname as dirname8, isAbsolute as isAbsolute5 } from "path";
20891
21279
  function getSourceLoader(filePath) {
20892
21280
  return SCRIPT_FILE_FILTER.test(filePath) ? detectLoaderFromPath(filePath) : null;
@@ -20901,7 +21289,7 @@ function recordDevImports(source, filePath) {
20901
21289
  if (!isAbsolute5(path) || getSourceLoader(path)) {
20902
21290
  continue;
20903
21291
  }
20904
- const stats = statSync3(path, { bigint: true, throwIfNoEntry: false });
21292
+ const stats = statSync4(path, { bigint: true, throwIfNoEntry: false });
20905
21293
  if (!stats) {
20906
21294
  continue;
20907
21295
  }
@@ -20960,7 +21348,13 @@ function transformDevSource(raw, filePath, options) {
20960
21348
  if (!options.renderFragment) {
20961
21349
  recordDevImports(raw, filePath);
20962
21350
  }
20963
- const isomorphicSource = transformIsomorphicFunctions(raw, filePath, "server").code;
21351
+ const server = parseModule(raw, filePath);
21352
+ for (const statement of server.program.body) {
21353
+ if (statement.type === "ImportDeclaration" && statement.specifiers.length === 0 && CSS_IMPORT.test(statement.source.value)) {
21354
+ removeRange(server, statement.start, statement.end);
21355
+ }
21356
+ }
21357
+ const isomorphicSource = transformIsomorphicFunctions(server.source.toString(), filePath, "server").code;
20964
21358
  const split = options.renderFragment ? undefined : splitDevPage(isomorphicSource, filePath, `${filePath}?furin-render&t=${routeModuleSourceVersion(filePath)}`);
20965
21359
  const serverSource = split?.contract ?? isomorphicSource;
20966
21360
  let result = options.rewriteRelativeImports ? rewriteRelativeImportsWithVersion(serverSource, filePath, true) : serverSource;
@@ -21077,8 +21471,9 @@ function registerDevPagePlugin() {
21077
21471
  }
21078
21472
  });
21079
21473
  }
21080
- var FURIN_SERVER_FILTER, FURIN_RENDER_FILTER, COMMONJS_FILE_RE, ANY_FILTER, T_PARAM_RE, STRIP_FURIN_SERVER_RE, STRIP_T_PARAM_RE, DELETED_DEV_PAGE_CONTENTS = "export const route = undefined;", _pluginRegistered = false, pluginSourceStamps;
21474
+ var FURIN_SERVER_FILTER, FURIN_RENDER_FILTER, COMMONJS_FILE_RE, ANY_FILTER, T_PARAM_RE, STRIP_FURIN_SERVER_RE, STRIP_T_PARAM_RE, DELETED_DEV_PAGE_CONTENTS = "export const route = undefined;", CSS_IMPORT, _pluginRegistered = false, pluginSourceStamps;
21081
21475
  var init_dev_page_plugin = __esm(() => {
21476
+ init_module_transform();
21082
21477
  init_transform_dev_page();
21083
21478
  init_transform_isomorphic();
21084
21479
  init_dev_loader();
@@ -21095,11 +21490,12 @@ var init_dev_page_plugin = __esm(() => {
21095
21490
  T_PARAM_RE = /&t=(\d+)/;
21096
21491
  STRIP_FURIN_SERVER_RE = /\?furin-server.*$/;
21097
21492
  STRIP_T_PARAM_RE = /\?t=\d+$/;
21493
+ CSS_IMPORT = /\.css(?:\?.*)?$/;
21098
21494
  pluginSourceStamps = new Map;
21099
21495
  });
21100
21496
 
21101
21497
  // src/plugin/route-modules.ts
21102
- import { existsSync as existsSync8, readFileSync as readFileSync5, realpathSync as realpathSync3, statSync as statSync4 } from "fs";
21498
+ import { existsSync as existsSync8, readFileSync as readFileSync6, realpathSync as realpathSync3, statSync as statSync5 } from "fs";
21103
21499
  import { dirname as dirname9, isAbsolute as isAbsolute6, join as join6, relative as relative8, sep as sep2 } from "path";
21104
21500
  function validateRouteParams(path, schemas) {
21105
21501
  const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? segment : segment.slice(1));
@@ -21143,7 +21539,7 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
21143
21539
  if (!SCRIPT_FILE_FILTER.test(dependencyPath)) {
21144
21540
  return [];
21145
21541
  }
21146
- const source = readFileSync5(dependencyPath, "utf8");
21542
+ const source = readFileSync6(dependencyPath, "utf8");
21147
21543
  const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(dependencyPath) });
21148
21544
  const resolvedImports = [];
21149
21545
  for (const imported of transpiler.scanImports(source)) {
@@ -21172,7 +21568,7 @@ function collectRouteModuleDependencies(sourcePath) {
21172
21568
  visited.add(dependencyPath);
21173
21569
  let mtimeMs;
21174
21570
  try {
21175
- ({ mtimeMs } = statSync4(dependencyPath));
21571
+ ({ mtimeMs } = statSync5(dependencyPath));
21176
21572
  } catch {
21177
21573
  continue;
21178
21574
  }
@@ -21191,7 +21587,7 @@ var init_route_modules = __esm(() => {
21191
21587
  });
21192
21588
 
21193
21589
  // src/plugin/dev-routes.ts
21194
- import { existsSync as existsSync9, readFileSync as readFileSync6, statSync as statSync5, watch } from "fs";
21590
+ import { existsSync as existsSync9, readFileSync as readFileSync7, statSync as statSync6, watch } from "fs";
21195
21591
  import { dirname as dirname10, relative as relative9, resolve as resolve9, sep as sep3 } from "path";
21196
21592
  import { Elysia as Elysia16 } from "elysia";
21197
21593
  function routeTopologySource(instance) {
@@ -21212,7 +21608,7 @@ function routeDependencyPaths(instance) {
21212
21608
  function routeFilesSignature(instance) {
21213
21609
  return routeDependencyPaths(instance).map((path) => {
21214
21610
  try {
21215
- const stats = statSync5(path, { bigint: true });
21611
+ const stats = statSync6(path, { bigint: true });
21216
21612
  return `${path}\x00${stats.mtimeNs}:${stats.size}`;
21217
21613
  } catch {
21218
21614
  return `${path}\x00missing`;
@@ -21309,7 +21705,7 @@ function reportChangedSourceError(state, directory, filename) {
21309
21705
  return;
21310
21706
  }
21311
21707
  try {
21312
- const source = readFileSync6(sourcePath, "utf8");
21708
+ const source = readFileSync7(sourcePath, "utf8");
21313
21709
  const loader = detectLoaderFromPath(sourcePath);
21314
21710
  new Bun.Transpiler({ loader }).transformSync(source, loader);
21315
21711
  } catch (error) {
@@ -21551,7 +21947,7 @@ var init_dev_routes = __esm(() => {
21551
21947
  });
21552
21948
 
21553
21949
  // src/plugin/route-config.ts
21554
- import { existsSync as existsSync10, readFileSync as readFileSync7, writeFileSync } from "fs";
21950
+ import { existsSync as existsSync10, readFileSync as readFileSync8, writeFileSync } from "fs";
21555
21951
  import { basename as basename3, join as join7, relative as relative10, resolve as resolve10 } from "path";
21556
21952
  function withoutExtension(path) {
21557
21953
  return path.replace(EXTENSION_RE, "");
@@ -21611,7 +22007,7 @@ function findRouteExport(program, imports) {
21611
22007
  }
21612
22008
  function readSource(file) {
21613
22009
  try {
21614
- return readFileSync7(file, "utf8");
22010
+ return readFileSync8(file, "utf8");
21615
22011
  } catch {}
21616
22012
  }
21617
22013
  function parseRoute(file) {
@@ -21844,6 +22240,37 @@ var init_route_config = __esm(() => {
21844
22240
  PATH_SEPARATOR_RE = /[\\/]/;
21845
22241
  });
21846
22242
 
22243
+ // src/build/route-metadata.ts
22244
+ function routeBuildInfo(route) {
22245
+ if ("build" in route) {
22246
+ return route.build;
22247
+ }
22248
+ const chain = route.routeChain ?? [];
22249
+ const query = mergeRouteSchemas(chain, "query");
22250
+ let queryKeys = [];
22251
+ if (query !== undefined) {
22252
+ queryKeys = isTypeBoxObjectSchema(query) ? Object.keys(query.properties).toSorted() : null;
22253
+ }
22254
+ return {
22255
+ documentMode: resolveDocumentMode({ ...route, routeChain: chain }),
22256
+ documentRevalidate: resolveDocumentRevalidate({ ...route, routeChain: chain }),
22257
+ hasLayout: chain.some((entry) => !!entry.layout),
22258
+ hasRequestLoader: chain.some((entry) => entry.requestLoader !== undefined),
22259
+ hasStaticParams: route.page.staticParams !== undefined || chain.some((entry) => entry.staticParams !== undefined),
22260
+ mixed: hasMixedLoaderModes({ ...route, routeChain: chain }),
22261
+ queryKeys,
22262
+ revalidate: resolveRouteRevalidate(route.page),
22263
+ searchDefaults: collectSearchDefaults(query)
22264
+ };
22265
+ }
22266
+ var init_route_metadata = __esm(() => {
22267
+ init_loaders();
22268
+ init_patterns();
22269
+ init_schema_merge();
22270
+ init_elysia_contract();
22271
+ init_search_params();
22272
+ });
22273
+
21847
22274
  // src/rsc/build/paths.ts
21848
22275
  import { dirname as dirname11, join as join8 } from "path";
21849
22276
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -21881,7 +22308,7 @@ ${body}
21881
22308
  }
21882
22309
 
21883
22310
  // src/build/route-types.ts
21884
- import { existsSync as existsSync11, readFileSync as readFileSync8, renameSync, writeFileSync as writeFileSync2 } from "fs";
22311
+ import { existsSync as existsSync11, readFileSync as readFileSync9, renameSync, writeFileSync as writeFileSync2 } from "fs";
21885
22312
  import { extname as extname3, join as join9, relative as relative11, resolve as resolve11 } from "path";
21886
22313
  function tagKeyToPropertyName(tag) {
21887
22314
  return /^[$A-Z_a-z][$\w]*$/.test(tag) ? tag : JSON.stringify(tag);
@@ -21964,7 +22391,7 @@ import "@teyik0/furin/routes";
21964
22391
  ${apps === undefined ? "" : fileRoutesDeclaration(apps, projectRoot)}${routeMapDeclaration(entries)}${tagBlock}
21965
22392
  `;
21966
22393
  const typesPath = join9(projectRoot, "furin-env.d.ts");
21967
- const existing = existsSync11(typesPath) ? readFileSync8(typesPath, "utf8") : "";
22394
+ const existing = existsSync11(typesPath) ? readFileSync9(typesPath, "utf8") : "";
21968
22395
  if (content === existing) {
21969
22396
  return false;
21970
22397
  }
@@ -21990,7 +22417,7 @@ var init_shared2 = __esm(() => {
21990
22417
  });
21991
22418
 
21992
22419
  // src/build/hydrate.ts
21993
- import { existsSync as existsSync12, mkdirSync, readFileSync as readFileSync9, writeFileSync as writeFileSync3 } from "fs";
22420
+ import { existsSync as existsSync12, mkdirSync, readFileSync as readFileSync10, writeFileSync as writeFileSync3 } from "fs";
21994
22421
  import { dirname as dirname12, join as join10 } from "path";
21995
22422
  function generateClientReferenceEntry(boundaries) {
21996
22423
  if (boundaries.length === 0) {
@@ -22027,7 +22454,7 @@ function hydrateEntry(routes, rootLayout, basePath, clientLogging, modulePathKey
22027
22454
  for (const route of clientRoutes) {
22028
22455
  const resolvedPage = route.path.replace(/\\/g, "/");
22029
22456
  const regexPattern = buildRouteRegex(route.pattern).regex.source;
22030
- const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain ?? [], "query"));
22457
+ const searchDefaults = routeBuildInfo(route).searchDefaults;
22031
22458
  const boundaryIdents = new Map;
22032
22459
  const layoutPaths = (route.routeChain ?? []).slice(1).filter((entry) => entry.layout && entry.sourcePath).map((entry) => entry.sourcePath);
22033
22460
  activeHotComponentKeys.add(`page:${modulePathKey(resolvedPage)}`);
@@ -22102,6 +22529,12 @@ const __furinBasePath = ${basePathLiteral};
22102
22529
  ${loggerSetup}
22103
22530
 
22104
22531
  if (import.meta.hot) {
22532
+ import.meta.hot.on("bun:beforeUpdate", () => {
22533
+ window.dispatchEvent(new Event("furin:hmr-before-update"));
22534
+ });
22535
+ import.meta.hot.on("bun:afterUpdate", () => {
22536
+ window.dispatchEvent(new Event("furin:hmr-after-update"));
22537
+ });
22105
22538
  const connectionState = ((window as unknown as {
22106
22539
  __FURIN_HMR_CONNECTION__?: { disconnected: boolean; installed: boolean };
22107
22540
  }).__FURIN_HMR_CONNECTION__ ??= { disconnected: false, installed: false });
@@ -22403,7 +22836,7 @@ if (import.meta.hot) import.meta.hot.data.furinServerSourceVersion = ${JSON.stri
22403
22836
  `;
22404
22837
  const hydrateCode = generateClientReferenceEntry(clientBoundaries ?? []) + generateHydrateEntry(routes, rootLayout, basePath, clientLogging) + serverVersion;
22405
22838
  const hydratePath = join10(outDir, "_hydrate.tsx");
22406
- const existingHydrate = existsSync12(hydratePath) ? readFileSync9(hydratePath, "utf8") : "";
22839
+ const existingHydrate = existsSync12(hydratePath) ? readFileSync10(hydratePath, "utf8") : "";
22407
22840
  let changed = false;
22408
22841
  if (hydrateCode !== existingHydrate) {
22409
22842
  writeFileSync3(hydratePath, hydrateCode);
@@ -22411,7 +22844,7 @@ if (import.meta.hot) import.meta.hot.data.furinServerSourceVersion = ${JSON.stri
22411
22844
  }
22412
22845
  const indexHtml = generateIndexHtml();
22413
22846
  const indexPath = join10(outDir, "index.html");
22414
- const existingIndex = existsSync12(indexPath) ? readFileSync9(indexPath, "utf8") : "";
22847
+ const existingIndex = existsSync12(indexPath) ? readFileSync10(indexPath, "utf8") : "";
22415
22848
  if (indexHtml !== existingIndex) {
22416
22849
  writeFileSync3(indexPath, indexHtml);
22417
22850
  changed = true;
@@ -22424,8 +22857,7 @@ if (import.meta.hot) import.meta.hot.data.furinServerSourceVersion = ${JSON.stri
22424
22857
  var devRouteTypesApps;
22425
22858
  var init_hydrate = __esm(() => {
22426
22859
  init_patterns();
22427
- init_schema_merge();
22428
- init_search_params();
22860
+ init_route_metadata();
22429
22861
  init_paths();
22430
22862
  init_route_types();
22431
22863
  init_shared2();
@@ -22709,7 +23141,7 @@ var init_discover = __esm(() => {
22709
23141
  });
22710
23142
 
22711
23143
  // src/plugin/hmr-dependencies.ts
22712
- import { readFileSync as readFileSync10 } from "fs";
23144
+ import { readFileSync as readFileSync11 } from "fs";
22713
23145
  import { dirname as dirname13, isAbsolute as isAbsolute7, resolve as resolve12 } from "path";
22714
23146
  function hmrDependencySignature(imports, filename) {
22715
23147
  const routePath = resolve12(filename);
@@ -22728,7 +23160,7 @@ function hmrDependencySignature(imports, filename) {
22728
23160
  return true;
22729
23161
  }
22730
23162
  visited.add(path);
22731
- const source = readFileSync10(path, "utf8");
23163
+ const source = readFileSync11(path, "utf8");
22732
23164
  hash.update(source);
22733
23165
  if (SCRIPT_FILE_FILTER.test(path)) {
22734
23166
  const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(path) });
@@ -22886,7 +23318,7 @@ var exports_runtime = {};
22886
23318
  __export(exports_runtime, {
22887
23319
  createDevRuntime: () => createDevRuntime
22888
23320
  });
22889
- import { existsSync as existsSync13, readFileSync as readFileSync11 } from "fs";
23321
+ import { existsSync as existsSync13, readFileSync as readFileSync12 } from "fs";
22890
23322
  import { basename as basename4, dirname as dirname14, join as join11, resolve as resolve13 } from "path";
22891
23323
  import { staticPlugin as staticPlugin2 } from "@elysia/static";
22892
23324
  import { Elysia as Elysia17, file as file2 } from "elysia";
@@ -23017,7 +23449,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23017
23449
  const nextSignatures = new Map(paths.map((path) => {
23018
23450
  let signature;
23019
23451
  try {
23020
- signature = getHmrDataSignature(readFileSync11(path, "utf8"), path);
23452
+ signature = getHmrDataSignature(readFileSync12(path, "utf8"), path);
23021
23453
  if (signature.startsWith("external:")) {
23022
23454
  signature = graph.sourceVersion(path);
23023
23455
  }
@@ -23284,28 +23716,6 @@ async function readBoundedBytes(stream, maxBytes) {
23284
23716
  // src/server/logging/ingest-plugin.ts
23285
23717
  init_instrumentation();
23286
23718
  init_evlog();
23287
-
23288
- // src/server/logger.ts
23289
- init_dist();
23290
- var FURIN_LOGGER_SAMPLING = Symbol.for("@teyik0/furin/logger-sampling");
23291
- function loggerState() {
23292
- return globalThis;
23293
- }
23294
- function initializeFurinLogger(config) {
23295
- const state = loggerState();
23296
- const sampling = JSON.stringify(config.sampling ?? null);
23297
- const active = state[FURIN_LOGGER_SAMPLING];
23298
- if (active === undefined) {
23299
- initLogger(config);
23300
- state[FURIN_LOGGER_SAMPLING] = sampling;
23301
- return;
23302
- }
23303
- if (config.sampling !== undefined && sampling !== active) {
23304
- throw new Error(`[furin] logger.sampling is process-wide (evlog initLogger): this process already samples with ${active}, so ${sampling} would be ignored. Pass the same sampling to every furin() instance, or omit it on later ones.`);
23305
- }
23306
- }
23307
-
23308
- // src/server/logging/ingest-plugin.ts
23309
23719
  var MAX_BROWSER_INGEST_BYTES = 64 * 1024;
23310
23720
  var MAX_BROWSER_INGEST_EVENTS = 100;
23311
23721
  var PROTOTYPE_POLLUTION_KEYS = new Set(["__proto__", "constructor", "prototype"]);
@@ -23350,12 +23760,7 @@ function createLoggerOptions(prefix, syncPath, logger) {
23350
23760
  };
23351
23761
  }
23352
23762
  function createLoggerPlugin(instance, logger, clientLogging) {
23353
- const { sampling, ...elysiaLoggerOptions } = logger ?? {};
23354
- initializeFurinLogger({
23355
- env: { service: "furin" },
23356
- ...sampling ? { sampling } : {}
23357
- });
23358
- const options = createLoggerOptions(instance.prefix, instance.syncPath, elysiaLoggerOptions);
23763
+ const options = createLoggerOptions(instance.prefix, instance.syncPath, logger ?? {});
23359
23764
  setFurinEvlogOptions(instance, options);
23360
23765
  const app = new Elysia10().use(createFurinEvlog(options));
23361
23766
  if (!clientLogging) {
@@ -24339,10 +24744,13 @@ function idempotentRouteMacro(_idempotent) {
24339
24744
  };
24340
24745
  }
24341
24746
  function createSyncPlugin(options, owner) {
24342
- const runtime = resolveSyncRuntime(options, IS_DEV);
24343
- const transactional = "executeMutation" in options.adapter ? options.adapter : undefined;
24747
+ const development = IS_DEV;
24748
+ prepareSyncRuntime(options, development);
24749
+ const runtime = () => resolveSyncRuntime(options, development);
24344
24750
  function mutationFor(ctx) {
24345
24751
  const mutation = async (callback) => {
24752
+ const resolved = runtime();
24753
+ const transactional = "executeMutation" in resolved.adapter ? resolved.adapter : undefined;
24346
24754
  const active = activeMutations.get(ctx.request);
24347
24755
  if (!(transactional && active)) {
24348
24756
  throw new Error("[furin] mutation() requires a transactional sync adapter and an enabled mutation route.");
@@ -24357,7 +24765,7 @@ function createSyncPlugin(options, owner) {
24357
24765
  app: syncValidationApp(ctx),
24358
24766
  context: ctx,
24359
24767
  lease: active.lease,
24360
- runtime,
24768
+ runtime: resolved,
24361
24769
  onCommit: (result) => atomicResponses.set(ctx.request, result)
24362
24770
  }, callback);
24363
24771
  } finally {
@@ -24392,7 +24800,7 @@ function createSyncPlugin(options, owner) {
24392
24800
  }
24393
24801
  const key = `${ctx.request.method}:${url.pathname}:${idempotencyKey}`;
24394
24802
  const fingerprint = createMutationFingerprint({ body: ctx.body, request: ctx.request });
24395
- const result = await runtime.adapter.beginMutation({ fingerprint, key, principal });
24803
+ const result = await runtime().adapter.beginMutation({ fingerprint, key, principal });
24396
24804
  if (result.kind === "replay") {
24397
24805
  return replayResponse(result.response);
24398
24806
  }
@@ -24406,7 +24814,7 @@ function createSyncPlugin(options, owner) {
24406
24814
  if (activeMutations.get(ctx.request) === active) {
24407
24815
  scheduleRenewal();
24408
24816
  }
24409
- await runtime.adapter.renewMutation(result.lease).catch(() => {
24817
+ await runtime().adapter.renewMutation(result.lease).catch(() => {
24410
24818
  return;
24411
24819
  });
24412
24820
  }, renewAfter);
@@ -24426,7 +24834,7 @@ function createSyncPlugin(options, owner) {
24426
24834
  async function abortMutation(request) {
24427
24835
  const active = releaseMutation(request);
24428
24836
  if (active) {
24429
- await runtime.adapter.abortMutation(active.lease);
24837
+ await runtime().adapter.abortMutation(active.lease);
24430
24838
  }
24431
24839
  }
24432
24840
  async function applyInvalidations(ctx) {
@@ -24450,7 +24858,7 @@ function createSyncPlugin(options, owner) {
24450
24858
  const result = await storeResponse(ctx.responseValue, ctx.set);
24451
24859
  const invalidations = await applyInvalidations(ctx);
24452
24860
  const response = mergeStoredResponseHeaders(result.response, result.kind === "unreplayable" ? ctx.set.headers : effectiveResponseHeaders(ctx.responseValue, ctx.set));
24453
- const completion = await runtime.adapter.completeMutation({
24861
+ const completion = await runtime().adapter.completeMutation({
24454
24862
  invalidations,
24455
24863
  lease: active.lease,
24456
24864
  response
@@ -24459,7 +24867,7 @@ function createSyncPlugin(options, owner) {
24459
24867
  return leaseLostResponse();
24460
24868
  }
24461
24869
  if (completion.cursor !== undefined) {
24462
- publishCursor(runtime, completion.cursor);
24870
+ publishCursor(runtime(), completion.cursor);
24463
24871
  }
24464
24872
  if (result.kind === "unreplayable") {
24465
24873
  return replayResponse(response);
@@ -24471,7 +24879,7 @@ function createSyncPlugin(options, owner) {
24471
24879
  }
24472
24880
  const invalidations = await applyInvalidations(ctx);
24473
24881
  try {
24474
- publishCursor(runtime, await runtime.adapter.appendInvalidations(invalidations));
24882
+ publishCursor(runtime(), await runtime().adapter.appendInvalidations(invalidations));
24475
24883
  } catch {
24476
24884
  getLogger().warn("Sync journal append failed after a non-idempotent mutation");
24477
24885
  }
@@ -24496,12 +24904,12 @@ function createSyncPlugin(options, owner) {
24496
24904
  }
24497
24905
  try {
24498
24906
  if (!isSuccessfulMutationResponse(ctx)) {
24499
- await runtime.adapter.abortMutation(active.lease);
24907
+ await runtime().adapter.abortMutation(active.lease);
24500
24908
  return;
24501
24909
  }
24502
24910
  return await persistMutation(ctx, active);
24503
24911
  } catch (error) {
24504
- await runtime.adapter.abortMutation(active.lease).catch(() => {
24912
+ await runtime().adapter.abortMutation(active.lease).catch(() => {
24505
24913
  return;
24506
24914
  });
24507
24915
  throw error;
@@ -24541,7 +24949,7 @@ function createSyncPlugin(options, owner) {
24541
24949
  }
24542
24950
  const identity = {
24543
24951
  ...urlIdentity(ctx),
24544
- session: principalHash(options.adapter, principal)
24952
+ session: principalHash(runtime().adapter, principal)
24545
24953
  };
24546
24954
  ctx.set.headers["x-furin-query"] = serializeQueryHeader(identity);
24547
24955
  }).onError("global", MutationLeaseLost, hideTransportResponse(({ request }) => Promise.resolve(requestOwners.get(request) === owner ? leaseLostResponse() : undefined))).onError("global", hideTransportResponse(async ({ request }) => {
@@ -24572,9 +24980,7 @@ function furinSync(options) {
24572
24980
  requestOwners.set(request, routeOwner);
24573
24981
  });
24574
24982
  installMutationHandlers(app);
24575
- if ("executeMutation" in options.adapter) {
24576
- bindSyncValidation(app);
24577
- }
24983
+ bindSyncValidation(app);
24578
24984
  return app.use(createSyncPlugin(options, owner));
24579
24985
  };
24580
24986
  }
@@ -24601,13 +25007,379 @@ init_element();
24601
25007
  init_not_found2();
24602
25008
  // src/server/sync/invalidate-sync.ts
24603
25009
  init_runtime();
24604
- async function invalidateSync(sync, target, params) {
25010
+ async function invalidateSync(sync, target, paramsOrOptions, options) {
25011
+ const provenance = typeof target === "string" ? options : paramsOrOptions;
25012
+ if (provenance?.principal === "") {
25013
+ throw new Error("[furin] Sync invalidation principal must not be empty.");
25014
+ }
24605
25015
  const runtime = resolveSyncRuntime(sync, IS_DEV);
24606
- const rule = typeof target === "string" ? { tags: [queryTag({ id: target, scope: params ?? {} })] } : target;
25016
+ const rule = typeof target === "string" ? {
25017
+ tags: [
25018
+ queryTag({ id: target, scope: paramsOrOptions ?? {} })
25019
+ ]
25020
+ } : target;
24607
25021
  await runInvalidationRules(rule);
24608
- publishCursor(runtime, await runtime.adapter.appendInvalidations(normalizedInvalidations(rule)));
25022
+ publishCursor(runtime, await runtime.adapter.appendInvalidations(normalizedInvalidations(rule), provenance?.principal));
25023
+ }
25024
+
25025
+ // src/client/sync-client.ts
25026
+ init_query_store();
25027
+ init_sync_catch_up();
25028
+ function isEdenError(error) {
25029
+ return error instanceof Error && "status" in error && typeof error.status === "number" && "value" in error;
25030
+ }
25031
+ class SyncClientError extends Error {
25032
+ status;
25033
+ static [Symbol.hasInstance](error) {
25034
+ return error instanceof Error && error.name === "SyncClientError" && "status" in error;
25035
+ }
25036
+ constructor(message, status, cause) {
25037
+ super(message, { cause });
25038
+ this.name = "SyncClientError";
25039
+ this.status = status;
25040
+ }
25041
+ }
25042
+ function createSyncClientRuntime(options, transport) {
25043
+ const queries = new QueryStore(undefined);
25044
+ const listeners = new Set;
25045
+ const subscriptions = new Map;
25046
+ let state = { status: "idle", error: null };
25047
+ let controller = new AbortController;
25048
+ let ready = Promise.withResolvers();
25049
+ let connection;
25050
+ let timer;
25051
+ let attempt = 0;
25052
+ let generation = 0;
25053
+ let session;
25054
+ const publish = (status, error, reason) => {
25055
+ state = { status, error, reason };
25056
+ for (const listener of listeners) {
25057
+ listener(state);
25058
+ }
25059
+ };
25060
+ const headers = async () => new Headers(typeof options.headers === "function" ? await options.headers() : options.headers);
25061
+ const asError = (error) => error instanceof SyncClientError ? error : new SyncClientError("Sync connection failed", undefined, error);
25062
+ const unauthorized = (error) => error.status === 401 || error.status === 403;
25063
+ const active = () => state.status !== "closed" && state.status !== "unauthorized";
25064
+ const createRecovery = () => createSyncCatchUp({
25065
+ fetchPage: async (after) => {
25066
+ const { signal } = controller;
25067
+ const requestHeaders = await headers();
25068
+ signal.throwIfAborted();
25069
+ const response = await transport.fetchChanges(after, requestHeaders, signal);
25070
+ signal.throwIfAborted();
25071
+ if (!response.ok) {
25072
+ throw new SyncClientError("Sync recovery refused", response.status);
25073
+ }
25074
+ const page = await response.json();
25075
+ signal.throwIfAborted();
25076
+ const identity = response.headers.get("x-furin-sync-session");
25077
+ if (identity !== null) {
25078
+ if (session !== undefined && identity !== session) {
25079
+ reconnect();
25080
+ }
25081
+ session = identity;
25082
+ }
25083
+ return page;
25084
+ },
25085
+ onInvalidations: (paths) => {
25086
+ if (paths.includes("/:layout")) {
25087
+ queries.invalidateAll();
25088
+ }
25089
+ },
25090
+ onQueries: (identities) => queries.invalidate(identities)
25091
+ });
25092
+ let recovery = createRecovery();
25093
+ const releaseConnection = () => {
25094
+ connection?.stop?.();
25095
+ connection = undefined;
25096
+ clearTimeout(timer);
25097
+ timer = undefined;
25098
+ };
25099
+ const fail = (value) => {
25100
+ if (!active()) {
25101
+ return;
25102
+ }
25103
+ const error = asError(value);
25104
+ releaseConnection();
25105
+ if (unauthorized(error)) {
25106
+ generation += 1;
25107
+ const epoch = generation;
25108
+ recovery.close();
25109
+ state = { status: "unauthorized", error };
25110
+ controller.abort();
25111
+ ready.resolve();
25112
+ queries.clear();
25113
+ if (epoch === generation) {
25114
+ publish("unauthorized", error);
25115
+ }
25116
+ return;
25117
+ }
25118
+ const delay = Math.min(250 * 2 ** attempt, 5000);
25119
+ attempt += 1;
25120
+ timer = setTimeout(() => {
25121
+ timer = undefined;
25122
+ connect();
25123
+ }, delay);
25124
+ publish("reconnecting", error, "network");
25125
+ };
25126
+ const checkAccess = (url, status, error) => {
25127
+ if (status === 403) {
25128
+ queries.setError(url, error);
25129
+ } else if (status === 401) {
25130
+ fail(new SyncClientError("Live query access refused", status));
25131
+ if (state.status === "unauthorized") {
25132
+ queries.setError(url, error);
25133
+ }
25134
+ }
25135
+ };
25136
+ const connect = async () => {
25137
+ const epoch = generation;
25138
+ try {
25139
+ await recovery.catchUp();
25140
+ if (epoch !== generation || !active()) {
25141
+ return;
25142
+ }
25143
+ const requestHeaders = await headers();
25144
+ if (epoch !== generation || !active()) {
25145
+ return;
25146
+ }
25147
+ const current = {};
25148
+ connection = current;
25149
+ const stop = await transport.subscribe({
25150
+ headers: requestHeaders,
25151
+ signal: controller.signal,
25152
+ onContextChange: () => {
25153
+ if (epoch === generation && connection === current && active()) {
25154
+ reconnect(undefined, true);
25155
+ }
25156
+ },
25157
+ onCursor: () => {
25158
+ recovery.catchUp().then(() => {
25159
+ if (epoch === generation && active() && connection === current) {
25160
+ const reconnecting = state.status === "reconnecting";
25161
+ attempt = 0;
25162
+ ready.resolve();
25163
+ publish("connected", null);
25164
+ if (reconnecting && epoch === generation && connection === current) {
25165
+ for (const url of subscriptions.values()) {
25166
+ queries.fetch(url);
25167
+ }
25168
+ }
25169
+ }
25170
+ }).catch((error) => {
25171
+ if (epoch === generation && connection === current) {
25172
+ fail(error);
25173
+ }
25174
+ });
25175
+ },
25176
+ onError: (error) => {
25177
+ if (epoch === generation && connection === current) {
25178
+ fail(error);
25179
+ }
25180
+ }
25181
+ });
25182
+ if (epoch !== generation || !active() || connection !== current) {
25183
+ stop();
25184
+ return;
25185
+ }
25186
+ current.stop = stop;
25187
+ } catch (error) {
25188
+ if (epoch === generation) {
25189
+ fail(error);
25190
+ }
25191
+ }
25192
+ };
25193
+ function reconnect(reconnectOptions, automatic) {
25194
+ if (state.status === "closed") {
25195
+ return;
25196
+ }
25197
+ generation += 1;
25198
+ const epoch = generation;
25199
+ releaseConnection();
25200
+ const cursor = reconnectOptions?.preserveCache ? recovery.cursor() : undefined;
25201
+ recovery.close();
25202
+ controller.abort();
25203
+ ready.resolve();
25204
+ controller = new AbortController;
25205
+ ready = Promise.withResolvers();
25206
+ recovery = createRecovery();
25207
+ if (cursor === undefined) {
25208
+ session = undefined;
25209
+ } else {
25210
+ recovery.seed(cursor);
25211
+ }
25212
+ const delay = Math.min(250 * 2 ** attempt, 5000);
25213
+ attempt = automatic ? attempt + 1 : 0;
25214
+ queries.clear(reconnectOptions?.preserveCache);
25215
+ if (epoch !== generation) {
25216
+ return;
25217
+ }
25218
+ publish(automatic ? "reconnecting" : "connecting", null, reconnectOptions?.preserveCache ? "credentials" : "context");
25219
+ if (epoch !== generation) {
25220
+ return;
25221
+ }
25222
+ if (automatic) {
25223
+ timer = setTimeout(() => {
25224
+ timer = undefined;
25225
+ connect();
25226
+ }, delay);
25227
+ } else {
25228
+ connect();
25229
+ }
25230
+ queries.invalidateAll();
25231
+ }
25232
+ return {
25233
+ subscribe(query, listener) {
25234
+ if (state.status === "closed") {
25235
+ throw new SyncClientError("Sync client is closed", undefined);
25236
+ }
25237
+ const { reference, options: readOptions } = query[LIVE_QUERY];
25238
+ if (!transport.accepts(reference)) {
25239
+ throw new SyncClientError("Live query belongs to a different server", undefined);
25240
+ }
25241
+ const url = queries.readKey(reference, readOptions);
25242
+ queries.bind(url, async () => {
25243
+ const { signal } = controller;
25244
+ try {
25245
+ await ready.promise;
25246
+ signal.throwIfAborted();
25247
+ const read = readOptions;
25248
+ const fetch2 = { ...options.fetch, ...read?.fetch };
25249
+ fetch2.signal = fetch2.signal ? AbortSignal.any([signal, fetch2.signal]) : signal;
25250
+ const result = await reference.load({
25251
+ ...read,
25252
+ ...options.headers === undefined ? {} : { headers: [read?.headers, await headers()] },
25253
+ fetch: fetch2
25254
+ });
25255
+ signal.throwIfAborted();
25256
+ checkAccess(url, result.response?.status, result.error);
25257
+ return result;
25258
+ } catch (error) {
25259
+ if (signal.aborted) {
25260
+ throw asError(signal.reason);
25261
+ }
25262
+ if (isEdenError(error)) {
25263
+ checkAccess(url, error.status, error);
25264
+ return { data: null, error };
25265
+ }
25266
+ throw asError(error);
25267
+ }
25268
+ }, reference.client);
25269
+ let stopped = false;
25270
+ const unlisten = queries.subscribe(url, () => {
25271
+ if (!stopped) {
25272
+ listener(queries.snapshot(url));
25273
+ }
25274
+ });
25275
+ const stop = () => {
25276
+ stopped = true;
25277
+ unlisten();
25278
+ subscriptions.delete(stop);
25279
+ };
25280
+ subscriptions.set(stop, url);
25281
+ listener(queries.snapshot(url));
25282
+ if (!subscriptions.has(stop)) {
25283
+ return stop;
25284
+ }
25285
+ if (state.status === "idle") {
25286
+ publish("connecting", null);
25287
+ connect();
25288
+ }
25289
+ queries.fetch(url);
25290
+ return stop;
25291
+ },
25292
+ getConnectionState: () => state,
25293
+ subscribeConnection(listener) {
25294
+ if (state.status === "closed") {
25295
+ listener(state);
25296
+ return () => {
25297
+ return;
25298
+ };
25299
+ }
25300
+ listeners.add(listener);
25301
+ listener(state);
25302
+ return () => {
25303
+ listeners.delete(listener);
25304
+ };
25305
+ },
25306
+ reconnect,
25307
+ close() {
25308
+ if (state.status === "closed") {
25309
+ return;
25310
+ }
25311
+ generation += 1;
25312
+ publish("closed", null);
25313
+ releaseConnection();
25314
+ recovery.close();
25315
+ controller.abort();
25316
+ ready.resolve();
25317
+ for (const stop of subscriptions.keys()) {
25318
+ stop();
25319
+ }
25320
+ listeners.clear();
25321
+ queries.dispose();
25322
+ }
25323
+ };
24609
25324
  }
24610
25325
 
25326
+ // src/server/sync/local-client.ts
25327
+ init_connection();
25328
+ init_stream();
25329
+ function createLocalSyncClient(options) {
25330
+ const changesUrl = new URL(`${options.syncPath ?? options.sync.path ?? "/_furin/sync"}/changes`, "http://e.ly");
25331
+ return createSyncClientRuntime(options, {
25332
+ accepts: (reference) => reference.application === options.app,
25333
+ fetchChanges: (after, headers, signal) => {
25334
+ const url = new URL(changesUrl);
25335
+ url.searchParams.set("after", after ?? "0");
25336
+ return options.app.handle(new Request(url, { ...options.fetch, headers, signal }));
25337
+ },
25338
+ subscribe: async ({ headers, signal, onCursor, onContextChange }) => {
25339
+ let access;
25340
+ let unsubscribe;
25341
+ const stop = () => {
25342
+ signal.removeEventListener("abort", stop);
25343
+ access?.close();
25344
+ unsubscribe?.();
25345
+ };
25346
+ signal.addEventListener("abort", stop, { once: true });
25347
+ const request = new Request(changesUrl, {
25348
+ ...options.fetch,
25349
+ headers,
25350
+ signal
25351
+ });
25352
+ request[LOCAL_SYNC_CONNECTION] = async (context, sync) => {
25353
+ access = createSyncConnectionLifetime(sync, context, onContextChange);
25354
+ await access.acquire();
25355
+ if (signal.aborted) {
25356
+ return;
25357
+ }
25358
+ const subscription = await subscribeSyncCursor(sync, IS_DEV, onCursor);
25359
+ if (signal.aborted) {
25360
+ subscription.unsubscribe();
25361
+ } else {
25362
+ ({ unsubscribe } = subscription);
25363
+ }
25364
+ };
25365
+ try {
25366
+ signal.throwIfAborted();
25367
+ const response = await options.app.handle(request);
25368
+ signal.throwIfAborted();
25369
+ if (!response.ok) {
25370
+ throw new SyncClientError("Local sync connection refused", response.status);
25371
+ }
25372
+ if (!access) {
25373
+ throw new SyncClientError("Local sync endpoint does not support event connections", undefined);
25374
+ }
25375
+ return stop;
25376
+ } catch (error) {
25377
+ stop();
25378
+ throw error;
25379
+ }
25380
+ }
25381
+ });
25382
+ }
24611
25383
  // src/server/sync/index.ts
24612
25384
  var furinSync2 = furinSync;
24613
25385
  var invalidateSync2 = invalidateSync;
@@ -24802,6 +25574,7 @@ export {
24802
25574
  Scripts,
24803
25575
  buildErrorElement,
24804
25576
  createIsomorphicFn,
25577
+ createLocalSyncClient,
24805
25578
  defer,
24806
25579
  defineRootRoute,
24807
25580
  defineRoute,