@teyik0/furin 0.1.0-alpha.6 → 0.1.0-alpha.8

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 (42) hide show
  1. package/dist/adapter/static.d.ts +3 -0
  2. package/dist/build/client.d.ts +3 -3
  3. package/dist/build/compile-entry.d.ts +4 -4
  4. package/dist/build/entry-template.d.ts +2 -2
  5. package/dist/build/hydrate.d.ts +6 -2
  6. package/dist/build/index.d.ts +1 -1
  7. package/dist/build/index.js +668 -90
  8. package/dist/build/types.d.ts +26 -3
  9. package/dist/cli/index.d.ts +1 -0
  10. package/dist/cli/index.js +704 -103
  11. package/dist/client.d.ts +22 -15
  12. package/dist/config.d.ts +33 -2
  13. package/dist/config.js +6 -1
  14. package/dist/dev-page-plugin.d.ts +77 -0
  15. package/dist/furin.js +771 -81
  16. package/dist/link.d.ts +31 -3
  17. package/dist/link.js +511 -62
  18. package/dist/render/index.d.ts +1 -1
  19. package/dist/render/loaders.d.ts +1 -1
  20. package/dist/router.js +84 -24
  21. package/package.json +9 -10
  22. package/src/adapter/bun.ts +31 -7
  23. package/src/adapter/static.ts +337 -0
  24. package/src/build/client.ts +28 -11
  25. package/src/build/compile-entry.ts +5 -3
  26. package/src/build/entry-template.ts +9 -5
  27. package/src/build/hydrate.ts +40 -10
  28. package/src/build/index.ts +56 -21
  29. package/src/build/scan-server.ts +43 -21
  30. package/src/build/shared.ts +7 -3
  31. package/src/build/types.ts +28 -3
  32. package/src/cli/index.ts +14 -5
  33. package/src/client.ts +26 -31
  34. package/src/config.ts +35 -1
  35. package/src/dev-page-plugin.ts +339 -4
  36. package/src/furin.ts +6 -2
  37. package/src/link.tsx +268 -62
  38. package/src/plugin/index.ts +2 -2
  39. package/src/render/index.ts +64 -24
  40. package/src/render/loaders.ts +77 -36
  41. package/src/render/shell.ts +2 -2
  42. package/src/router.ts +11 -1
package/dist/link.js CHANGED
@@ -1,5 +1,10 @@
1
1
  // @bun
2
- // ../../node_modules/.bun/evlog@2.11.0+a1ab7c6fe65f988d/node_modules/evlog/dist/utils.mjs
2
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/utils.mjs
3
+ function formatDuration(ms) {
4
+ if (ms < 1000)
5
+ return `${Math.round(ms)}ms`;
6
+ return `${(ms / 1000).toFixed(2)}s`;
7
+ }
3
8
  function isClient() {
4
9
  return typeof window !== "undefined";
5
10
  }
@@ -21,6 +26,15 @@ function detectEnvironment() {
21
26
  region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
22
27
  };
23
28
  }
29
+ var LEVEL_ORDER = {
30
+ debug: 0,
31
+ info: 1,
32
+ warn: 2,
33
+ error: 3
34
+ };
35
+ function isLevelEnabled(level, minLevel) {
36
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
37
+ }
24
38
  function getConsoleMethod(level) {
25
39
  return level;
26
40
  }
@@ -68,7 +82,157 @@ function escapeFormatString(str) {
68
82
  return str.replace(/%/g, "%%");
69
83
  }
70
84
 
