@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.14

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 (58) hide show
  1. package/README.md +14 -232
  2. package/dist/await.d.ts +67 -0
  3. package/dist/build/index.js +2013 -191
  4. package/dist/cli/index.js +2007 -190
  5. package/dist/client.d.ts +33 -2
  6. package/dist/client.js +65 -1
  7. package/dist/deferred-ndjson.d.ts +32 -0
  8. package/dist/error.d.ts +14 -0
  9. package/dist/furin.d.ts +3 -0
  10. package/dist/furin.js +2684 -318
  11. package/dist/lang-detect.d.ts +5 -0
  12. package/dist/link.d.ts +1 -0
  13. package/dist/link.js +1453 -95
  14. package/dist/plugin/index.js +96 -25
  15. package/dist/plugin/transform-client.d.ts +2 -1
  16. package/dist/render/assemble.d.ts +32 -0
  17. package/dist/render/cache.d.ts +7 -0
  18. package/dist/render/element.d.ts +17 -1
  19. package/dist/render/index.d.ts +10 -1
  20. package/dist/render/index.ts +247 -44
  21. package/dist/render/loaders.d.ts +46 -3
  22. package/dist/render/shell.d.ts +16 -6
  23. package/dist/render/shell.ts +27 -12
  24. package/dist/router-provider.d.ts +86 -18
  25. package/dist/router.d.ts +63 -0
  26. package/dist/router.js +2768 -317
  27. package/dist/router.ts +543 -54
  28. package/dist/server-error.d.ts +12 -0
  29. package/dist/utils.d.ts +7 -0
  30. package/package.json +8 -7
  31. package/src/adapter/bun.ts +3 -3
  32. package/src/adapter/static.ts +73 -31
  33. package/src/await.tsx +175 -0
  34. package/src/build/client.ts +4 -8
  35. package/src/build/hydrate.ts +67 -1
  36. package/src/build/route-types.ts +5 -1
  37. package/src/build/scan-server.ts +6 -23
  38. package/src/client.ts +58 -1
  39. package/src/deferred-ndjson.ts +212 -0
  40. package/src/dev-page-plugin.ts +2 -0
  41. package/src/error.ts +18 -1
  42. package/src/furin.ts +12 -2
  43. package/src/lang-detect.ts +46 -0
  44. package/src/link.tsx +16 -3
  45. package/src/plugin/index.ts +7 -8
  46. package/src/plugin/transform-client.ts +108 -39
  47. package/src/render/assemble.ts +67 -0
  48. package/src/render/boundaries.tsx +23 -5
  49. package/src/render/cache.ts +7 -0
  50. package/src/render/default-screens.tsx +4 -11
  51. package/src/render/element.tsx +26 -3
  52. package/src/render/index.ts +247 -44
  53. package/src/render/loaders.ts +221 -18
  54. package/src/render/shell.ts +27 -12
  55. package/src/router-provider.tsx +414 -122
  56. package/src/router.ts +543 -54
  57. package/src/server-error.ts +47 -0
  58. package/src/utils.ts +31 -0
package/dist/link.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // src/link.tsx
3
3
  import { createElement as createElement2, useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2 } from "react";
4
4
 