71
- // ../../node_modules/.bun/evlog@2.11.0+a1ab7c6fe65f988d/node_modules/evlog/dist/logger.mjs
85
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/logger-DnobymUQ.mjs
86
+ var DEFAULT_REPLACEMENT = "[REDACTED]";
87
+ var builtinPatterns = {
88
+ creditCard: {
89
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
90
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
91
+ },
92
+ email: {
93
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
94
+ mask: (m) => {
95
+ if (m.indexOf("@") < 1)
96
+ return "***@***";
97
+ const tld = m.slice(m.lastIndexOf("."));
98
+ return `${m[0]}***@***${tld}`;
99
+ }
100
+ },
101
+ ipv4: {
102
+ pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
103
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
104
+ },
105
+ phone: {
106
+ pattern: /(?:\+\d{1,3}[\s.-]?)?\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}\b/g,
107
+ mask: (m) => {
108
+ const digits = m.replace(/[^\d]/g, "");
109
+ if (m.startsWith("+") && digits.length > 4) {
110
+ const ccMatch = m.match(/^\+\d{1,3}/);
111
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
112
+ }
113
+ if (digits.length > 2)
114
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
115
+ return "***";
116
+ }
117
+ },
118
+ jwt: {
119
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
120
+ mask: () => "eyJ***.***"
121
+ },
122
+ bearer: {
123
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
124
+ mask: () => "Bearer ***"
125
+ },
126
+ iban: {
127
+ 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,
128
+ mask: (m) => {
129
+ const clean = m.replace(/[\s-]/g, "");
130
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
131
+ }
132
+ }
133
+ };
134
+ function resolveRedactConfig(input) {
135
+ if (input === undefined || input === false)
136
+ return;
137
+ if (input === true)
138
+ return { _maskers: allBuiltinMaskers() };
139
+ if (input.builtins === false)
140
+ return input;
141
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
142
+ return {
143
+ ...input,
144
+ _maskers: maskers
145
+ };
146
+ }
147
+ function allBuiltinMaskers() {
148
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
149
+ }
150
+ function cloneRegex(re) {
151
+ return new RegExp(re.source, re.flags);
152
+ }
153
+ function redactEvent(event, config) {
154
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
155
+ if (config.paths?.length)
156
+ for (const path of config.paths)
157
+ redactPath(event, path.split("."), replacement);
158
+ if (config._maskers?.length)
159
+ applyMaskersToTree(event, config._maskers);
160
+ if (config.patterns?.length)
161
+ redactPatterns(event, config.patterns, replacement);
162
+ }
163
+ function redactPath(obj, segments, replacement) {
164
+ let current = obj;
165
+ for (let i = 0;i < segments.length - 1; i++) {
166
+ if (current === null || current === undefined || typeof current !== "object")
167
+ return;
168
+ current = current[segments[i]];
169
+ }
170
+ if (current === null || current === undefined || typeof current !== "object")
171
+ return;
172
+ const leaf = segments[segments.length - 1];
173
+ if (leaf in current)
174
+ current[leaf] = replacement;
175
+ }
176
+ function redactPatterns(obj, patterns, replacement) {
177
+ if (obj === null || obj === undefined)
178
+ return;
179
+ if (Array.isArray(obj)) {
180
+ for (let i = 0;i < obj.length; i++)
181
+ if (typeof obj[i] === "string")
182
+ obj[i] = applyPatterns(obj[i], patterns, replacement);
183
+ else if (typeof obj[i] === "object")
184
+ redactPatterns(obj[i], patterns, replacement);
185
+ return;
186
+ }
187
+ if (typeof obj === "object") {
188
+ const record = obj;
189
+ for (const key in record) {
190
+ const val = record[key];
191
+ if (typeof val === "string")
192
+ record[key] = applyPatterns(val, patterns, replacement);
193
+ else if (typeof val === "object")
194
+ redactPatterns(val, patterns, replacement);
195
+ }
196
+ }
197
+ }
198
+ function applyPatterns(value, patterns, replacement) {
199
+ let result = value;
200
+ for (const pattern of patterns) {
201
+ pattern.lastIndex = 0;
202
+ result = result.replace(pattern, replacement);
203
+ }
204
+ return result;
205
+ }
206
+ function applyMaskersToTree(obj, maskers) {
207
+ if (obj === null || obj === undefined)
208
+ return;
209
+ if (Array.isArray(obj)) {
210
+ for (let i = 0;i < obj.length; i++)
211
+ if (typeof obj[i] === "string")
212
+ obj[i] = applyMaskers(obj[i], maskers);
213
+ else if (typeof obj[i] === "object")
214
+ applyMaskersToTree(obj[i], maskers);
215
+ return;
216
+ }
217
+ if (typeof obj === "object") {
218
+ const record = obj;
219
+ for (const key in record) {
220
+ const val = record[key];
221
+ if (typeof val === "string")
222
+ record[key] = applyMaskers(val, maskers);
223
+ else if (typeof val === "object")
224
+ applyMaskersToTree(val, maskers);
225
+ }
226
+ }
227
+ }
228
+ function applyMaskers(value, maskers) {
229
+ let result = value;
230
+ for (const [pattern, mask] of maskers) {
231
+ pattern.lastIndex = 0;
232
+ result = result.replace(pattern, mask);
233
+ }
234
+ return result;
235
+ }
72
236
  var _tsDate = /* @__PURE__ */ new Date;