5
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/utils.mjs
5
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/utils.mjs
6
6
  function formatDuration(ms) {
7
7
  if (ms < 1000)
8
8
  return `${Math.round(ms)}ms`;
@@ -91,7 +91,7 @@ function escapeFormatString(str) {
91
91
  return str.replace(/%/g, "%%");
92
92
  }
93
93
 
94
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/audit-DQoBo7Dl.mjs
94
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/audit-pV5aLGP0.mjs
95
95
  var DEFAULT_REPLACEMENT = "[REDACTED]";
96
96
  var builtinPatterns = {
97
97
  creditCard: {
@@ -242,6 +242,117 @@ function applyMaskers(value, maskers) {
242
242
  }
243
243
  return result;
244
244
  }
245
+ function logPluginError(name, hook, err) {
246
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
247
+ }
248
+ function createPluginRunner(plugins = []) {
249
+ const byName = /* @__PURE__ */ new Map;
250
+ for (const plugin of plugins)
251
+ byName.set(plugin.name, plugin);
252
+ const list = Array.from(byName.values());
253
+ return {
254
+ plugins: list,
255
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
256
+ hasDrain: list.some((p) => typeof p.drain === "function"),
257
+ hasKeep: list.some((p) => typeof p.keep === "function"),
258
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
259
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
260
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
261
+ applyExtendLogger(logger) {
262
+ for (const plugin of list) {
263
+ if (!plugin.extendLogger)
264
+ continue;
265
+ try {
266
+ plugin.extendLogger(logger);
267
+ } catch (err) {
268
+ logPluginError(plugin.name, "extendLogger", err);
269
+ }
270
+ }
271
+ },
272
+ runOnRequestStart(ctx) {
273
+ for (const plugin of list) {
274
+ if (!plugin.onRequestStart)
275
+ continue;
276
+ try {
277
+ plugin.onRequestStart(ctx);
278
+ } catch (err) {
279
+ logPluginError(plugin.name, "onRequestStart", err);
280
+ }
281
+ }
282
+ },
283
+ runOnRequestFinish(ctx) {
284
+ for (const plugin of list) {
285
+ if (!plugin.onRequestFinish)
286
+ continue;
287
+ try {
288
+ plugin.onRequestFinish(ctx);
289
+ } catch (err) {
290
+ logPluginError(plugin.name, "onRequestFinish", err);
291
+ }
292
+ }
293
+ },
294
+ async runEnrich(ctx) {
295
+ for (const plugin of list) {
296
+ if (!plugin.enrich)
297
+ continue;
298
+ try {
299
+ await plugin.enrich(ctx);
300
+ } catch (err) {
301
+ logPluginError(plugin.name, "enrich", err);
302
+ }
303
+ }
304
+ },
305
+ async runDrain(ctx) {
306
+ const drains = list.filter((p) => typeof p.drain === "function");
307
+ if (drains.length === 0)
308
+ return;
309
+ await Promise.allSettled(drains.map(async (plugin) => {
310
+ try {
311
+ await plugin.drain(ctx);
312
+ } catch (err) {
313
+ logPluginError(plugin.name, "drain", err);
314
+ }
315
+ }));
316
+ },
317
+ async runKeep(ctx) {
318
+ for (const plugin of list) {
319
+ if (!plugin.keep)
320
+ continue;
321
+ try {
322
+ await plugin.keep(ctx);
323
+ } catch (err) {
324
+ logPluginError(plugin.name, "keep", err);
325
+ }
326
+ }
327
+ },
328
+ runOnClientLog(ctx) {
329
+ for (const plugin of list) {
330
+ if (!plugin.onClientLog)
331
+ continue;
332
+ try {
333
+ plugin.onClientLog(ctx);
334
+ } catch (err) {
335
+ logPluginError(plugin.name, "onClientLog", err);
336
+ }
337
+ }
338
+ },
339
+ async runSetup(ctx) {
340
+ for (const plugin of list) {
341
+ if (!plugin.setup)
342
+ continue;
343
+ try {
344
+ await plugin.setup(ctx);
345
+ } catch (err) {
346
+ logPluginError(plugin.name, "setup", err);
347
+ }
348
+ }
349
+ }
350
+ };
351
+ }
352
+ var emptyRunner = createPluginRunner([]);
353
+ function getEmptyPluginRunner() {
354
+ return emptyRunner;
355
+ }
245
356
  var _tsDate = /* @__PURE__ */ new Date;
246
357
  function isoNow() {
247
358
  _tsDate.setTime(Date.now());
@@ -259,6 +370,7 @@ var globalRedact;
259
370
  var globalEnabled = true;
260
371
  var globalSilent = false;
261
372
  var globalMinLevel = "debug";
373
+ var globalPluginRunner = getEmptyPluginRunner();
262
374
  function initLogger(config = {}) {
263
375
  globalEnabled = config.enabled ?? true;
264
376
  const detected = detectEnvironment();
@@ -276,7 +388,11 @@ function initLogger(config = {}) {
276
388
  globalRedact = resolveRedactConfig(config.redact ?? !isDev());
277
389
  globalSilent = config.silent ?? false;
278
390
  globalMinLevel = config.minLevel ?? "debug";
279
- if (globalSilent && !globalDrain && !config._suppressDrainWarning)
391
+ globalPluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
392
+ if (globalPluginRunner.plugins.length > 0)
393
+ globalPluginRunner.runSetup({ env: { ...globalEnv } });
394
+ const hasAnyDrain = !!globalDrain || globalPluginRunner.hasDrain;
395
+ if (globalSilent && !hasAnyDrain && !config._suppressDrainWarning)
280
396
  console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
281
397
  }
282
398
  function shouldSample(level) {
@@ -332,12 +448,20 @@ function emitWideEvent(level, event, options = {}) {
332
448
  console[getConsoleMethod(level)](JSON.stringify(formatted));
333
449
  else
334
450
  console[getConsoleMethod(level)](formatted);
335
- if (globalDrain && !deferDrain) {
336
- const drainPromise = Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
337
- console.error("[evlog] drain failed:", err);
338
- });
339
- if (waitUntil)
340
- waitUntil(drainPromise);
451
+ if (!deferDrain) {
452
+ const drainPromises = [];
453
+ if (globalDrain)
454
+ drainPromises.push((async () => {
455
+ try {
456
+ await globalDrain({ event: formatted });
457
+ } catch (err) {
458
+ console.error("[evlog] drain failed:", err);
459
+ }
460
+ })());
461
+ if (globalPluginRunner.hasDrain)
462
+ drainPromises.push(globalPluginRunner.runDrain({ event: formatted }));
463
+ if (drainPromises.length > 0 && waitUntil)
464
+ waitUntil(Promise.all(drainPromises));
341
465
  }
342
466
  return formatted;
343
467
  }
@@ -694,6 +818,7 @@ function finalizeAudit(event) {
694
818
  return;
695
819
  event.audit = decorateAudit(a, String(event.timestamp));
696
820
  }
821
+
697
822
  // src/router-provider.tsx
698
823
  import {
699
824
  createContext,
@@ -707,13 +832,1110 @@ import {
707
832
  useState
708
833
  } from "react";
709
834
 
835
+ // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
836
+ var ALL_ENABLED = 1 | 2 | 4 | 8 | 16 | 32;
837
+ var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
838
+ var SYM_HAS_INSTANCE = Symbol.hasInstance;
839
+ var SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
840
+ var SYM_ITERATOR = Symbol.iterator;
841
+ var SYM_MATCH = Symbol.match;
842
+ var SYM_MATCH_ALL = Symbol.matchAll;
843
+ var SYM_REPLACE = Symbol.replace;
844
+ var SYM_SEARCH = Symbol.search;
845
+ var SYM_SPECIES = Symbol.species;
846
+ var SYM_SPLIT = Symbol.split;
847
+ var SYM_TO_PRIMITIVE = Symbol.toPrimitive;
848
+ var SYM_TO_STRING_TAG = Symbol.toStringTag;
849
+ var SYM_UNSCOPABLES = Symbol.unscopables;
850
+ var INV_SYMBOL_REF = {
851
+ [SYM_ASYNC_ITERATOR]: 0,
852
+ [SYM_HAS_INSTANCE]: 1,
853
+ [SYM_IS_CONCAT_SPREADABLE]: 2,
854
+ [SYM_ITERATOR]: 3,
855
+ [SYM_MATCH]: 4,
856
+ [SYM_MATCH_ALL]: 5,
857
+ [SYM_REPLACE]: 6,
858
+ [SYM_SEARCH]: 7,
859
+ [SYM_SPECIES]: 8,
860
+ [SYM_SPLIT]: 9,
861
+ [SYM_TO_PRIMITIVE]: 10,
862
+ [SYM_TO_STRING_TAG]: 11,
863
+ [SYM_UNSCOPABLES]: 12
864
+ };
865
+ var SYMBOL_REF = {
866
+ [0]: SYM_ASYNC_ITERATOR,
867
+ [1]: SYM_HAS_INSTANCE,
868
+ [2]: SYM_IS_CONCAT_SPREADABLE,
869
+ [3]: SYM_ITERATOR,
870
+ [4]: SYM_MATCH,
871
+ [5]: SYM_MATCH_ALL,
872
+ [6]: SYM_REPLACE,
873
+ [7]: SYM_SEARCH,
874
+ [8]: SYM_SPECIES,
875
+ [9]: SYM_SPLIT,
876
+ [10]: SYM_TO_PRIMITIVE,
877
+ [11]: SYM_TO_STRING_TAG,
878
+ [12]: SYM_UNSCOPABLES
879
+ };
880
+ var NIL = undefined;
881
+ var CONSTANT_VAL = {
882
+ [2]: true,
883
+ [3]: false,
884
+ [1]: NIL,
885
+ [0]: null,
886
+ [4]: -0,
887
+ [5]: Number.POSITIVE_INFINITY,
888
+ [6]: Number.NEGATIVE_INFINITY,
889
+ [7]: Number.NaN
890
+ };
891
+ var ERROR_CONSTRUCTOR = {
892
+ [0]: Error,
893
+ [1]: EvalError,
894
+ [2]: RangeError,
895
+ [3]: ReferenceError,
896
+ [4]: SyntaxError,
897
+ [5]: TypeError,
898
+ [6]: URIError
899
+ };
900
+ function serializeChar(str) {
901
+ switch (str) {
902
+ case '"':
903
+ return "\\\"";
904
+ case "\\":
905
+ return "\\\\";
906
+ case `
907
+ `:
908
+ return "\\n";
909
+ case "\r":
910
+ return "\\r";
911
+ case "\b":
912
+ return "\\b";
913
+ case "\t":
914
+ return "\\t";
915
+ case "\f":
916
+ return "\\f";
917
+ case "<":
918
+ return "\\x3C";
919
+ case "\u2028":
920
+ return "\\u2028";
921
+ case "\u2029":
922
+ return "\\u2029";
923
+ default:
924
+ return NIL;
925
+ }
926
+ }
927
+ function serializeString(str) {
928
+ let result = "";
929
+ let lastPos = 0;
930
+ let replacement;
931
+ for (let i = 0, len = str.length;i < len; i++) {
932
+ replacement = serializeChar(str[i]);
933
+ if (replacement) {
934
+ result += str.slice(lastPos, i) + replacement;
935
+ lastPos = i + 1;
936
+ }
937
+ }
938
+ if (lastPos === 0) {
939
+ result = str;
940
+ } else {
941
+ result += str.slice(lastPos);
942
+ }
943
+ return result;
944
+ }
945
+ function deserializeReplacer(str) {
946
+ switch (str) {
947
+ case "\\\\":
948
+ return "\\";
949
+ case "\\\"":
950
+ return '"';
951
+ case "\\n":
952
+ return `
953
+ `;
954
+ case "\\r":
955
+ return "\r";
956
+ case "\\b":
957
+ return "\b";
958
+ case "\\t":
959
+ return "\t";
960
+ case "\\f":
961
+ return "\f";
962
+ case "\\x3C":
963
+ return "<";
964
+ case "\\u2028":
965
+ return "\u2028";
966
+ case "\\u2029":
967
+ return "\u2029";
968
+ default:
969
+ return str;
970
+ }
971
+ }
972
+ function deserializeString(str) {
973
+ return str.replace(/(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g, deserializeReplacer);
974
+ }
975
+ var REFERENCES_KEY = "__SEROVAL_REFS__";
976
+ var GLOBAL_CONTEXT_REFERENCES = "$R";
977
+ var GLOBAL_CONTEXT_R = `self.${GLOBAL_CONTEXT_REFERENCES}`;
978
+ var INV_REFERENCE = /* @__PURE__ */ new Map;
979
+ function hasReference(id) {
980
+ return INV_REFERENCE.has(id);
981
+ }
982
+ function getReference(id) {
983
+ if (hasReference(id)) {
984
+ return INV_REFERENCE.get(id);
985
+ }
986
+ throw new SerovalMissingReferenceForIdError(id);
987
+ }
988
+ if (typeof globalThis !== "undefined") {
989
+ Object.defineProperty(globalThis, REFERENCES_KEY, {
990
+ value: INV_REFERENCE,
991
+ configurable: true,
992
+ writable: false,
993
+ enumerable: false
994
+ });
995
+ } else if (typeof window !== "undefined") {
996
+ Object.defineProperty(window, REFERENCES_KEY, {
997
+ value: INV_REFERENCE,
998
+ configurable: true,
999
+ writable: false,
1000
+ enumerable: false
1001
+ });
1002
+ } else if (typeof self !== "undefined") {
1003
+ Object.defineProperty(self, REFERENCES_KEY, {
1004
+ value: INV_REFERENCE,
1005
+ configurable: true,
1006
+ writable: false,
1007
+ enumerable: false
1008
+ });
1009
+ } else if (typeof global !== "undefined") {
1010
+ Object.defineProperty(global, REFERENCES_KEY, {
1011
+ value: INV_REFERENCE,
1012
+ configurable: true,
1013
+ writable: false,
1014
+ enumerable: false
1015
+ });
1016
+ }
1017
+ var { toString: objectToString } = Object.prototype;
1018
+ function getErrorMessageDev(type, cause) {
1019
+ if (cause instanceof Error) {
1020
+ return `Seroval caught an error during the ${type} process.
1021
+
1022
+ ${cause.name}
1023
+ ${cause.message}
1024
+
1025
+ - For more information, please check the "cause" property of this error.
1026
+ - If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;
1027
+ }
1028
+ return `Seroval caught an error during the ${type} process.
1029
+
1030
+ "${objectToString.call(cause)}"
1031
+
1032
+ For more information, please check the "cause" property of this error.`;
1033
+ }
1034
+ var getErrorMessage = (type, cause) => getErrorMessageDev(type, cause);
1035
+ var SerovalError = class extends Error {
1036
+ constructor(type, cause) {
1037
+ super(getErrorMessage(type, cause));
1038
+ this.cause = cause;
1039
+ }
1040
+ };
1041
+ var SerovalDeserializationError = class extends SerovalError {
1042
+ constructor(cause) {
1043
+ super("deserialization", cause);
1044
+ }
1045
+ };
1046
+ var SerovalUnsupportedNodeError = class extends Error {
1047
+ constructor(node) {
1048
+ super('Unsupported node type "' + node.t + '".');
1049
+ }
1050
+ };
1051
+ var SerovalMissingPluginError = class extends Error {
1052
+ constructor(tag) {
1053
+ super('Missing plugin for tag "' + tag + '".');
1054
+ }
1055
+ };
1056
+ var SerovalMissingInstanceError = class extends Error {
1057
+ constructor(tag) {
1058
+ super('Missing "' + tag + '" instance.');
1059
+ }
1060
+ };
1061
+ var SerovalMissingReferenceForIdError = class extends Error {
1062
+ constructor(id) {
1063
+ super('Missing reference for id "' + serializeString(id) + '"');
1064
+ }
1065
+ };
1066
+ var SerovalUnknownTypedArrayError = class extends Error {
1067
+ constructor(name) {
1068
+ super('Unknown TypedArray "' + name + '"');
1069
+ }
1070
+ };
1071
+ var SerovalMalformedNodeError = class extends Error {
1072
+ constructor(node) {
1073
+ super('Malformed node type "' + node.t + '".');
1074
+ }
1075
+ };
1076
+ var SerovalDepthLimitError = class extends Error {
1077
+ constructor(limit) {
1078
+ super("Depth limit of " + limit + " reached");
1079
+ }
1080
+ };
1081
+ var PROMISE_CONSTRUCTOR = () => {
1082
+ const resolver = {
1083
+ p: 0,
1084
+ s: 0,
1085
+ f: 0
1086
+ };
1087
+ resolver.p = new Promise((resolve, reject) => {
1088
+ resolver.s = resolve;
1089
+ resolver.f = reject;
1090
+ });
1091
+ return resolver;
1092
+ };
1093
+ var STREAM_CONSTRUCTOR = () => {
1094
+ const buffer = [];
1095
+ const listeners = [];
1096
+ let alive = true;
1097
+ let success = false;
1098
+ let count = 0;
1099
+ const flush = (value, mode, x) => {
1100
+ for (x = 0;x < count; x++) {
1101
+ if (listeners[x]) {
1102
+ listeners[x][mode](value);
1103
+ }
1104
+ }
1105
+ };
1106
+ const up = (listener, x, z, current) => {
1107
+ for (x = 0, z = buffer.length;x < z; x++) {
1108
+ current = buffer[x];
1109
+ if (!alive && x === z - 1) {
1110
+ listener[success ? "return" : "throw"](current);
1111
+ } else {
1112
+ listener.next(current);
1113
+ }
1114
+ }
1115
+ };
1116
+ const on = (listener, temp) => {
1117
+ if (alive) {
1118
+ temp = count++;
1119
+ listeners[temp] = listener;
1120
+ }
1121
+ up(listener);
1122
+ return () => {
1123
+ if (alive) {
1124
+ listeners[temp] = listeners[count];
1125
+ listeners[count--] = undefined;
1126
+ }
1127
+ };
1128
+ };
1129
+ return {
1130
+ __SEROVAL_STREAM__: true,
1131
+ on: (listener) => on(listener),
1132
+ next: (value) => {
1133
+ if (alive) {
1134
+ buffer.push(value);
1135
+ flush(value, "next");
1136
+ }
1137
+ },
1138
+ throw: (value) => {
1139
+ if (alive) {
1140
+ buffer.push(value);
1141
+ flush(value, "throw");
1142
+ alive = false;
1143
+ success = false;
1144
+ listeners.length = 0;
1145
+ }
1146
+ },
1147
+ return: (value) => {
1148
+ if (alive) {
1149
+ buffer.push(value);
1150
+ flush(value, "return");
1151
+ alive = false;
1152
+ success = true;
1153
+ listeners.length = 0;
1154
+ }
1155
+ }
1156
+ };
1157
+ };
1158
+ var ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
1159
+ let index = 0;
1160
+ const instance = {
1161
+ [symbol]: () => instance,
1162
+ next: () => {
1163
+ if (index > sequence.d) {
1164
+ return {
1165
+ done: true,
1166
+ value: undefined
1167
+ };
1168
+ }
1169
+ const currentIndex = index++;
1170
+ const data = sequence.v[currentIndex];
1171
+ if (currentIndex === sequence.t) {
1172
+ throw data;
1173
+ }
1174
+ return {
1175
+ done: currentIndex === sequence.d,
1176
+ value: data
1177
+ };
1178
+ }
1179
+ };
1180
+ return instance;
1181
+ };
1182
+ var ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
1183
+ let count = 0;
1184
+ let doneAt = -1;
1185
+ let isThrow = false;
1186
+ const buffer = [];
1187
+ const pending = [];
1188
+ const finalize = (i = 0, len = pending.length) => {
1189
+ for (;i < len; i++) {
1190
+ pending[i].s({
1191
+ done: true,
1192
+ value: undefined
1193
+ });
1194
+ }
1195
+ };
1196
+ stream.on({
1197
+ next: (value) => {
1198
+ const temp = pending.shift();
1199
+ if (temp) {
1200
+ temp.s({ done: false, value });
1201
+ }
1202
+ buffer.push(value);
1203
+ },
1204
+ throw: (value) => {
1205
+ const temp = pending.shift();
1206
+ if (temp) {
1207
+ temp.f(value);
1208
+ }
1209
+ finalize();
1210
+ doneAt = buffer.length;
1211
+ isThrow = true;
1212
+ buffer.push(value);
1213
+ },
1214
+ return: (value) => {
1215
+ const temp = pending.shift();
1216
+ if (temp) {
1217
+ temp.s({ done: true, value });
1218
+ }
1219
+ finalize();
1220
+ doneAt = buffer.length;
1221
+ buffer.push(value);
1222
+ }
1223
+ });
1224
+ const instance = {
1225
+ [symbol]: () => instance,
1226
+ next: () => {
1227
+ if (doneAt === -1) {
1228
+ const index2 = count++;
1229
+ if (index2 >= buffer.length) {
1230
+ const temp = createPromise();
1231
+ pending.push(temp);
1232
+ return temp.p;
1233
+ }
1234
+ return {
1235
+ done: false,
1236
+ value: buffer[index2]
1237
+ };
1238
+ }
1239
+ if (count > doneAt) {
1240
+ return {
1241
+ done: true,
1242
+ value: undefined
1243
+ };
1244
+ }
1245
+ const index = count++;
1246
+ const value = buffer[index];
1247
+ if (index !== doneAt) {
1248
+ return {
1249
+ done: false,
1250
+ value
1251
+ };
1252
+ }
1253
+ if (isThrow) {
1254
+ throw value;
1255
+ }
1256
+ return {
1257
+ done: true,
1258
+ value
1259
+ };
1260
+ }
1261
+ };
1262
+ return instance;
1263
+ };
1264
+ var ARRAY_BUFFER_CONSTRUCTOR = (b64) => {
1265
+ const decoded = atob(b64);
1266
+ const length = decoded.length;
1267
+ const arr = new Uint8Array(length);
1268
+ for (let i = 0;i < length; i++) {
1269
+ arr[i] = decoded.charCodeAt(i);
1270
+ }
1271
+ return arr.buffer;
1272
+ };
1273
+ function createSequence(values, throwAt, doneAt) {
1274
+ return {
1275
+ __SEROVAL_SEQUENCE__: true,
1276
+ v: values,
1277
+ t: throwAt,
1278
+ d: doneAt
1279
+ };
1280
+ }
1281
+ var createIterator = ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
1282
+ function sequenceToIterator(sequence) {
1283
+ return createIterator(sequence);
1284
+ }
1285
+ function createStream() {
1286
+ return STREAM_CONSTRUCTOR();
1287
+ }
1288
+ var createAsyncIterable = ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
1289
+ function streamToAsyncIterable(stream) {
1290
+ return createAsyncIterable(stream);
1291
+ }
1292
+ function dedupePlugins(deduped, plugins) {
1293
+ for (let i = 0, len = plugins.length;i < len; i++) {
1294
+ const current = plugins[i];
1295
+ if (!deduped.has(current)) {
1296
+ deduped.add(current);
1297
+ if (current.extends) {
1298
+ dedupePlugins(deduped, current.extends);
1299
+ }
1300
+ }
1301
+ }
1302
+ }
1303
+ function resolvePlugins(plugins) {
1304
+ if (plugins) {
1305
+ const deduped = /* @__PURE__ */ new Set;
1306
+ dedupePlugins(deduped, plugins);
1307
+ return [...deduped];
1308
+ }
1309
+ return;
1310
+ }
1311
+ function getTypedArrayConstructor(name) {
1312
+ switch (name) {
1313
+ case "Int8Array":
1314
+ return Int8Array;
1315
+ case "Int16Array":
1316
+ return Int16Array;
1317
+ case "Int32Array":
1318
+ return Int32Array;
1319
+ case "Uint8Array":
1320
+ return Uint8Array;
1321
+ case "Uint16Array":
1322
+ return Uint16Array;
1323
+ case "Uint32Array":
1324
+ return Uint32Array;
1325
+ case "Uint8ClampedArray":
1326
+ return Uint8ClampedArray;
1327
+ case "Float32Array":
1328
+ return Float32Array;
1329
+ case "Float64Array":
1330
+ return Float64Array;
1331
+ case "BigInt64Array":
1332
+ return BigInt64Array;
1333
+ case "BigUint64Array":
1334
+ return BigUint64Array;
1335
+ default:
1336
+ throw new SerovalUnknownTypedArrayError(name);
1337
+ }
1338
+ }
1339
+ var MAX_BASE64_LENGTH = 1e6;
1340
+ var MAX_BIGINT_LENGTH = 1e4;
1341
+ var MAX_REGEXP_SOURCE_LENGTH = 20000;
1342
+ function applyObjectFlag(obj, flag) {
1343
+ switch (flag) {
1344
+ case 3:
1345
+ return Object.freeze(obj);
1346
+ case 1:
1347
+ return Object.preventExtensions(obj);
1348
+ case 2:
1349
+ return Object.seal(obj);
1350
+ default:
1351
+ return obj;
1352
+ }
1353
+ }
1354
+ var DEFAULT_DEPTH_LIMIT = 1000;
1355
+ function createBaseDeserializerContext(mode, options) {
1356
+ var _a;
1357
+ const refs = options.refs || /* @__PURE__ */ new Map;
1358
+ if (!("types" in refs)) {
1359
+ Object.assign(refs, {
1360
+ types: /* @__PURE__ */ new Map
1361
+ });
1362
+ }
1363
+ return {
1364
+ mode,
1365
+ plugins: options.plugins,
1366
+ refs,
1367
+ features: (_a = options.features) != null ? _a : ALL_ENABLED ^ (options.disabledFeatures || 0),
1368
+ depthLimit: options.depthLimit || DEFAULT_DEPTH_LIMIT
1369
+ };
1370
+ }
1371
+ function createCrossDeserializerContext(options) {
1372
+ return {
1373
+ mode: 2,
1374
+ base: createBaseDeserializerContext(2, options),
1375
+ child: NIL
1376
+ };
1377
+ }
1378
+ var DeserializePluginContext = class {
1379
+ constructor(_p, depth) {
1380
+ this._p = _p;
1381
+ this.depth = depth;
1382
+ }
1383
+ deserialize(node) {
1384
+ return deserialize(this._p, this.depth, node);
1385
+ }
1386
+ };
1387
+ function guardIndexedValue(ctx, id) {
1388
+ if (id < 0 || !Number.isFinite(id) || !Number.isInteger(id)) {
1389
+ throw new SerovalMalformedNodeError({
1390
+ t: 4,
1391
+ i: id
1392
+ });
1393
+ }
1394
+ if (ctx.refs.has(id)) {
1395
+ throw new Error("Conflicted ref id: " + id);
1396
+ }
1397
+ }
1398
+ function assignIndexedValueVanilla(ctx, id, value) {
1399
+ guardIndexedValue(ctx.base, id);
1400
+ if (ctx.state.marked.has(id)) {
1401
+ ctx.base.refs.set(id, value);
1402
+ }
1403
+ return value;
1404
+ }
1405
+ function assignIndexedValueCross(ctx, id, value) {
1406
+ guardIndexedValue(ctx.base, id);
1407
+ ctx.base.refs.set(id, value);
1408
+ return value;
1409
+ }
1410
+ function assignIndexedValue(ctx, id, value) {
1411
+ return ctx.mode === 1 ? assignIndexedValueVanilla(ctx, id, value) : assignIndexedValueCross(ctx, id, value);
1412
+ }
1413
+ function deserializeKnownValue(node, record, key) {
1414
+ if (Object.hasOwn(record, key)) {
1415
+ return record[key];
1416
+ }
1417
+ throw new SerovalMalformedNodeError(node);
1418
+ }
1419
+ function deserializeReference(ctx, node) {
1420
+ return assignIndexedValue(ctx, node.i, getReference(deserializeString(node.s)));
1421
+ }
1422
+ function deserializeArray(ctx, depth, node) {
1423
+ const items = node.a;
1424
+ const len = items.length;
1425
+ const result = assignIndexedValue(ctx, node.i, new Array(len));
1426
+ for (let i = 0, item;i < len; i++) {
1427
+ item = items[i];
1428
+ if (item) {
1429
+ result[i] = deserialize(ctx, depth, item);
1430
+ }
1431
+ }
1432
+ applyObjectFlag(result, node.o);
1433
+ return result;
1434
+ }
1435
+ function isValidKey(key) {
1436
+ switch (key) {
1437
+ case "constructor":
1438
+ case "__proto__":
1439
+ case "prototype":
1440
+ case "__defineGetter__":
1441
+ case "__defineSetter__":
1442
+ case "__lookupGetter__":
1443
+ case "__lookupSetter__":
1444
+ return false;
1445
+ default:
1446
+ return true;
1447
+ }
1448
+ }
1449
+ function isValidSymbol(symbol) {
1450
+ switch (symbol) {
1451
+ case SYM_ASYNC_ITERATOR:
1452
+ case SYM_IS_CONCAT_SPREADABLE:
1453
+ case SYM_TO_STRING_TAG:
1454
+ case SYM_ITERATOR:
1455
+ return true;
1456
+ default:
1457
+ return false;
1458
+ }
1459
+ }
1460
+ function assignStringProperty(object, key, value) {
1461
+ if (isValidKey(key)) {
1462
+ object[key] = value;
1463
+ } else {
1464
+ Object.defineProperty(object, key, {
1465
+ value,
1466
+ configurable: true,
1467
+ enumerable: true,
1468
+ writable: true
1469
+ });
1470
+ }
1471
+ }
1472
+ function assignProperty(ctx, depth, object, key, value) {
1473
+ if (typeof key === "string") {
1474
+ assignStringProperty(object, deserializeString(key), deserialize(ctx, depth, value));
1475
+ } else {
1476
+ const actual = deserialize(ctx, depth, key);
1477
+ switch (typeof actual) {
1478
+ case "string":
1479
+ assignStringProperty(object, actual, deserialize(ctx, depth, value));
1480
+ break;
1481
+ case "symbol":
1482
+ if (isValidSymbol(actual)) {
1483
+ object[actual] = deserialize(ctx, depth, value);
1484
+ }
1485
+ break;
1486
+ default:
1487
+ throw new SerovalMalformedNodeError(key);
1488
+ }
1489
+ }
1490
+ }
1491
+ function assignNodeType(ctx, id, type) {
1492
+ ctx.base.refs.types.set(id, type);
1493
+ }
1494
+ function validateNodeType(ctx, node, id, type) {
1495
+ if (ctx.base.refs.types.get(id) !== type) {
1496
+ throw new SerovalMalformedNodeError(node);
1497
+ }
1498
+ }
1499
+ function deserializeProperties(ctx, depth, node, result) {
1500
+ const keys = node.k;
1501
+ const len = keys.length;
1502
+ if (len > 0) {
1503
+ for (let i = 0, vals = node.v, len2 = keys.length;i < len2; i++) {
1504
+ assignProperty(ctx, depth, result, keys[i], vals[i]);
1505
+ }
1506
+ }
1507
+ return result;
1508
+ }
1509
+ function deserializeObject(ctx, depth, node) {
1510
+ const result = assignIndexedValue(ctx, node.i, node.t === 10 ? {} : /* @__PURE__ */ Object.create(null));
1511
+ deserializeProperties(ctx, depth, node.p, result);
1512
+ applyObjectFlag(result, node.o);
1513
+ return result;
1514
+ }
1515
+ function deserializeDate(ctx, node) {
1516
+ return assignIndexedValue(ctx, node.i, new Date(node.s));
1517
+ }
1518
+ function deserializeRegExp(ctx, node) {
1519
+ if (ctx.base.features & 32) {
1520
+ const source = deserializeString(node.c);
1521
+ if (source.length > MAX_REGEXP_SOURCE_LENGTH) {
1522
+ throw new SerovalMalformedNodeError(node);
1523
+ }
1524
+ return assignIndexedValue(ctx, node.i, new RegExp(source, node.m));
1525
+ }
1526
+ throw new SerovalUnsupportedNodeError(node);
1527
+ }
1528
+ function deserializeSet(ctx, depth, node) {
1529
+ const result = assignIndexedValue(ctx, node.i, /* @__PURE__ */ new Set);
1530
+ for (let i = 0, items = node.a, len = items.length;i < len; i++) {
1531
+ result.add(deserialize(ctx, depth, items[i]));
1532
+ }
1533
+ return result;
1534
+ }
1535
+ function deserializeMap(ctx, depth, node) {
1536
+ const result = assignIndexedValue(ctx, node.i, /* @__PURE__ */ new Map);
1537
+ for (let i = 0, keys = node.e.k, vals = node.e.v, len = keys.length;i < len; i++) {
1538
+ result.set(deserialize(ctx, depth, keys[i]), deserialize(ctx, depth, vals[i]));
1539
+ }
1540
+ return result;
1541
+ }
1542
+ function deserializeArrayBuffer(ctx, node) {
1543
+ if (node.s.length > MAX_BASE64_LENGTH) {
1544
+ throw new SerovalMalformedNodeError(node);
1545
+ }
1546
+ const result = assignIndexedValue(ctx, node.i, ARRAY_BUFFER_CONSTRUCTOR(deserializeString(node.s)));
1547
+ return result;
1548
+ }
1549
+ function deserializeTypedArray(ctx, depth, node) {
1550
+ var _a;
1551
+ const construct = getTypedArrayConstructor(node.c);
1552
+ const source = deserialize(ctx, depth, node.f);
1553
+ const offset = (_a = node.b) != null ? _a : 0;
1554
+ if (offset < 0 || offset > source.byteLength) {
1555
+ throw new SerovalMalformedNodeError(node);
1556
+ }
1557
+ const result = assignIndexedValue(ctx, node.i, new construct(source, offset, node.l));
1558
+ return result;
1559
+ }
1560
+ function deserializeDataView(ctx, depth, node) {
1561
+ var _a;
1562
+ const source = deserialize(ctx, depth, node.f);
1563
+ const offset = (_a = node.b) != null ? _a : 0;
1564
+ if (offset < 0 || offset > source.byteLength) {
1565
+ throw new SerovalMalformedNodeError(node);
1566
+ }
1567
+ const result = assignIndexedValue(ctx, node.i, new DataView(source, offset, node.l));
1568
+ return result;
1569
+ }
1570
+ function deserializeDictionary(ctx, depth, node, result) {
1571
+ if (node.p) {
1572
+ const fields = deserializeProperties(ctx, depth, node.p, {});
1573
+ Object.defineProperties(result, Object.getOwnPropertyDescriptors(fields));
1574
+ }
1575
+ return result;
1576
+ }
1577
+ function deserializeAggregateError(ctx, depth, node) {
1578
+ const result = assignIndexedValue(ctx, node.i, new AggregateError([], deserializeString(node.m)));
1579
+ return deserializeDictionary(ctx, depth, node, result);
1580
+ }
1581
+ function deserializeError(ctx, depth, node) {
1582
+ const construct = deserializeKnownValue(node, ERROR_CONSTRUCTOR, node.s);
1583
+ const result = assignIndexedValue(ctx, node.i, new construct(deserializeString(node.m)));
1584
+ return deserializeDictionary(ctx, depth, node, result);
1585
+ }
1586
+ function deserializePromise(ctx, depth, node) {
1587
+ const deferred = PROMISE_CONSTRUCTOR();
1588
+ const result = assignIndexedValue(ctx, node.i, deferred.p);
1589
+ const deserialized = deserialize(ctx, depth, node.f);
1590
+ if (node.s) {
1591
+ deferred.s(deserialized);
1592
+ } else {
1593
+ deferred.f(deserialized);
1594
+ }
1595
+ return result;
1596
+ }
1597
+ function deserializeBoxed(ctx, depth, node) {
1598
+ return assignIndexedValue(ctx, node.i, Object(deserialize(ctx, depth, node.f)));
1599
+ }
1600
+ function deserializePlugin(ctx, depth, node) {
1601
+ const currentPlugins = ctx.base.plugins;
1602
+ if (currentPlugins) {
1603
+ const tag = deserializeString(node.c);
1604
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
1605
+ const plugin = currentPlugins[i];
1606
+ if (plugin.tag === tag) {
1607
+ return assignIndexedValue(ctx, node.i, plugin.deserialize(node.s, new DeserializePluginContext(ctx, depth), {
1608
+ id: node.i
1609
+ }));
1610
+ }
1611
+ }
1612
+ }
1613
+ throw new SerovalMissingPluginError(node.c);
1614
+ }
1615
+ function deserializePromiseConstructor(ctx, node) {
1616
+ const value = assignIndexedValue(ctx, node.i, assignIndexedValue(ctx, node.s, PROMISE_CONSTRUCTOR()).p);
1617
+ assignNodeType(ctx, node.s, 22);
1618
+ return value;
1619
+ }
1620
+ function deserializePromiseResolve(ctx, depth, node) {
1621
+ const deferred = ctx.base.refs.get(node.i);
1622
+ if (deferred) {
1623
+ validateNodeType(ctx, node, node.i, 22);
1624
+ deferred.s(deserialize(ctx, depth, node.a[1]));
1625
+ return NIL;
1626
+ }
1627
+ throw new SerovalMissingInstanceError("Promise");
1628
+ }
1629
+ function deserializePromiseReject(ctx, depth, node) {
1630
+ const deferred = ctx.base.refs.get(node.i);
1631
+ if (deferred) {
1632
+ validateNodeType(ctx, node, node.i, 22);
1633
+ deferred.f(deserialize(ctx, depth, node.a[1]));
1634
+ return NIL;
1635
+ }
1636
+ throw new SerovalMissingInstanceError("Promise");
1637
+ }
1638
+ function deserializeIteratorFactoryInstance(ctx, depth, node) {
1639
+ deserialize(ctx, depth, node.a[0]);
1640
+ const source = deserialize(ctx, depth, node.a[1]);
1641
+ return sequenceToIterator(source);
1642
+ }
1643
+ function deserializeAsyncIteratorFactoryInstance(ctx, depth, node) {
1644
+ deserialize(ctx, depth, node.a[0]);
1645
+ const source = deserialize(ctx, depth, node.a[1]);
1646
+ return streamToAsyncIterable(source);
1647
+ }
1648
+ function deserializeStreamConstructor(ctx, depth, node) {
1649
+ const result = assignIndexedValue(ctx, node.i, createStream());
1650
+ assignNodeType(ctx, node.i, 31);
1651
+ const items = node.a;
1652
+ const len = items.length;
1653
+ if (len) {
1654
+ for (let i = 0;i < len; i++) {
1655
+ deserialize(ctx, depth, items[i]);
1656
+ }
1657
+ }
1658
+ return result;
1659
+ }
1660
+ function deserializeStreamNext(ctx, depth, node) {
1661
+ const deferred = ctx.base.refs.get(node.i);
1662
+ if (deferred) {
1663
+ validateNodeType(ctx, node, node.i, 31);
1664
+ deferred.next(deserialize(ctx, depth, node.f));
1665
+ return NIL;
1666
+ }
1667
+ throw new SerovalMissingInstanceError("Stream");
1668
+ }
1669
+ function deserializeStreamThrow(ctx, depth, node) {
1670
+ const deferred = ctx.base.refs.get(node.i);
1671
+ if (deferred) {
1672
+ validateNodeType(ctx, node, node.i, 31);
1673
+ deferred.throw(deserialize(ctx, depth, node.f));
1674
+ return NIL;
1675
+ }
1676
+ throw new SerovalMissingInstanceError("Stream");
1677
+ }
1678
+ function deserializeStreamReturn(ctx, depth, node) {
1679
+ const deferred = ctx.base.refs.get(node.i);
1680
+ if (deferred) {
1681
+ validateNodeType(ctx, node, node.i, 31);
1682
+ deferred.return(deserialize(ctx, depth, node.f));
1683
+ return NIL;
1684
+ }
1685
+ throw new SerovalMissingInstanceError("Stream");
1686
+ }
1687
+ function deserializeIteratorFactory(ctx, depth, node) {
1688
+ deserialize(ctx, depth, node.f);
1689
+ return NIL;
1690
+ }
1691
+ function deserializeAsyncIteratorFactory(ctx, depth, node) {
1692
+ deserialize(ctx, depth, node.a[1]);
1693
+ return NIL;
1694
+ }
1695
+ function deserializeSequence(ctx, depth, node) {
1696
+ const result = assignIndexedValue(ctx, node.i, createSequence([], node.s, node.l));
1697
+ for (let i = 0, len = node.a.length;i < len; i++) {
1698
+ result.v[i] = deserialize(ctx, depth, node.a[i]);
1699
+ }
1700
+ return result;
1701
+ }
1702
+ function deserialize(ctx, depth, node) {
1703
+ if (depth > ctx.base.depthLimit) {
1704
+ throw new SerovalDepthLimitError(ctx.base.depthLimit);
1705
+ }
1706
+ depth += 1;
1707
+ switch (node.t) {
1708
+ case 2:
1709
+ return deserializeKnownValue(node, CONSTANT_VAL, node.s);
1710
+ case 0:
1711
+ return Number(node.s);
1712
+ case 1:
1713
+ return deserializeString(String(node.s));
1714
+ case 3:
1715
+ if (String(node.s).length > MAX_BIGINT_LENGTH) {
1716
+ throw new SerovalMalformedNodeError(node);
1717
+ }
1718
+ return BigInt(node.s);
1719
+ case 4:
1720
+ return ctx.base.refs.get(node.i);
1721
+ case 18:
1722
+ return deserializeReference(ctx, node);
1723
+ case 9:
1724
+ return deserializeArray(ctx, depth, node);
1725
+ case 10:
1726
+ case 11:
1727
+ return deserializeObject(ctx, depth, node);
1728
+ case 5:
1729
+ return deserializeDate(ctx, node);
1730
+ case 6:
1731
+ return deserializeRegExp(ctx, node);
1732
+ case 7:
1733
+ return deserializeSet(ctx, depth, node);
1734
+ case 8:
1735
+ return deserializeMap(ctx, depth, node);
1736
+ case 19:
1737
+ return deserializeArrayBuffer(ctx, node);
1738
+ case 16:
1739
+ case 15:
1740
+ return deserializeTypedArray(ctx, depth, node);
1741
+ case 20:
1742
+ return deserializeDataView(ctx, depth, node);
1743
+ case 14:
1744
+ return deserializeAggregateError(ctx, depth, node);
1745
+ case 13:
1746
+ return deserializeError(ctx, depth, node);
1747
+ case 12:
1748
+ return deserializePromise(ctx, depth, node);
1749
+ case 17:
1750
+ return deserializeKnownValue(node, SYMBOL_REF, node.s);
1751
+ case 21:
1752
+ return deserializeBoxed(ctx, depth, node);
1753
+ case 25:
1754
+ return deserializePlugin(ctx, depth, node);
1755
+ case 22:
1756
+ return deserializePromiseConstructor(ctx, node);
1757
+ case 23:
1758
+ return deserializePromiseResolve(ctx, depth, node);
1759
+ case 24:
1760
+ return deserializePromiseReject(ctx, depth, node);
1761
+ case 28:
1762
+ return deserializeIteratorFactoryInstance(ctx, depth, node);
1763
+ case 30:
1764
+ return deserializeAsyncIteratorFactoryInstance(ctx, depth, node);
1765
+ case 31:
1766
+ return deserializeStreamConstructor(ctx, depth, node);
1767
+ case 32:
1768
+ return deserializeStreamNext(ctx, depth, node);
1769
+ case 33:
1770
+ return deserializeStreamThrow(ctx, depth, node);
1771
+ case 34:
1772
+ return deserializeStreamReturn(ctx, depth, node);
1773
+ case 27:
1774
+ return deserializeIteratorFactory(ctx, depth, node);
1775
+ case 29:
1776
+ return deserializeAsyncIteratorFactory(ctx, depth, node);
1777
+ case 35:
1778
+ return deserializeSequence(ctx, depth, node);
1779
+ default:
1780
+ throw new SerovalUnsupportedNodeError(node);
1781
+ }
1782
+ }
1783
+ function deserializeTop(ctx, node) {
1784
+ try {
1785
+ return deserialize(ctx, 0, node);
1786
+ } catch (error) {
1787
+ throw new SerovalDeserializationError(error);
1788
+ }
1789
+ }
1790
+ var REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_";
1791
+ var REF_START_CHARS_LEN = REF_START_CHARS.length;
1792
+ var REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
1793
+ var REF_CHARS_LEN = REF_CHARS.length;
1794
+ function fromCrossJSON(source, options) {
1795
+ const plugins = resolvePlugins(options.plugins);
1796
+ const ctx = createCrossDeserializerContext({
1797
+ plugins,
1798
+ refs: options.refs,
1799
+ features: options.features,
1800
+ disabledFeatures: options.disabledFeatures,
1801
+ depthLimit: options.depthLimit
1802
+ });
1803
+ return deserializeTop(ctx, source);
1804
+ }
1805
+
1806
+ // src/deferred-ndjson.ts
1807
+ function makeAbortError(reason) {
1808
+ const message = reason instanceof Error ? reason.message || "The operation was aborted." : "aborted";
1809
+ const err = new Error(message);
1810
+ err.name = "AbortError";
1811
+ return err;
1812
+ }
1813
+ async function parseDeferredNdjson(stream, signal) {
1814
+ const reader = stream.getReader();
1815
+ const decoder = new TextDecoder;
1816
+ let buffer = "";
1817
+ async function readLine() {
1818
+ for (;; ) {
1819
+ const newlineIndex = buffer.indexOf(`
1820
+ `);
1821
+ if (newlineIndex >= 0) {
1822
+ const line = buffer.slice(0, newlineIndex).trim();
1823
+ buffer = buffer.slice(newlineIndex + 1);
1824
+ if (line.length > 0) {
1825
+ return line;
1826
+ }
1827
+ continue;
1828
+ }
1829
+ const { done, value } = await reader.read();
1830
+ if (done) {
1831
+ buffer += decoder.decode();
1832
+ const line = buffer.trim();
1833
+ buffer = "";
1834
+ return line.length > 0 ? line : undefined;
1835
+ }
1836
+ buffer += decoder.decode(value, { stream: true });
1837
+ }
1838
+ }
1839
+ const firstLine = await readLine();
1840
+ if (!firstLine) {
1841
+ try {
1842
+ reader.releaseLock();
1843
+ } catch {}
1844
+ return { syncData: {}, deferredPromises: {} };
1845
+ }
1846
+ const node = JSON.parse(firstLine);
1847
+ const deserialized = fromCrossJSON(node, {});
1848
+ const syncData = {};
1849
+ const deferredPromises = {};
1850
+ const resolvers = {};
1851
+ const deferredKeys = Array.isArray(deserialized.__furinDeferredKeys) ? deserialized.__furinDeferredKeys.filter((key) => typeof key === "string") : [];
1852
+ for (const [key, value] of Object.entries(deserialized)) {
1853
+ if (key === "__furinDeferredKeys") {
1854
+ continue;
1855
+ }
1856
+ if (value instanceof Promise) {
1857
+ deferredPromises[key] = value;
1858
+ } else {
1859
+ syncData[key] = value;
1860
+ }
1861
+ }
1862
+ for (const key of deferredKeys) {
1863
+ if (!(key in deferredPromises)) {
1864
+ deferredPromises[key] = new Promise((resolve, reject) => {
1865
+ resolvers[key] = { resolve, reject };
1866
+ });
1867
+ }
1868
+ }
1869
+ if (deferredKeys.length === 0) {
1870
+ try {
1871
+ reader.releaseLock();
1872
+ } catch {}
1873
+ return { syncData, deferredPromises };
1874
+ }
1875
+ const rejectAllPending = (reason) => {
1876
+ for (const key of Object.keys(resolvers)) {
1877
+ resolvers[key]?.reject(reason);
1878
+ delete resolvers[key];
1879
+ }
1880
+ reader.cancel(reason).catch(() => {});
1881
+ };
1882
+ if (signal !== undefined) {
1883
+ if (signal.aborted) {
1884
+ rejectAllPending(makeAbortError(signal.reason));
1885
+ return { syncData, deferredPromises };
1886
+ }
1887
+ signal.addEventListener("abort", () => {
1888
+ rejectAllPending(makeAbortError(signal.reason));
1889
+ }, { once: true });
1890
+ }
1891
+ readDeferredLines(readLine, resolvers).then(() => {
1892
+ for (const key of Object.keys(resolvers)) {
1893
+ const err = new Error(`[furin] deferred stream closed before "${key}" was resolved`);
1894
+ resolvers[key]?.reject(err);
1895
+ delete resolvers[key];
1896
+ }
1897
+ }).catch((err) => {
1898
+ for (const resolver of Object.values(resolvers)) {
1899
+ resolver.reject(err);
1900
+ }
1901
+ }).finally(() => {
1902
+ try {
1903
+ reader.releaseLock();
1904
+ } catch {}
1905
+ });
1906
+ return { syncData, deferredPromises };
1907
+ }
1908
+ async function readDeferredLines(readLine, resolvers) {
1909
+ for (;; ) {
1910
+ const line = await readLine();
1911
+ if (!line) {
1912
+ return;
1913
+ }
1914
+ const entry = JSON.parse(line);
1915
+ if (typeof entry.key !== "string" || !entry.value) {
1916
+ continue;
1917
+ }
1918
+ const resolver = resolvers[entry.key];
1919
+ if (!resolver) {
1920
+ continue;
1921
+ }
1922
+ const value = fromCrossJSON(entry.value, {});
1923
+ if (entry.action === "reject") {
1924
+ resolver.reject(value);
1925
+ } else {
1926
+ resolver.resolve(value);
1927
+ }
1928
+ delete resolvers[entry.key];
1929
+ }
1930
+ }
1931
+
710
1932
  // src/render/boundaries.tsx
711
1933
  import { Component, Fragment } from "react";
712
1934
 
713
1935
  // src/error.ts
714
1936
  function getPublicErrorMessage(error) {
715
1937
  const branded = error;
716
- if (branded?.__furinBrand === "FURIN_NOT_FOUND") {
1938
+ if (branded?.__furinBrand === "FURIN_NOT_FOUND" || branded?.__furinBrand === "FURIN_SERVER_ERROR") {
717
1939
  return error.message;
718
1940
  }
719
1941
  return "Something went wrong";
@@ -734,6 +1956,23 @@ function isNotFoundError(err) {
734
1956
  return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
735
1957
  }
736
1958
 
1959
+ // src/server-error.ts
1960
+ var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
1961
+
1962
+ class FurinServerError extends Error {
1963
+ __furinBrand = SERVER_ERROR_BRAND;
1964
+ digest;
1965
+ status;
1966
+ constructor(args) {
1967
+ super(args.message);
1968
+ this.status = args.status;
1969
+ this.digest = args.digest;
1970
+ }
1971
+ }
1972
+ function isFurinServerError(err) {
1973
+ return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
1974
+ }
1975
+
737
1976
  // src/render/default-screens.tsx
738
1977
  import { jsxDEV } from "react/jsx-dev-runtime";
739
1978
  var FONT_SANS = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
@@ -809,11 +2048,6 @@ var BADGE_STYLE = {
809
2048
  marginBottom: "16px",
810
2049
  padding: "12px 36px"
811
2050
  };
812
- var NOT_FOUND_BADGE_STYLE = {
813
- ...BADGE_STYLE,
814
- border: 0,
815
- padding: 0
816
- };
817
2051
  var HEADING_STYLE = {
818
2052
  color: COLOR_TEXT,
819
2053
  fontFamily: FONT_SANS,
@@ -901,7 +2135,7 @@ function ScreenFrame({ badge, children }) {
901
2135
  style: PAGE_STYLE,
902
2136
  children: [
903
2137
  /* @__PURE__ */ jsxDEV("style", {
904
- dangerouslySetInnerHTML: { __html: RESET_CSS }
2138
+ children: RESET_CSS
905
2139
  }, undefined, false, undefined, this),
906
2140
  /* @__PURE__ */ jsxDEV("div", {
907
2141
  style: FRAME_STYLE,
@@ -982,7 +2216,7 @@ function DefaultErrorScreen({ message, digest, reset }) {
982
2216
  function DefaultNotFoundScreen({ message }) {
983
2217
  return /* @__PURE__ */ jsxDEV(ScreenFrame, {
984
2218
  badge: /* @__PURE__ */ jsxDEV("div", {
985
- style: NOT_FOUND_BADGE_STYLE,
2219
+ style: BADGE_STYLE,
986
2220
  children: "404 \u2014 NOT FOUND"
987
2221
  }, undefined, false, undefined, this),
988
2222
  children: [
@@ -1048,6 +2282,7 @@ var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV2(Default
1048
2282
  message: error.message,
1049
2283
  reset
1050
2284
  }, undefined, false, undefined, this);
2285
+ var DEFAULT_ERROR_STATUS = 500;
1051
2286
  var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV2(DefaultNotFoundScreen, {
1052
2287
  message: error.message
1053
2288
  }, undefined, false, undefined, this);
@@ -1079,10 +2314,12 @@ class FurinErrorBoundary extends Component {
1079
2314
  throw error;
1080
2315
  }
1081
2316
  const Fallback = this.props.fallback ?? DefaultErrorFallback;
1082
- const finalDigest = digest ?? this.props.digest ?? computeErrorDigest(error);
2317
+ const serverDigest = isFurinServerError(error) ? error.digest : undefined;
2318
+ const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
1083
2319
  const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
2320
+ const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
1084
2321
  return /* @__PURE__ */ jsxDEV2(Fallback, {
1085
- error: { message, digest: finalDigest },
2322
+ error: { message, digest: finalDigest, status },
1086
2323
  reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
1087
2324
  }, undefined, false, undefined, this);
1088
2325
  }
@@ -1193,6 +2430,7 @@ function shouldRefetch(entry) {
1193
2430
  return Date.now() - entry.createdAt > entry.staleTime;
1194
2431
  }
1195
2432
  var HASH_FRAGMENT_RE = /#.*$/;
2433
+ var TRAILING_SLASHES_RE = /\/+$/;
1196
2434
  function stripHashFromHref(href) {
1197
2435
  return href.replace(HASH_FRAGMENT_RE, "");
1198
2436
  }
@@ -1210,10 +2448,20 @@ function normalizePath(path) {
1210
2448
  }
1211
2449
  return path.endsWith("/") ? path.slice(0, -1) : path;
1212
2450
  }
2451
+ function isFurinErrorPayload(value) {
2452
+ if (!value || typeof value !== "object") {
2453
+ return false;
2454
+ }
2455
+ const v = value;
2456
+ return typeof v.digest === "string" && typeof v.message === "string" && typeof v.status === "number";
2457
+ }
1213
2458
  function classifySpaResponse(status, data) {
1214
2459
  if (!data) {
1215
2460
  return { kind: "bail" };
1216
2461
  }
2462
+ if (isFurinErrorPayload(data.__furinError)) {
2463
+ return { kind: "error", error: data.__furinError };
2464
+ }
1217
2465
  if ((status >= 200 && status < 300 || status === 404) && data.__furinStatus === 404) {
1218
2466
  const notFound = data.__furinNotFound;
1219
2467
  return { kind: "not-found", error: notFound ?? {} };
@@ -1275,10 +2523,10 @@ function buildNotFoundPageElement(boundaries, error) {
1275
2523
  return createElement(Fallback, { error });
1276
2524
  }
1277
2525
  function buildRouterTree(context, pageElement, options) {
1278
- return /* @__PURE__ */ jsxDEV3(FurinErrorBoundary, {
1279
- ...options,
1280
- children: /* @__PURE__ */ jsxDEV3(RouterContext.Provider, {
1281
- value: context,
2526
+ return /* @__PURE__ */ jsxDEV3(RouterContext.Provider, {
2527
+ value: context,
2528
+ children: /* @__PURE__ */ jsxDEV3(FurinErrorBoundary, {
2529
+ ...options,
1282
2530
  children: pageElement
1283
2531
  }, undefined, false, undefined, this)
1284
2532
  }, undefined, false, undefined, this);
@@ -1305,8 +2553,13 @@ function wrapPageBoundaries(inner, segment, options) {
1305
2553
  }
1306
2554
  return wrapped;
1307
2555
  }
1308
- function buildPageElement(match, root, data, options) {
1309
- let element = createElement(match.component, data);
2556
+ function RouteErrorThrower({
2557
+ error
2558
+ }) {
2559
+ throw new FurinServerError(error);
2560
+ }
2561
+ function buildPageElement(match, root, data, options, error) {
2562
+ let element = error ? createElement(RouteErrorThrower, { error }) : createElement(match.component, data);
1310
2563
  const allLayouts = [];
1311
2564
  let current = match.pageRoute;
1312
2565
  while (current) {
@@ -1373,6 +2626,21 @@ async function parsePageResponse(res, basePath) {
1373
2626
  const data = dataEl ? JSON.parse(dataEl.textContent || "{}") : null;
1374
2627
  return { data, finalHref, title: doc.title };
1375
2628
  }
2629
+ function buildDataEndpoint(basePath, logicalHref, staticMode) {
2630
+ if (!staticMode) {
2631
+ return `${basePath}/_furin/data?path=${encodeURIComponent(logicalHref)}`;
2632
+ }
2633
+ const parsed = new URL(logicalHref, "http://x");
2634
+ const pathname = parsed.pathname.replace(TRAILING_SLASHES_RE, "");
2635
+ return `${basePath}${pathname}/__furin_data.ndjson`;
2636
+ }
2637
+ function detectStaticMode() {
2638
+ if (typeof document === "undefined") {
2639
+ return false;
2640
+ }
2641
+ const meta = document.querySelector('meta[name="furin-mode"]');
2642
+ return meta?.content === "static";
2643
+ }
1376
2644
  function toLogical(physicalPathname, basePath) {
1377
2645
  if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
1378
2646
  return physicalPathname.slice(basePath.length) || "/";
@@ -1393,12 +2661,6 @@ function RouterProvider({
1393
2661
  defaultPreloadStaleTime,
1394
2662
  prefetchCacheSize
1395
2663
  }) {
1396
- const _autoRefresh = autoRefresh ?? true;
1397
- const _basePath = basePath ?? "";
1398
- const _defaultPreload = defaultPreload ?? "intent";
1399
- const _defaultPreloadDelay = defaultPreloadDelay ?? 50;
1400
- const _defaultPreloadStaleTime = defaultPreloadStaleTime ?? 30000;
1401
- const _prefetchCacheSize = prefetchCacheSize ?? 50;
1402
2664
  const [state, setState] = useState(() => ({
1403
2665
  match: initialMatch,
1404
2666
  data: initialData,
@@ -1409,12 +2671,14 @@ function RouterProvider({
1409
2671
  if (typeof window === "undefined") {
1410
2672
  return "/";
1411
2673
  }
1412
- return normalizeHref(toLogical(window.location.pathname, _basePath)) + window.location.search;
2674
+ return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
1413
2675
  });
1414
2676
  const prefetchCache = useRef(new Map);
1415
2677
  const navVersion = useRef(0);
2678
+ const navAbortRef = useRef(null);
1416
2679
  const pendingScrollRef = useRef(null);
1417
2680
  const currentMatchRef = useRef(initialMatch);
2681
+ const staticModeRef = useRef(detectStaticMode());
1418
2682
  const rootBoundaries = useMemo(() => {
1419
2683
  for (const route of routes) {
1420
2684
  const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
@@ -1424,66 +2688,104 @@ function RouterProvider({
1424
2688
  }
1425
2689
  return;
1426
2690
  }, [routes]);
1427
- const fetchPageState = useCallback(async (rawLogicalHref) => {
2691
+ const resolveNoMatchState = useCallback(async (physicalHref) => {
2692
+ const res = await fetch(physicalHref);
2693
+ if (isStaleDeployResponse(res)) {
2694
+ window.location.href = physicalHref;
2695
+ return null;
2696
+ }
2697
+ const { data, finalHref, title } = await parsePageResponse(res, basePath);
2698
+ const kind = classifySpaResponse(res.status, data);
2699
+ if (kind.kind !== "not-found") {
2700
+ return null;
2701
+ }
2702
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
2703
+ return {
2704
+ match: currentMatchRef.current,
2705
+ data: cleanData,
2706
+ title,
2707
+ finalHref,
2708
+ notFound: kind.error,
2709
+ notFoundBoundaries: rootBoundaries
2710
+ };
2711
+ }, [basePath, rootBoundaries]);
2712
+ const fetchPageState = useCallback(async (rawLogicalHref, signal) => {
1428
2713
  const logicalHref = normalizeHref(rawLogicalHref);
1429
2714
  try {
1430
- const physicalHref = _basePath + logicalHref;
2715
+ const physicalHref = basePath + logicalHref;
1431
2716
  const url = new URL(physicalHref, window.location.origin);
1432
- const logicalPathname = toLogical(url.pathname, _basePath);
2717
+ const logicalPathname = toLogical(url.pathname, basePath);
1433
2718
  const match = routes.find((r) => r.regex.test(logicalPathname));
1434
2719
  if (!match) {
1435
- const res2 = await fetch(physicalHref);
1436
- if (isStaleDeployResponse(res2)) {
1437
- window.location.href = physicalHref;
1438
- return null;
1439
- }
1440
- const { data: data2, finalHref: finalHref2, title: title2 } = await parsePageResponse(res2, _basePath);
1441
- const kind2 = classifySpaResponse(res2.status, data2);
1442
- if (kind2.kind !== "not-found") {
1443
- return null;
1444
- }
1445
- const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data2 ?? {};
1446
- return {
1447
- match: currentMatchRef.current,
1448
- data: cleanData,
1449
- title: title2,
1450
- finalHref: finalHref2,
1451
- notFound: kind2.error,
1452
- notFoundBoundaries: rootBoundaries
1453
- };
2720
+ return await resolveNoMatchState(physicalHref);
1454
2721
  }
1455
- const [res, loadedMod] = await Promise.all([fetch(physicalHref), match.load()]);
2722
+ const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticModeRef.current);
2723
+ const [res, loadedMod] = await Promise.all([fetch(dataEndpoint), match.load()]);
1456
2724
  if (isStaleDeployResponse(res)) {
1457
2725
  window.location.href = physicalHref;
1458
2726
  return null;
1459
2727
  }
1460
- const { data, finalHref, title } = await parsePageResponse(res, _basePath);
1461
- const kind = classifySpaResponse(res.status, data);
1462
- if (kind.kind === "bail") {
1463
- _log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
2728
+ const body = res.body ?? new ReadableStream({ start: (c) => c.close() });
2729
+ let parsed;
2730
+ try {
2731
+ parsed = await parseDeferredNdjson(body, signal);
2732
+ } catch (parseErr) {
2733
+ _log.warn({
2734
+ action: "navigate_server_error",
2735
+ href: physicalHref,
2736
+ status: res.status,
2737
+ error: String(parseErr)
2738
+ });
1464
2739
  return null;
1465
2740
  }
2741
+ const { syncData, deferredPromises } = parsed;
2742
+ const {
2743
+ __furinStatus,
2744
+ __furinNotFound,
2745
+ __furinRedirect,
2746
+ __furinError,
2747
+ __furinTitle,
2748
+ ...cleanSyncData
2749
+ } = syncData;
2750
+ const finalHref = typeof __furinRedirect === "string" ? __furinRedirect : undefined;
2751
+ const data = { ...cleanSyncData, ...deferredPromises };
2752
+ const title = typeof __furinTitle === "string" ? __furinTitle : "";
1466
2753
  const loadedMatch = {
1467
2754
  ...match,
1468
2755
  component: loadedMod.default.component,
1469
2756
  pageRoute: loadedMod.default._route
1470
2757
  };
1471
- if (kind.kind === "not-found") {
1472
- const { __furinStatus, __furinNotFound, ...cleanData } = data ?? {};
2758
+ if (__furinError) {
1473
2759
  return {
1474
2760
  match: loadedMatch,
1475
- data: cleanData,
2761
+ data: {},
1476
2762
  title,
1477
2763
  finalHref,
1478
- notFound: kind.error
2764
+ error: __furinError
1479
2765
  };
1480
2766
  }
1481
- return { match: loadedMatch, data: data ?? {}, title, finalHref };
2767
+ if (!res.ok && res.status !== 404) {
2768
+ _log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
2769
+ return null;
2770
+ }
2771
+ if (__furinStatus === 404) {
2772
+ return {
2773
+ match: loadedMatch,
2774
+ data,
2775
+ title,
2776
+ finalHref,
2777
+ notFound: __furinNotFound ?? {}
2778
+ };
2779
+ }
2780
+ if (finalHref) {
2781
+ return { match: null, data, title, finalHref };
2782
+ }
2783
+ return { match: loadedMatch, data, title, finalHref };
1482
2784
  } catch (err) {
1483
- _log.error({ action: "navigate_failed", href: _basePath + logicalHref, error: String(err) });
2785
+ _log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
1484
2786
  return null;
1485
2787
  }
1486
- }, [routes, _basePath, rootBoundaries]);
2788
+ }, [routes, basePath, resolveNoMatchState]);
1487
2789
  const invalidatePrefetch = useCallback((path, type = "page") => {
1488
2790
  const normalizedPath = stripHashFromHref(path);
1489
2791
  if (type === "page") {
@@ -1503,28 +2805,40 @@ function RouterProvider({
1503
2805
  }
1504
2806
  }, []);
1505
2807
  const prefetch = useCallback((href, opts) => {
1506
- const staleTime = opts?.staleTime ?? _defaultPreloadStaleTime;
2808
+ const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
1507
2809
  const existing = prefetchCache.current.get(href);
1508
2810
  if (existing && !shouldRefetch(existing)) {
1509
2811
  return;
1510
2812
  }
1511
2813
  prefetchCache.current.set(href, {
1512
- promise: fetchPageState(href),
2814
+ promise: fetchPageState(href, undefined),
1513
2815
  createdAt: Date.now(),
1514
2816
  staleTime
1515
2817
  });
1516
- if (prefetchCache.current.size > _prefetchCacheSize) {
2818
+ if (prefetchCache.current.size > prefetchCacheSize) {
1517
2819
  const oldest = prefetchCache.current.keys().next().value;
1518
2820
  prefetchCache.current.delete(oldest);
1519
2821
  }
1520
- }, [fetchPageState, _defaultPreloadStaleTime, _prefetchCacheSize]);
2822
+ }, [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
2823
+ async function resolveRedirectState(redirectLogical, myVersion, signal) {
2824
+ const cached = prefetchCache.current.get(redirectLogical);
2825
+ const state2 = cached && !shouldRefetch(cached) ? await cached.promise : await fetchPageState(redirectLogical, signal);
2826
+ if (navVersion.current !== myVersion) {
2827
+ return null;
2828
+ }
2829
+ return state2;
2830
+ }
1521
2831
  const navigate = useCallback(async (rawLogicalHref, opts) => {
1522
2832
  const logicalHref = normalizeHref(rawLogicalHref);
1523
2833
  prefetch(logicalHref);
1524
2834
  const myVersion = ++navVersion.current;
2835
+ navAbortRef.current?.abort();
2836
+ const navAbort = new AbortController;
2837
+ navAbortRef.current = navAbort;
2838
+ const navSignal = navAbort.signal;
1525
2839
  setIsNavigating(true);
1526
2840
  try {
1527
- const newState = await prefetchCache.current.get(logicalHref)?.promise;
2841
+ let newState = await prefetchCache.current.get(logicalHref)?.promise;
1528
2842
  if (navVersion.current !== myVersion) {
1529
2843
  return;
1530
2844
  }
@@ -1534,16 +2848,34 @@ function RouterProvider({
1534
2848
  href: logicalHref,
1535
2849
  reason: "prefetch_returned_null"
1536
2850
  });
1537
- window.location.href = _basePath + logicalHref;
2851
+ window.location.href = basePath + logicalHref;
1538
2852
  return;
1539
2853
  }
2854
+ let redirectLogical;
2855
+ if (newState.finalHref && !newState.match && !newState.notFound) {
2856
+ redirectLogical = normalizeHref(newState.finalHref);
2857
+ const redirectPhysical = basePath + redirectLogical;
2858
+ window.history.replaceState({
2859
+ ...history.state ?? {},
2860
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
2861
+ }, "", redirectPhysical);
2862
+ setCurrentHref(redirectLogical);
2863
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
2864
+ if (!redirectState) {
2865
+ if (navVersion.current === myVersion) {
2866
+ window.location.href = redirectPhysical;
2867
+ }
2868
+ return;
2869
+ }
2870
+ newState = redirectState;
2871
+ }
1540
2872
  currentMatchRef.current = newState.match;
1541
2873
  setState(newState);
1542
2874
  if (newState.title) {
1543
2875
  document.title = newState.title;
1544
2876
  }
1545
- const effectiveLogical = newState.finalHref ?? logicalHref;
1546
- const physicalEffective = _basePath + effectiveLogical;
2877
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
2878
+ const physicalEffective = basePath + effectiveLogical;
1547
2879
  if (opts?.replace) {
1548
2880
  window.history.replaceState({
1549
2881
  ...history.state ?? {},
@@ -1557,7 +2889,7 @@ function RouterProvider({
1557
2889
  window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
1558
2890
  }
1559
2891
  const effectiveUrl = new URL(physicalEffective, window.location.origin);
1560
- const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, _basePath));
2892
+ const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
1561
2893
  setCurrentHref(logicalPath + effectiveUrl.search);
1562
2894
  if (opts?.resetScroll ?? true) {
1563
2895
  pendingScrollRef.current = { type: "reset", href: physicalEffective };
@@ -1567,13 +2899,13 @@ function RouterProvider({
1567
2899
  setIsNavigating(false);
1568
2900
  }
1569
2901
  }
1570
- }, [prefetch, _basePath]);
2902
+ }, [prefetch, basePath]);
1571
2903
  const refresh = useCallback(async (opts) => {
1572
- const logicalPath = toLogical(window.location.pathname, _basePath);
2904
+ const logicalPath = toLogical(window.location.pathname, basePath);
1573
2905
  const logicalHref = logicalPath + window.location.search;
1574
2906
  invalidatePrefetch(logicalHref, "page");
1575
2907
  await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
1576
- }, [navigate, invalidatePrefetch, _basePath]);
2908
+ }, [navigate, invalidatePrefetch, basePath]);
1577
2909
  useEffect(() => {
1578
2910
  if (typeof window !== "undefined") {
1579
2911
  window.__FURIN_HMR_REFRESH__ = refresh;
@@ -1584,9 +2916,13 @@ function RouterProvider({
1584
2916
  }, [refresh]);
1585
2917
  const handlePopState = useCallback(() => {
1586
2918
  const destKey = getHistoryKey(history.state);
1587
- const logicalPath = normalizeHref(toLogical(window.location.pathname, _basePath));
2919
+ const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
1588
2920
  const logicalHref = logicalPath + window.location.search;
1589
2921
  const myVersion = ++navVersion.current;
2922
+ navAbortRef.current?.abort();
2923
+ const navAbort = new AbortController;
2924
+ navAbortRef.current = navAbort;
2925
+ const navSignal = navAbort.signal;
1590
2926
  setIsNavigating(true);
1591
2927
  (async () => {
1592
2928
  try {
@@ -1595,7 +2931,7 @@ function RouterProvider({
1595
2931
  if (cached && !shouldRefetch(cached)) {
1596
2932
  newState = await cached.promise;
1597
2933
  } else {
1598
- newState = await fetchPageState(logicalHref);
2934
+ newState = await fetchPageState(logicalHref, navSignal);
1599
2935
  }
1600
2936
  if (navVersion.current !== myVersion) {
1601
2937
  return;
@@ -1609,14 +2945,28 @@ function RouterProvider({
1609
2945
  window.location.reload();
1610
2946
  return;
1611
2947
  }
2948
+ let redirectLogical;
2949
+ if (newState.finalHref && !newState.match && !newState.notFound) {
2950
+ redirectLogical = normalizeHref(newState.finalHref);
2951
+ window.history.replaceState(history.state, "", basePath + redirectLogical);
2952
+ setCurrentHref(redirectLogical);
2953
+ const redirectState = await resolveRedirectState(redirectLogical, myVersion, navSignal);
2954
+ if (!redirectState) {
2955
+ if (navVersion.current === myVersion) {
2956
+ window.location.reload();
2957
+ }
2958
+ return;
2959
+ }
2960
+ newState = redirectState;
2961
+ }
1612
2962
  currentMatchRef.current = newState.match;
1613
2963
  setState(newState);
1614
2964
  if (newState.title) {
1615
2965
  document.title = newState.title;
1616
2966
  }
1617
- const effectiveLogical = newState.finalHref ?? logicalHref;
2967
+ const effectiveLogical = newState.finalHref ?? redirectLogical ?? logicalHref;
1618
2968
  if (newState.finalHref) {
1619
- window.history.replaceState(history.state, "", _basePath + effectiveLogical);
2969
+ window.history.replaceState(history.state, "", basePath + effectiveLogical);
1620
2970
  }
1621
2971
  setCurrentHref(normalizeHref(effectiveLogical));
1622
2972
  if (destKey) {
@@ -1630,7 +2980,7 @@ function RouterProvider({
1630
2980
  }
1631
2981
  }
1632
2982
  })();
1633
- }, [fetchPageState, _basePath]);
2983
+ }, [fetchPageState, basePath]);
1634
2984
  useEffect(() => {
1635
2985
  history.scrollRestoration = "manual";
1636
2986
  if (!getHistoryKey(history.state)) {
@@ -1684,7 +3034,7 @@ function RouterProvider({
1684
3034
  if (anchor.closest("a[data-furin-link]")) {
1685
3035
  return;
1686
3036
  }
1687
- const logicalHref = shouldInterceptClick(anchor, e, _basePath, window.location.origin, window.location.pathname);
3037
+ const logicalHref = shouldInterceptClick(anchor, e, basePath, window.location.origin, window.location.pathname);
1688
3038
  if (logicalHref === null) {
1689
3039
  return;
1690
3040
  }
@@ -1693,7 +3043,7 @@ function RouterProvider({
1693
3043
  };
1694
3044
  document.addEventListener("click", handler);
1695
3045
  return () => document.removeEventListener("click", handler);
1696
- }, [navigate, _basePath]);
3046
+ }, [navigate, basePath]);
1697
3047
  useEffect(() => {
1698
3048
  if (typeof window === "undefined") {
1699
3049
  return;
@@ -1706,8 +3056,8 @@ function RouterProvider({
1706
3056
  invalidatePrefetch(path, type);
1707
3057
  invalidated.push({ path, type });
1708
3058
  });
1709
- if (_autoRefresh && invalidated.length > 0) {
1710
- const currentLogicalPath = normalizeHref(toLogical(window.location.pathname, _basePath)) + window.location.search;
3059
+ if (autoRefresh && invalidated.length > 0) {
3060
+ const currentLogicalPath = normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
1711
3061
  if (shouldAutoRefreshPath(currentLogicalPath, invalidated)) {
1712
3062
  refresh();
1713
3063
  }
@@ -1719,7 +3069,7 @@ function RouterProvider({
1719
3069
  return () => {
1720
3070
  window.fetch = originalFetch;
1721
3071
  };
1722
- }, [invalidatePrefetch, refresh, _autoRefresh]);
3072
+ }, [invalidatePrefetch, refresh, autoRefresh]);
1723
3073
  let pageElement;
1724
3074
  if (state.notFound || !state.match) {
1725
3075
  pageElement = buildNotFoundPageElement(state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries, state.notFound ?? {});
@@ -1727,19 +3077,19 @@ function RouterProvider({
1727
3077
  pageElement = buildPageElement(state.match, root, state.data, {
1728
3078
  onReset: refresh,
1729
3079
  resetKey: currentHref
1730
- });
3080
+ }, state.error);
1731
3081
  }
1732
3082
  return buildRouterTree({
1733
- basePath: _basePath,
3083
+ basePath,
1734
3084
  currentHref,
1735
3085
  navigate,
1736
3086
  prefetch,
1737
3087
  refresh,
1738
3088
  invalidatePrefetch,
1739
3089
  isNavigating,
1740
- defaultPreload: _defaultPreload,
1741
- defaultPreloadDelay: _defaultPreloadDelay,
1742
- defaultPreloadStaleTime: _defaultPreloadStaleTime
3090
+ defaultPreload,
3091
+ defaultPreloadDelay,
3092
+ defaultPreloadStaleTime
1743
3093
  }, pageElement, {
1744
3094
  digest: initialDigest,
1745
3095
  onReset: refresh,
@@ -1795,9 +3145,10 @@ function LinkInteractive({
1795
3145
  const effectivePreload = preload ?? router.defaultPreload;
1796
3146
  const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
1797
3147
  const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
3148
+ const { prefetch } = router;
1798
3149
  const triggerPrefetch = useCallback2(() => {
1799
- router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
1800
- }, [router, logicalHref, effectiveStaleTime]);
3150
+ prefetch(logicalHref, { staleTime: effectiveStaleTime });
3151
+ }, [prefetch, logicalHref, effectiveStaleTime]);
1801
3152
  useEffect2(() => {
1802
3153
  if (effectivePreload === "render") {
1803
3154
  triggerPrefetch();
@@ -1848,6 +3199,10 @@ function LinkInteractive({
1848
3199
  return;
1849
3200
  }
1850
3201
  e.preventDefault();
3202
+ if (typeof window !== "undefined" && router.navigate === SSR_FALLBACK_ROUTER.navigate) {
3203
+ window.location.href = href;
3204
+ return;
3205
+ }
1851
3206
  router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
1852
3207
  };
1853
3208
  const handleMouseEnter = (e) => {
@@ -1942,11 +3297,14 @@ export {
1942
3297
  shouldAutoRefreshPath,
1943
3298
  pickDeepestNotFound,
1944
3299
  normalizeHref,
3300
+ fromCrossJSON,
3301
+ detectStaticMode,
1945
3302
  classifySpaResponse,
1946
3303
  buildRouterTree,
1947
3304
  buildPageElement,
1948
3305
  buildNotFoundPageElement,
1949
3306
  buildHref,
3307
+ buildDataEndpoint,
1950
3308
  applyRevalidateHeader,
1951
3309
  SSR_FALLBACK_ROUTER,
1952
3310
  RouterProvider,