73
237
  function isoNow() {
74
238
  _tsDate.setTime(Date.now());
@@ -82,8 +246,10 @@ var globalPretty = isDev();
82
246
  var globalSampling = {};
83
247
  var globalStringify = true;
84
248
  var globalDrain;
249
+ var globalRedact;
85
250
  var globalEnabled = true;
86
251
  var globalSilent = false;
252
+ var globalMinLevel = "debug";
87
253
  function initLogger(config = {}) {
88
254
  globalEnabled = config.enabled ?? true;
89
255
  const detected = detectEnvironment();
@@ -98,7 +264,9 @@ function initLogger(config = {}) {
98
264
  globalSampling = config.sampling ?? {};
99
265
  globalStringify = config.stringify ?? true;
100
266
  globalDrain = config.drain;
267
+ globalRedact = resolveRedactConfig(config.redact ?? !isDev());
101
268
  globalSilent = config.silent ?? false;
269
+ globalMinLevel = config.minLevel ?? "debug";
102
270
  if (globalSilent && !globalDrain && !config._suppressDrainWarning)
103
271
  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).");
104
272
  }
@@ -116,8 +284,12 @@ function shouldSample(level) {
116
284
  function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
117
285
  if (!globalEnabled)
118
286
  return null;
119
- if (!ownsEvent && !shouldSample(level))
120
- return null;
287
+ if (!ownsEvent) {
288
+ if (!isLevelEnabled(level, globalMinLevel))
289
+ return null;
290
+ if (!shouldSample(level))
291
+ return null;
292
+ }
121
293
  let formatted;
122
294
  if (ownsEvent) {
123
295
  event.timestamp = isoNow();
@@ -140,6 +312,8 @@ function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
140
312
  ...globalEnv,
141
313
  ...event
142
314
  };
315
+ if (globalRedact)
316
+ redactEvent(formatted, globalRedact);
143
317
  if (!globalSilent)
144
318
  if (globalPretty)
145
319
  prettyPrintWideEvent(formatted);
@@ -157,6 +331,8 @@ function emitTaggedLog(level, tag, message) {
157
331
  if (!globalEnabled)
158
332
  return;
159
333
  if (globalPretty && !globalSilent) {
334
+ if (!isLevelEnabled(level, globalMinLevel))
335
+ return;
160
336
  if (!shouldSample(level))
161
337
  return;
162
338
  if (isClient()) {
@@ -190,6 +366,169 @@ function formatValue(value) {
190
366
  }
191
367
  return String(value);
192
368
  }
369
+ function formatCost(cost) {
370
+ if (cost < 0.01)
371
+ return `$${cost.toFixed(6)}`;
372
+ if (cost < 1)
373
+ return `$${cost.toFixed(4)}`;
374
+ return `$${cost.toFixed(2)}`;
375
+ }
376
+ function buildAIEntries(ai) {
377
+ const entries = [];
378
+ const headerParts = [];
379
+ if (ai.model) {
380
+ let m = String(ai.model);
381
+ if (ai.provider)
382
+ m += ` (${ai.provider})`;
383
+ headerParts.push(m);
384
+ }
385
+ if (ai.calls)
386
+ headerParts.push(`${ai.calls} call${ai.calls > 1 ? "s" : ""}`);
387
+ if (ai.steps && ai.steps > 1)
388
+ headerParts.push(`${ai.steps} steps`);
389
+ entries.push({
390
+ key: "ai",
391
+ value: headerParts.join(" \xB7 ")
392
+ });
393
+ const inputTokens = ai.inputTokens;
394
+ const outputTokens = ai.outputTokens;
395
+ const totalTokens = ai.totalTokens;
396
+ if (inputTokens !== undefined && outputTokens !== undefined) {
397
+ let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
398
+ if (totalTokens)
399
+ tokLine += ` (${totalTokens} total)`;
400
+ const extras = [];
401
+ if (ai.cacheReadTokens)
402
+ extras.push(`${ai.cacheReadTokens} cache read`);
403
+ if (ai.cacheWriteTokens)
404
+ extras.push(`${ai.cacheWriteTokens} cache write`);
405
+ if (ai.reasoningTokens)
406
+ extras.push(`${ai.reasoningTokens} reasoning`);
407
+ if (extras.length)
408
+ tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
409
+ entries.push({
410
+ key: "ai.tokens",
411
+ value: tokLine
412
+ });
413
+ }
414
+ const msFirst = ai.msToFirstChunk;
415
+ const msFinish = ai.msToFinish;
416
+ const tps = ai.tokensPerSecond;
417
+ if (msFirst !== undefined || msFinish !== undefined) {
418
+ const parts = [];
419
+ if (msFirst !== undefined)
420
+ parts.push(`${formatDuration(msFirst)} to first chunk`);
421
+ if (msFinish !== undefined)
422
+ parts.push(`${formatDuration(msFinish)} total`);
423
+ let streamLine = parts.join(" \u2192 ");
424
+ if (tps)
425
+ streamLine += ` \xB7 ${tps} tok/s`;
426
+ entries.push({
427
+ key: "ai.streaming",
428
+ value: streamLine
429
+ });
430
+ }
431
+ if (ai.estimatedCost !== undefined)
432
+ entries.push({
433
+ key: "ai.cost",
434
+ value: formatCost(ai.estimatedCost)
435
+ });
436
+ if (ai.totalDurationMs !== undefined)
437
+ entries.push({
438
+ key: "ai.totalDuration",
439
+ value: formatDuration(ai.totalDurationMs)
440
+ });
441
+ const toolCalls = ai.toolCalls;
442
+ const tools = ai.tools;
443
+ const hasInputs = toolCalls?.length ? typeof toolCalls[0] === "object" : false;
444
+ if (tools?.length) {
445
+ const children = tools.map((t, idx) => {
446
+ const mark = t.success ? "\u2713" : "\u2717";
447
+ let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
448
+ if (t.error)
449
+ line += ` ${t.error}`;
450
+ if (hasInputs && toolCalls && idx < toolCalls.length) {
451
+ const tc = toolCalls[idx];
452
+ const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
453
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
454
+ line += ` ${truncated}`;
455
+ }
456
+ return line;
457
+ });
458
+ entries.push({
459
+ key: "ai.tools",
460
+ value: "",
461
+ children
462
+ });
463
+ } else if (toolCalls?.length)
464
+ if (hasInputs) {
465
+ const children = toolCalls.map((tc) => {
466
+ const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
467
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
468
+ return `${tc.name}(${truncated})`;
469
+ });
470
+ entries.push({
471
+ key: "ai.tools",
472
+ value: "",
473
+ children
474
+ });
475
+ } else
476
+ entries.push({
477
+ key: "ai.tools",
478
+ value: toolCalls.join(", ")
479
+ });
480
+ const stepsUsage = ai.stepsUsage;
481
+ if (stepsUsage?.length) {
482
+ const allSameModel = stepsUsage.every((s) => s.model === stepsUsage[0].model);
483
+ const children = stepsUsage.map((s) => {
484
+ let line = `${allSameModel ? "" : `${s.model} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
485
+ const stepTools = s.toolCalls;
486
+ if (stepTools?.length)
487
+ line += ` [${stepTools.join(", ")}]`;
488
+ return line;
489
+ });
490
+ entries.push({
491
+ key: "ai.steps",
492
+ value: "",
493
+ children
494
+ });
495
+ } else if (ai.steps && ai.steps > 1)
496
+ entries.push({
497
+ key: "ai.steps",
498
+ value: String(ai.steps)
499
+ });
500
+ const embedding = ai.embedding;
501
+ if (embedding) {
502
+ const parts = [];
503
+ if (embedding.model)
504
+ parts.push(String(embedding.model));
505
+ parts.push(`${embedding.tokens} tokens`);
506
+ if (embedding.dimensions)
507
+ parts.push(`${embedding.dimensions}d`);
508
+ if (embedding.count)
509
+ parts.push(`${embedding.count} items`);
510
+ entries.push({
511
+ key: "ai.embedding",
512
+ value: parts.join(" \xB7 ")
513
+ });
514
+ }
515
+ if (ai.finishReason)
516
+ entries.push({
517
+ key: "ai.finishReason",
518
+ value: String(ai.finishReason)
519
+ });
520
+ if (ai.error)
521
+ entries.push({
522
+ key: "ai.error",
523
+ value: String(ai.error)
524
+ });
525
+ if (ai.responseId)
526
+ entries.push({
527
+ key: "ai.responseId",
528
+ value: String(ai.responseId)
529
+ });
530
+ return entries;
531
+ }
193
532
  function prettyPrintWideEvent(event) {
194
533
  const { timestamp, level, service, environment, version, ...rest } = event;
195
534
  const ts = timestamp.slice(11, 23);
@@ -227,16 +566,38 @@ function prettyPrintWideEvent(event) {
227
566
  delete rest.duration;
228
567
  }
229
568
  console.log(parts.join(""), ...styles);
230
- const entries = Object.entries(rest).filter(([_, v]) => v !== undefined);
231
- const lastIndex = entries.length - 1;
232
- entries.forEach(([key, value], index) => {
233
- const prefix = index === lastIndex ? "\u2514\u2500" : "\u251C\u2500";
234
- const val = formatValue(value);
235
- if (browser)
236
- console.log(` %c${prefix}%c %c${escapeFormatString(key)}:%c ${escapeFormatString(val)}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
237
- else
238
- console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${key}:${colors.reset} ${val}`);
239
- });
569
+ const aiData = rest.ai;
570
+ if (aiData && typeof aiData === "object")
571
+ delete rest.ai;
572
+ const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
573
+ const aiEntries = aiData ? buildAIEntries(aiData) : [];
574
+ const allEntries = [...restEntries.map(([key, value]) => ({
575
+ key,
576
+ value: formatValue(value)
577
+ })), ...aiEntries];
578
+ for (let i = 0;i < allEntries.length; i++) {
579
+ const entry = allEntries[i];
580
+ const hasChildren = entry.children && entry.children.length > 0;
581
+ const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
582
+ if (browser) {
583
+ const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
584
+ console.log(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
585
+ } else {
586
+ const val = entry.value ? ` ${entry.value}` : "";
587
+ console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
588
+ }
589
+ if (hasChildren) {
590
+ const connector = i === allEntries.length - 1 ? " " : "\u2502";
591
+ for (let j = 0;j < entry.children.length; j++) {
592
+ const child = entry.children[j];
593
+ const childPrefix = j === entry.children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
594
+ if (browser)
595
+ console.log(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
596
+ else
597
+ console.log(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
598
+ }
599
+ }
600
+ }
240
601
  }
241
602
  function createLogMethod(level) {
242
603
  return function logMethod(tagOrEvent, message) {
@@ -315,7 +676,8 @@ function shouldAutoRefreshPath(currentPath, invalidations) {
315
676
  var RouterContext = createContext(null);
316
677
  function useRouter() {
317
678
  return useContext(RouterContext) ?? {
318
- currentHref: typeof window === "undefined" ? "/" : window.location.pathname + window.location.search,
679
+ basePath: "",
680
+ currentHref: "/",
319
681
  navigate: (href) => {
320
682
  window.location.href = href;
321
683
  return Promise.resolve();
@@ -387,12 +749,19 @@ function handleScrollRestoration(href, navigationToken, navVersion) {
387
749
  window.scrollTo(0, 0);
388
750
  }
389
751
  }
752
+ function toLogical(physicalPathname, basePath) {
753
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
754
+ return physicalPathname.slice(basePath.length) || "/";
755
+ }
756
+ return physicalPathname;
757
+ }
390
758
  function RouterProvider({
391
759
  routes,
392
760
  root,
393
761
  initialMatch,
394
762
  initialData,
395
763
  autoRefresh = true,
764
+ basePath = "",
396
765
  defaultPreload = "intent",
397
766
  defaultPreloadDelay = 50,
398
767
  defaultPreloadStaleTime = 30000,
@@ -403,34 +772,41 @@ function RouterProvider({
403
772
  data: initialData
404
773
  });
405
774
  const [isNavigating, setIsNavigating] = useState(false);
406
- const [currentHref, setCurrentHref] = useState(() => typeof window === "undefined" ? "/" : window.location.pathname + window.location.search);
775
+ const [currentHref, setCurrentHref] = useState(() => {
776
+ if (typeof window === "undefined") {
777
+ return "/";
778
+ }
779
+ return toLogical(window.location.pathname, basePath) + window.location.search;
780
+ });
407
781
  const prefetchCache = useRef(new Map);
408
782
  const navVersion = useRef(0);
409
- const fetchPageState = useCallback(async (href) => {
783
+ const fetchPageState = useCallback(async (logicalHref) => {
410
784
  try {
411
- const url = new URL(href, window.location.origin);
412
- const match = routes.find((r) => r.regex.test(url.pathname));
785
+ const physicalHref = basePath + logicalHref;
786
+ const url = new URL(physicalHref, window.location.origin);
787
+ const logicalPathname = toLogical(url.pathname, basePath);
788
+ const match = routes.find((r) => r.regex.test(logicalPathname));
413
789
  if (!match) {
414
790
  return null;
415
791
  }
416
- const [res, loadedMod] = await Promise.all([fetch(href), match.load()]);
792
+ const [res, loadedMod] = await Promise.all([fetch(physicalHref), match.load()]);
417
793
  const serverBuildId = res.headers.get("x-furin-build-id");
418
794
  if (serverBuildId) {
419
795
  const metaEl = typeof document === "undefined" ? null : document.querySelector('meta[name="furin-build-id"]');
420
796
  const clientBuildId = metaEl?.content;
421
797
  if (clientBuildId && serverBuildId !== clientBuildId) {
422
- window.location.href = href;
798
+ window.location.href = physicalHref;
423
799
  return null;
424
800
  }
425
801
  }
426
802
  if (!res.ok) {
427
- _log.warn({ action: "navigate_server_error", href, status: res.status });
803
+ _log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
428
804
  return null;
429
805
  }
430
806
  let finalHref;
431
807
  if (res.redirected) {
432
808
  const final = new URL(res.url);
433
- finalHref = final.pathname + final.search;
809
+ finalHref = toLogical(final.pathname, basePath) + final.search;
434
810
  }
435
811
  const html = await res.text();
436
812
  const doc = new DOMParser().parseFromString(html, "text/html");
@@ -443,10 +819,10 @@ function RouterProvider({
443
819
  };
444
820
  return { match: loadedMatch, data, title: doc.title, finalHref };
445
821
  } catch (err) {
446
- _log.error({ action: "navigate_failed", href, error: String(err) });
822
+ _log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
447
823
  return null;
448
824
  }
449
- }, [routes]);
825
+ }, [routes, basePath]);
450
826
  const invalidatePrefetch = useCallback((path, type = "page") => {
451
827
  const normalizedPath = stripHashFromHref(path);
452
828
  if (type === "page") {
@@ -481,63 +857,75 @@ function RouterProvider({
481
857
  prefetchCache.current.delete(oldest);
482
858
  }
483
859
  }, [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
484
- const navigate = useCallback(async (href, opts) => {
485
- prefetch(href);
860
+ const navigate = useCallback(async (logicalHref, opts) => {
861
+ prefetch(logicalHref);
486
862
  const myVersion = ++navVersion.current;
487
863
  setIsNavigating(true);
488
864
  try {
489
- const newState = await prefetchCache.current.get(href)?.promise;
865
+ const newState = await prefetchCache.current.get(logicalHref)?.promise;
490
866
  if (navVersion.current !== myVersion) {
491
867
  return;
492
868
  }
493
869
  if (!newState) {
494
- _log.warn({ action: "navigate_fallback", href, reason: "prefetch_returned_null" });
495
- window.location.href = href;
870
+ _log.warn({
871
+ action: "navigate_fallback",
872
+ href: logicalHref,
873
+ reason: "prefetch_returned_null"
874
+ });
875
+ window.location.href = basePath + logicalHref;
496
876
  return;
497
877
  }
498
878
  setState(newState);
499
879
  if (newState.title) {
500
880
  document.title = newState.title;
501
881
  }
502
- const effectiveHref = newState.finalHref ?? href;
882
+ const effectiveLogical = newState.finalHref ?? logicalHref;
883
+ const physicalEffective = basePath + effectiveLogical;
503
884
  if (opts?.replace) {
504
- window.history.replaceState(null, "", effectiveHref);
885
+ window.history.replaceState(null, "", physicalEffective);
505
886
  } else {
506
- window.history.pushState(null, "", effectiveHref);
887
+ window.history.pushState(null, "", physicalEffective);
507
888
  }
508
- const effectiveUrl = new URL(effectiveHref, window.location.origin);
509
- setCurrentHref(effectiveUrl.pathname + effectiveUrl.search);
889
+ const effectiveUrl = new URL(physicalEffective, window.location.origin);
890
+ const logicalPath = toLogical(effectiveUrl.pathname, basePath);
891
+ setCurrentHref(logicalPath + effectiveUrl.search);
510
892
  if (opts?.resetScroll ?? true) {
511
- handleScrollRestoration(effectiveHref, myVersion, navVersion);
893
+ handleScrollRestoration(physicalEffective, myVersion, navVersion);
512
894
  }
513
895
  } finally {
514
896
  if (navVersion.current === myVersion) {
515
897
  setIsNavigating(false);
516
898
  }
517
899
  }
518
- }, [prefetch]);
900
+ }, [prefetch, basePath]);
519
901
  const refresh = useCallback(async (opts) => {
520
- const href = window.location.pathname + window.location.search;
521
- invalidatePrefetch(href, "page");
522
- await navigate(href, { replace: true, resetScroll: opts?.resetScroll ?? false });
523
- }, [navigate, invalidatePrefetch]);
902
+ const logicalPath = toLogical(window.location.pathname, basePath);
903
+ const logicalHref = logicalPath + window.location.search;
904
+ invalidatePrefetch(logicalHref, "page");
905
+ await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
906
+ }, [navigate, invalidatePrefetch, basePath]);
524
907
  const handlePopState = useCallback(async () => {
525
- const href = window.location.pathname + window.location.search;
908
+ const logicalPath = toLogical(window.location.pathname, basePath);
909
+ const logicalHref = logicalPath + window.location.search;
526
910
  const myVersion = ++navVersion.current;
527
911
  setIsNavigating(true);
528
912
  try {
529
- const cached = prefetchCache.current.get(href);
913
+ const cached = prefetchCache.current.get(logicalHref);
530
914
  let newState;
531
915
  if (cached && !shouldRefetch(cached)) {
532
916
  newState = await cached.promise;
533
917
  } else {
534
- newState = await fetchPageState(href);
918
+ newState = await fetchPageState(logicalHref);
535
919
  }
536
920
  if (navVersion.current !== myVersion) {
537
921
  return;
538
922
  }
539
923
  if (!newState) {
540
- _log.warn({ action: "popstate_fallback", href, reason: "fetchPageState_returned_null" });
924
+ _log.warn({
925
+ action: "popstate_fallback",
926
+ href: logicalHref,
927
+ reason: "fetchPageState_returned_null"
928
+ });
541
929
  window.location.reload();
542
930
  return;
543
931
  }
@@ -545,18 +933,17 @@ function RouterProvider({
545
933
  if (newState.title) {
546
934
  document.title = newState.title;
547
935
  }
548
- const effectiveHref = newState.finalHref ?? href;
936
+ const effectiveLogical = newState.finalHref ?? logicalHref;
549
937
  if (newState.finalHref) {
550
- window.history.replaceState(null, "", effectiveHref);
938
+ window.history.replaceState(null, "", basePath + effectiveLogical);
551
939
  }
552
- const effectiveUrl = new URL(effectiveHref, window.location.origin);
553
- setCurrentHref(effectiveUrl.pathname + effectiveUrl.search);
940
+ setCurrentHref(effectiveLogical);
554
941
  } finally {
555
942
  if (navVersion.current === myVersion) {
556
943
  setIsNavigating(false);
557
944
  }
558
945
  }
559
- }, [fetchPageState]);
946
+ }, [fetchPageState, basePath]);
560
947
  useEffect(() => {
561
948
  window.addEventListener("popstate", handlePopState);
562
949
  return () => window.removeEventListener("popstate", handlePopState);
@@ -589,6 +976,7 @@ function RouterProvider({
589
976
  }, [invalidatePrefetch, refresh, autoRefresh]);
590
977
  return createElement(RouterContext.Provider, {
591
978
  value: {
979
+ basePath,
592
980
  currentHref,
593
981
  navigate,
594
982
  prefetch,
@@ -601,7 +989,26 @@ function RouterProvider({
601
989
  }
602
990
  }, buildPageElement(state.match, root, state.data));
603
991
  }
604
- function Link({
992
+ function computeLinkView({
993
+ to,
994
+ search,
995
+ hash,
996
+ children,
997
+ activeProps,
998
+ inactiveProps
999
+ }, router) {
1000
+ const logicalHref = buildHref(to, search, hash);
1001
+ const logicalHrefWithoutHash = buildHref(to, search, undefined);
1002
+ const href = router.basePath + logicalHref;
1003
+ const isActive = router.currentHref === logicalHrefWithoutHash;
1004
+ const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
1005
+ const extraProps = {
1006
+ ...inactiveProps && !isActive ? inactiveProps() : {},
1007
+ ...activeProps ? activeProps({ isActive }) : {}
1008
+ };
1009
+ return { logicalHref, href, isActive, resolvedChildren, extraProps };
1010
+ }
1011
+ function LinkInteractive({
605
1012
  to,
606
1013
  search,
607
1014
  hash,
@@ -623,15 +1030,13 @@ function Link({
623
1030
  const router = useRouter();
624
1031
  const anchorRef = useRef(null);
625
1032
  const intentTimerRef = useRef(null);
626
- const href = buildHref(to, search, hash);
627
- const hrefWithoutHash = buildHref(to, search, undefined);
628
- const isActive = router.currentHref === hrefWithoutHash;
1033
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
629
1034
  const effectivePreload = preload ?? router.defaultPreload;
630
1035
  const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
631
1036
  const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
632
1037
  const triggerPrefetch = useCallback(() => {
633
- router.prefetch(href, { staleTime: effectiveStaleTime });
634
- }, [router, href, effectiveStaleTime]);
1038
+ router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
1039
+ }, [router, logicalHref, effectiveStaleTime]);
635
1040
  useEffect(() => {
636
1041
  if (effectivePreload === "render") {
637
1042
  triggerPrefetch();
@@ -672,7 +1077,7 @@ function Link({
672
1077
  return;
673
1078
  }
674
1079
  e.preventDefault();
675
- router.navigate(href, { replace, resetScroll: resetScroll ?? true });
1080
+ router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
676
1081
  };
677
1082
  const handleMouseEnter = (e) => {
678
1083
  onMouseEnter?.(e);
@@ -693,11 +1098,6 @@ function Link({
693
1098
  triggerPrefetch();
694
1099
  }
695
1100
  };
696
- const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
697
- const extraProps = {
698
- ...inactiveProps && !isActive ? inactiveProps() : {},
699
- ...activeProps ? activeProps({ isActive }) : {}
700
- };
701
1101
  return createElement("a", {
702
1102
  ref: anchorRef,
703
1103
  href,
@@ -711,6 +1111,55 @@ function Link({
711
1111
  ...disabled ? { "aria-disabled": true } : {}
712
1112
  }, resolvedChildren);
713
1113
  }
1114
+ var SSR_FALLBACK_ROUTER = {
1115
+ basePath: "",
1116
+ currentHref: "/",
1117
+ navigate: () => Promise.resolve(),
1118
+ prefetch: () => {},
1119
+ invalidatePrefetch: () => {},
1120
+ refresh: () => Promise.resolve(),
1121
+ isNavigating: false,
1122
+ defaultPreload: "intent",
1123
+ defaultPreloadDelay: 50,
1124
+ defaultPreloadStaleTime: 30000
1125
+ };
1126
+ function renderLinkElement(props, router) {
1127
+ const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
1128
+ const {
1129
+ to: _to,
1130
+ search: _search,
1131
+ hash: _hash,
1132
+ children: _children,
1133
+ activeProps: _ap,
1134
+ inactiveProps: _ip,
1135
+ disabled,
1136
+ preload: _p,
1137
+ preloadDelay: _pd,
1138
+ preloadStaleTime: _ps,
1139
+ replace: _r,
1140
+ resetScroll: _rs,
1141
+ onClick: _oc,
1142
+ onMouseEnter: _ome,
1143
+ onMouseLeave: _oml,
1144
+ onFocus: _of,
1145
+ ...anchorProps
1146
+ } = props;
1147
+ return createElement("a", {
1148
+ href,
1149
+ ...isActive ? { "data-status": "active" } : {},
1150
+ ...anchorProps,
1151
+ ...extraProps,
1152
+ ...disabled ? { "aria-disabled": true } : {}
1153
+ }, resolvedChildren);
1154
+ }
1155
+ function Link(props) {
1156
+ if (typeof window === "undefined") {
1157
+ return createElement(RouterContext.Consumer, {
1158
+ children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
1159
+ });
1160
+ }
1161
+ return createElement(LinkInteractive, props);
1162
+ }
714
1163
  export {
715
1164
  useRouter,
716
1165
  shouldRefetch,