@teyik0/furin 0.1.0-alpha.10 → 0.1.0-alpha.12

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.
package/dist/cli/index.js CHANGED
@@ -1537,10 +1537,15 @@ function generateHydrateEntry(routes, rootLayout, basePath) {
1537
1537
  const conventionImportLines = [...conventionIdents.entries()].map(([filePath, ident]) => `import ${ident} from "${filePath.replace(/\\/g, "/")}";`).join(`
1538
1538
  `);
1539
1539
  const basePathLiteral = JSON.stringify(basePath);
1540
- const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; return (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; })()` : "window.location.pathname";
1540
+ const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; const stripped = (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; return stripped === "/" ? "/" : stripped.replace(/\\/+$/, ""); })()` : `window.location.pathname.replace(/\\/+$/, "") || "/"`;
1541
1541
  const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
1542
- const basePathProp = basePath ? `
1543
- basePath: ${basePathLiteral},` : "";
1542
+ const routerProviderDefaults = `
1543
+ autoRefresh: true,
1544
+ basePath: ${basePathLiteral},
1545
+ defaultPreload: "intent",
1546
+ defaultPreloadDelay: 50,
1547
+ defaultPreloadStaleTime: 30000,
1548
+ prefetchCacheSize: 50,`;
1544
1549
  const conventionImportsBlock = conventionImportLines ? `
1545
1550
  ${conventionImportLines}` : "";
1546
1551
  return `import { hydrateRoot, createRoot } from "react-dom/client";
@@ -1589,7 +1594,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
1589
1594
  initialMatch: match,
1590
1595
  initialData: loaderData,
1591
1596
  initialDigest: loaderData.__furinError?.digest,
1592
- initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${basePathProp}
1597
+ initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
1593
1598
  } as any);
1594
1599
  } else if (loaderData.__furinStatus === 404) {
1595
1600
  // Direct load to an unknown URL. The server sent the root not-found UI
@@ -1606,7 +1611,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
1606
1611
  initialMatch: null,
1607
1612
  initialData: cleanData,
1608
1613
  initialDigest: loaderData.__furinError?.digest,
1609
- initialNotFound: loaderData.__furinNotFound ?? {},${basePathProp}
1614
+ initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
1610
1615
  } as any);
1611
1616
  } else {
1612
1617
  // No match and no 404 signal \u2014 either the client bundle is out of sync
@@ -2175,16 +2180,38 @@ function assembleHTML(template, headData, reactHtml, data) {
2175
2180
  }
2176
2181
 
2177
2182
  // src/render/index.ts
2178
- import { createElement as createElement2 } from "react";
2183
+ import { createElement as createElement3 } from "react";
2179
2184
  import { renderToReadableStream } from "react-dom/server";
2180
- // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/utils.mjs
2185
+
2186
+ // src/not-found.ts
2187
+ var NOT_FOUND_BRAND = "FURIN_NOT_FOUND";
2188
+
2189
+ class FurinNotFoundError extends Error {
2190
+ __furinBrand = NOT_FOUND_BRAND;
2191
+ data;
2192
+ constructor(options) {
2193
+ super(options?.message ?? "");
2194
+ this.data = options?.data;
2195
+ }
2196
+ }
2197
+ function isNotFoundError(err) {
2198
+ return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
2199
+ }
2200
+
2201
+ // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/utils.mjs
2181
2202
  function formatDuration(ms) {
2182
2203
  if (ms < 1000)
2183
2204
  return `${Math.round(ms)}ms`;
2184
2205
  return `${(ms / 1000).toFixed(2)}s`;
2185
2206
  }
2186
- function isClient() {
2187
- return typeof window !== "undefined";
2207
+ function isBrowser() {
2208
+ if (typeof window === "undefined")
2209
+ return false;
2210
+ if (typeof document === "undefined")
2211
+ return false;
2212
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative")
2213
+ return false;
2214
+ return true;
2188
2215
  }
2189
2216
  function isDev() {
2190
2217
  if (typeof process !== "undefined")
@@ -2270,7 +2297,7 @@ function matchesPattern(path, pattern) {
2270
2297
  return regex.test(path);
2271
2298
  }
2272
2299
 
2273
- // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/logger-DnobymUQ.mjs
2300
+ // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/audit-DQoBo7Dl.mjs
2274
2301
  var DEFAULT_REPLACEMENT = "[REDACTED]";
2275
2302
  var builtinPatterns = {
2276
2303
  creditCard: {
@@ -2291,7 +2318,7 @@ var builtinPatterns = {
2291
2318
  mask: (m) => `***.***.***.${m.split(".").pop()}`
2292
2319
  },
2293
2320
  phone: {
2294
- pattern: /(?:\+\d{1,3}[\s.-]?)?\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}\b/g,
2321
+ pattern: /(?:\+\d{1,3}[\s.-]?\(?\d{1,4}\)?|\(\d{1,4}\))(?:[\s.-]?\d{2,4}){2,4}\b/g,
2295
2322
  mask: (m) => {
2296
2323
  const digits = m.replace(/[^\d]/g, "");
2297
2324
  if (m.startsWith("+") && digits.length > 4) {
@@ -2504,7 +2531,8 @@ function shouldKeep(ctx) {
2504
2531
  return false;
2505
2532
  });
2506
2533
  }
2507
- function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
2534
+ function emitWideEvent(level, event, options = {}) {
2535
+ const { deferDrain = false, ownsEvent = false, waitUntil } = options;
2508
2536
  if (!globalEnabled)
2509
2537
  return null;
2510
2538
  if (!ownsEvent) {
@@ -2535,6 +2563,7 @@ function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
2535
2563
  ...globalEnv,
2536
2564
  ...event
2537
2565
  };
2566
+ finalizeAudit(formatted);
2538
2567
  if (globalRedact)
2539
2568
  redactEvent(formatted, globalRedact);
2540
2569
  if (!globalSilent)
@@ -2544,10 +2573,13 @@ function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
2544
2573
  console[getConsoleMethod(level)](JSON.stringify(formatted));
2545
2574
  else
2546
2575
  console[getConsoleMethod(level)](formatted);
2547
- if (globalDrain && !deferDrain)
2548
- Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
2576
+ if (globalDrain && !deferDrain) {
2577
+ const drainPromise = Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
2549
2578
  console.error("[evlog] drain failed:", err);
2550
2579
  });
2580
+ if (waitUntil)
2581
+ waitUntil(drainPromise);
2582
+ }
2551
2583
  return formatted;
2552
2584
  }
2553
2585
  function emitTaggedLog(level, tag, message) {
@@ -2558,7 +2590,7 @@ function emitTaggedLog(level, tag, message) {
2558
2590
  return;
2559
2591
  if (!shouldSample(level))
2560
2592
  return;
2561
- if (isClient()) {
2593
+ if (isBrowser()) {
2562
2594
  const levelColor = getCssLevelColor(level);
2563
2595
  const timestamp = isoNow().slice(11, 23);
2564
2596
  console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
@@ -2755,7 +2787,7 @@ function buildAIEntries(ai) {
2755
2787
  function prettyPrintWideEvent(event) {
2756
2788
  const { timestamp, level, service, environment, version, ...rest } = event;
2757
2789
  const ts = timestamp.slice(11, 23);
2758
- const browser = isClient();
2790
+ const browser = isBrowser();
2759
2791
  const parts = [];
2760
2792
  const styles = [];
2761
2793
  if (browser) {
@@ -2848,12 +2880,14 @@ var noopLogger = {
2848
2880
  },
2849
2881
  getContext() {
2850
2882
  return {};
2851
- }
2883
+ },
2884
+ audit: Object.assign(() => {}, { deny: () => {} })
2852
2885
  };
2853
2886
  function createLogger(initialContext = {}, internalOptions) {
2854
2887
  if (!globalEnabled)
2855
2888
  return noopLogger;
2856
2889
  const deferDrain = internalOptions?._deferDrain ?? false;
2890
+ const waitUntil = internalOptions?.waitUntil;
2857
2891
  const startTime = Date.now();
2858
2892
  const context = { ...initialContext };
2859
2893
  let hasError = false;
@@ -2868,7 +2902,27 @@ function createLogger(initialContext = {}, internalOptions) {
2868
2902
  timestamp: isoNow()
2869
2903
  });
2870
2904
  }
2905
+ const auditMethod = function audit(input) {
2906
+ if (emitted) {
2907
+ warnPostEmit("log.audit()", `Audit dropped: action=${input.action}.`);
2908
+ return;
2909
+ }
2910
+ const fields = buildAuditFields(input);
2911
+ if (!isPlainObject(context.audit))
2912
+ context.audit = fields;
2913
+ else
2914
+ mergeInto(context.audit, fields);
2915
+ context._auditForceKeep = true;
2916
+ };
2917
+ auditMethod.deny = function deny(reason, input) {
2918
+ auditMethod({
2919
+ ...input,
2920
+ outcome: "denied",
2921
+ reason
2922
+ });
2923
+ };
2871
2924
  return {
2925
+ audit: auditMethod,
2872
2926
  set(data) {
2873
2927
  if (emitted) {
2874
2928
  const keys = Object.keys(data);
@@ -2941,6 +2995,8 @@ function createLogger(initialContext = {}, internalOptions) {
2941
2995
  let forceKeep = false;
2942
2996
  if (overrides?._forceKeep)
2943
2997
  forceKeep = true;
2998
+ else if (consumeAuditForceKeep(context))
2999
+ forceKeep = true;
2944
3000
  else if (globalSampling.keep?.length)
2945
3001
  forceKeep = shouldKeep({
2946
3002
  status: overrides?.status ?? context.status,
@@ -2960,7 +3016,11 @@ function createLogger(initialContext = {}, internalOptions) {
2960
3016
  context[key] = obj[key];
2961
3017
  }
2962
3018
  context.duration = formatDuration(durationMs);
2963
- const wide = emitWideEvent(level, context, deferDrain, true);
3019
+ const wide = emitWideEvent(level, context, {
3020
+ deferDrain,
3021
+ ownsEvent: true,
3022
+ waitUntil
3023
+ });
2964
3024
  emitted = true;
2965
3025
  return wide;
2966
3026
  },
@@ -2971,15 +3031,88 @@ function createLogger(initialContext = {}, internalOptions) {
2971
3031
  }
2972
3032
  if (typeof __EVLOG_CONFIG__ !== "undefined")
2973
3033
  initLogger(__EVLOG_CONFIG__);
2974
- // src/link.tsx
3034
+ function stableStringify(value) {
3035
+ if (value === null || typeof value !== "object")
3036
+ return JSON.stringify(value);
3037
+ if (Array.isArray(value))
3038
+ return `[${value.map(stableStringify).join(",")}]`;
3039
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
3040
+ }
3041
+ function fnv1a32(input, seed) {
3042
+ let h = seed >>> 0;
3043
+ for (let i = 0;i < input.length; i++) {
3044
+ h ^= input.charCodeAt(i) & 255;
3045
+ h = Math.imul(h, 16777619) >>> 0;
3046
+ }
3047
+ return h >>> 0;
3048
+ }
3049
+ function computeIdempotencyKey(audit, timestamp) {
3050
+ const seconds = timestamp.slice(0, 19);
3051
+ const payload = stableStringify({
3052
+ action: audit.action,
3053
+ actor: {
3054
+ type: audit.actor.type,
3055
+ id: audit.actor.id
3056
+ },
3057
+ target: audit.target ? {
3058
+ type: audit.target.type,
3059
+ id: audit.target.id
3060
+ } : undefined,
3061
+ outcome: audit.outcome,
3062
+ timestamp: seconds
3063
+ });
3064
+ const a = fnv1a32(payload, 2166136261).toString(16).padStart(8, "0");
3065
+ const b = fnv1a32(payload, 3735928559).toString(16).padStart(8, "0");
3066
+ const c = fnv1a32(payload, 528734635).toString(16).padStart(8, "0");
3067
+ const d = fnv1a32(payload, 1541459225).toString(16).padStart(8, "0");
3068
+ return a + b + c + d;
3069
+ }
3070
+ function buildAuditFields(input) {
3071
+ return {
3072
+ action: input.action,
3073
+ actor: input.actor,
3074
+ target: input.target,
3075
+ outcome: input.outcome ?? "success",
3076
+ reason: input.reason,
3077
+ changes: input.changes,
3078
+ causationId: input.causationId,
3079
+ correlationId: input.correlationId,
3080
+ version: input.version ?? 1
3081
+ };
3082
+ }
3083
+ function decorateAudit(audit, timestamp) {
3084
+ if (audit.idempotencyKey)
3085
+ return audit;
3086
+ return {
3087
+ ...audit,
3088
+ idempotencyKey: computeIdempotencyKey(audit, timestamp)
3089
+ };
3090
+ }
3091
+ function consumeAuditForceKeep(context) {
3092
+ if (context._auditForceKeep) {
3093
+ delete context._auditForceKeep;
3094
+ return true;
3095
+ }
3096
+ if (context.audit)
3097
+ return true;
3098
+ return false;
3099
+ }
3100
+ function finalizeAudit(event) {
3101
+ const a = event.audit;
3102
+ if (!a)
3103
+ return;
3104
+ event.audit = decorateAudit(a, String(event.timestamp));
3105
+ }
3106
+ // src/router-provider.tsx
2975
3107
  import {
2976
3108
  createContext,
2977
- createElement,
2978
- useCallback,
3109
+ createElement as createElement2,
3110
+ useCallback as useCallback2,
2979
3111
  useContext,
2980
- useEffect,
3112
+ useEffect as useEffect2,
3113
+ useLayoutEffect,
2981
3114
  useMemo,
2982
- useRef,
3115
+ useRef as useRef2,
2983
3116
  useState
2984
3117
  } from "react";
2985
3118
 
@@ -2995,19 +3128,193 @@ function getPublicErrorMessage(error) {
2995
3128
  return "Something went wrong";
2996
3129
  }
2997
3130
 
2998
- // src/not-found.ts
2999
- var NOT_FOUND_BRAND = "FURIN_NOT_FOUND";
3000
-
3001
- class FurinNotFoundError extends Error {
3002
- __furinBrand = NOT_FOUND_BRAND;
3003
- data;
3004
- constructor(options) {
3005
- super(options?.message ?? "");
3006
- this.data = options?.data;
3007
- }
3131
+ // src/link.tsx
3132
+ import { createElement, useCallback, useEffect, useRef } from "react";
3133
+ function computeLinkView({
3134
+ to,
3135
+ search,
3136
+ hash,
3137
+ children,
3138
+ activeProps,
3139
+ inactiveProps
3140
+ }, router) {
3141
+ const logicalHref = buildHref(to, search, hash);
3142
+ const logicalHrefWithoutHash = buildHref(to, search, undefined);
3143
+ const isAbsolute = logicalHref.startsWith("http://") || logicalHref.startsWith("https://") || logicalHref.startsWith("//");
3144
+ const href = isAbsolute ? logicalHref : router.basePath + logicalHref;
3145
+ const isActive = router.currentHref === logicalHrefWithoutHash;
3146
+ const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
3147
+ const extraProps = {
3148
+ ...inactiveProps && !isActive ? inactiveProps() : {},
3149
+ ...activeProps ? activeProps({ isActive }) : {}
3150
+ };
3151
+ return { logicalHref, href, isActive, resolvedChildren, extraProps };
3008
3152
  }
3009
- function isNotFoundError(err) {
3010
- return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
3153
+ function LinkInteractive({
3154
+ to,
3155
+ search,
3156
+ hash,
3157
+ preload,
3158
+ preloadDelay,
3159
+ preloadStaleTime,
3160
+ replace,
3161
+ disabled,
3162
+ resetScroll,
3163
+ activeProps,
3164
+ inactiveProps,
3165
+ onClick,
3166
+ onMouseEnter,
3167
+ onMouseLeave,
3168
+ onFocus,
3169
+ children,
3170
+ href: _href,
3171
+ ...anchorProps
3172
+ }) {
3173
+ const router = useRouter();
3174
+ const anchorRef = useRef(null);
3175
+ const intentTimerRef = useRef(null);
3176
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
3177
+ const effectivePreload = preload ?? router.defaultPreload;
3178
+ const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
3179
+ const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
3180
+ const triggerPrefetch = useCallback(() => {
3181
+ router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
3182
+ }, [router, logicalHref, effectiveStaleTime]);
3183
+ useEffect(() => {
3184
+ if (effectivePreload === "render") {
3185
+ triggerPrefetch();
3186
+ }
3187
+ }, [effectivePreload, triggerPrefetch]);
3188
+ useEffect(() => {
3189
+ if (effectivePreload !== "viewport" || !anchorRef.current) {
3190
+ return;
3191
+ }
3192
+ const observer = new IntersectionObserver(([entry]) => {
3193
+ if (entry?.isIntersecting) {
3194
+ triggerPrefetch();
3195
+ observer.disconnect();
3196
+ }
3197
+ }, { rootMargin: "200px" });
3198
+ observer.observe(anchorRef.current);
3199
+ return () => observer.disconnect();
3200
+ }, [effectivePreload, triggerPrefetch]);
3201
+ useEffect(() => () => {
3202
+ if (intentTimerRef.current !== null) {
3203
+ clearTimeout(intentTimerRef.current);
3204
+ intentTimerRef.current = null;
3205
+ }
3206
+ }, []);
3207
+ const isInternal = (url) => {
3208
+ try {
3209
+ return new URL(url, window.location.origin).origin === window.location.origin;
3210
+ } catch {
3211
+ return false;
3212
+ }
3213
+ };
3214
+ const handleClick = (e) => {
3215
+ onClick?.(e);
3216
+ if (e.defaultPrevented) {
3217
+ return;
3218
+ }
3219
+ if (disabled) {
3220
+ e.preventDefault();
3221
+ return;
3222
+ }
3223
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
3224
+ return;
3225
+ }
3226
+ if (anchorProps.target && anchorProps.target !== "_self") {
3227
+ return;
3228
+ }
3229
+ if (!isInternal(href)) {
3230
+ return;
3231
+ }
3232
+ e.preventDefault();
3233
+ router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
3234
+ };
3235
+ const handleMouseEnter = (e) => {
3236
+ onMouseEnter?.(e);
3237
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3238
+ intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
3239
+ }
3240
+ };
3241
+ const handleMouseLeave = (e) => {
3242
+ onMouseLeave?.(e);
3243
+ if (intentTimerRef.current !== null) {
3244
+ clearTimeout(intentTimerRef.current);
3245
+ intentTimerRef.current = null;
3246
+ }
3247
+ };
3248
+ const handleFocus = (e) => {
3249
+ onFocus?.(e);
3250
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3251
+ triggerPrefetch();
3252
+ }
3253
+ };
3254
+ return createElement("a", {
3255
+ ref: anchorRef,
3256
+ href,
3257
+ "data-furin-link": true,
3258
+ onClick: handleClick,
3259
+ onMouseEnter: handleMouseEnter,
3260
+ onMouseLeave: handleMouseLeave,
3261
+ onFocus: handleFocus,
3262
+ ...isActive ? { "data-status": "active" } : {},
3263
+ ...anchorProps,
3264
+ ...extraProps,
3265
+ ...disabled ? { "aria-disabled": true } : {}
3266
+ }, resolvedChildren);
3267
+ }
3268
+ var SSR_FALLBACK_ROUTER = {
3269
+ basePath: "",
3270
+ currentHref: "/",
3271
+ navigate: () => Promise.resolve(),
3272
+ prefetch: () => {},
3273
+ invalidatePrefetch: () => {},
3274
+ refresh: () => Promise.resolve(),
3275
+ isNavigating: false,
3276
+ defaultPreload: "intent",
3277
+ defaultPreloadDelay: 50,
3278
+ defaultPreloadStaleTime: 30000
3279
+ };
3280
+ function renderLinkElement(props, router) {
3281
+ const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
3282
+ const {
3283
+ to: _to,
3284
+ search: _search,
3285
+ hash: _hash,
3286
+ children: _children,
3287
+ activeProps: _ap,
3288
+ inactiveProps: _ip,
3289
+ disabled,
3290
+ preload: _p,
3291
+ preloadDelay: _pd,
3292
+ preloadStaleTime: _ps,
3293
+ replace: _r,
3294
+ resetScroll: _rs,
3295
+ onClick: _oc,
3296
+ onMouseEnter: _ome,
3297
+ onMouseLeave: _oml,
3298
+ onFocus: _of,
3299
+ href: _href,
3300
+ ...anchorProps
3301
+ } = props;
3302
+ return createElement("a", {
3303
+ href,
3304
+ "data-furin-link": true,
3305
+ ...isActive ? { "data-status": "active" } : {},
3306
+ ...anchorProps,
3307
+ ...extraProps,
3308
+ ...disabled ? { "aria-disabled": true } : {}
3309
+ }, resolvedChildren);
3310
+ }
3311
+ function Link(props) {
3312
+ if (typeof window === "undefined") {
3313
+ return createElement(RouterContext.Consumer, {
3314
+ children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
3315
+ });
3316
+ }
3317
+ return createElement(LinkInteractive, props);
3011
3318
  }
3012
3319
 
3013
3320
  // src/render/default-screens.tsx
@@ -3395,7 +3702,7 @@ class FurinNotFoundBoundary extends Component {
3395
3702
  }
3396
3703
  }
3397
3704
 
3398
- // src/link.tsx
3705
+ // src/router-provider.tsx
3399
3706
  import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
3400
3707
  function buildHref(to, search, hash) {
3401
3708
  let url = to;
@@ -3418,7 +3725,8 @@ function buildHref(to, search, hash) {
3418
3725
  }
3419
3726
  var RouterContext = createContext(null);
3420
3727
  function useRouter() {
3421
- return useContext(RouterContext) ?? {
3728
+ const ctx = useContext(RouterContext);
3729
+ return ctx ?? {
3422
3730
  basePath: "",
3423
3731
  currentHref: "/",
3424
3732
  navigate: (href) => {
@@ -3437,177 +3745,6 @@ function useRouter() {
3437
3745
  defaultPreloadStaleTime: 30000
3438
3746
  };
3439
3747
  }
3440
- function computeLinkView({
3441
- to,
3442
- search,
3443
- hash,
3444
- children,
3445
- activeProps,
3446
- inactiveProps
3447
- }, router) {
3448
- const logicalHref = buildHref(to, search, hash);
3449
- const logicalHrefWithoutHash = buildHref(to, search, undefined);
3450
- const href = router.basePath + logicalHref;
3451
- const isActive = router.currentHref === logicalHrefWithoutHash;
3452
- const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
3453
- const extraProps = {
3454
- ...inactiveProps && !isActive ? inactiveProps() : {},
3455
- ...activeProps ? activeProps({ isActive }) : {}
3456
- };
3457
- return { logicalHref, href, isActive, resolvedChildren, extraProps };
3458
- }
3459
- function LinkInteractive({
3460
- to,
3461
- search,
3462
- hash,
3463
- preload,
3464
- preloadDelay,
3465
- preloadStaleTime,
3466
- replace,
3467
- disabled,
3468
- resetScroll,
3469
- activeProps,
3470
- inactiveProps,
3471
- onClick,
3472
- onMouseEnter,
3473
- onMouseLeave,
3474
- onFocus,
3475
- children,
3476
- ...anchorProps
3477
- }) {
3478
- const router = useRouter();
3479
- const anchorRef = useRef(null);
3480
- const intentTimerRef = useRef(null);
3481
- const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
3482
- const effectivePreload = preload ?? router.defaultPreload;
3483
- const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
3484
- const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
3485
- const triggerPrefetch = useCallback(() => {
3486
- router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
3487
- }, [router, logicalHref, effectiveStaleTime]);
3488
- useEffect(() => {
3489
- if (effectivePreload === "render") {
3490
- triggerPrefetch();
3491
- }
3492
- }, [effectivePreload, triggerPrefetch]);
3493
- useEffect(() => {
3494
- if (effectivePreload !== "viewport" || !anchorRef.current) {
3495
- return;
3496
- }
3497
- const observer = new IntersectionObserver(([entry]) => {
3498
- if (entry?.isIntersecting) {
3499
- triggerPrefetch();
3500
- observer.disconnect();
3501
- }
3502
- }, { rootMargin: "200px" });
3503
- observer.observe(anchorRef.current);
3504
- return () => observer.disconnect();
3505
- }, [effectivePreload, triggerPrefetch]);
3506
- const isInternal = (url) => {
3507
- try {
3508
- return new URL(url, window.location.origin).origin === window.location.origin;
3509
- } catch {
3510
- return false;
3511
- }
3512
- };
3513
- const handleClick = (e) => {
3514
- onClick?.(e);
3515
- if (e.defaultPrevented || disabled) {
3516
- return;
3517
- }
3518
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
3519
- return;
3520
- }
3521
- if (anchorProps.target && anchorProps.target !== "_self") {
3522
- return;
3523
- }
3524
- if (!isInternal(href)) {
3525
- return;
3526
- }
3527
- e.preventDefault();
3528
- router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
3529
- };
3530
- const handleMouseEnter = (e) => {
3531
- onMouseEnter?.(e);
3532
- if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3533
- intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
3534
- }
3535
- };
3536
- const handleMouseLeave = (e) => {
3537
- onMouseLeave?.(e);
3538
- if (intentTimerRef.current !== null) {
3539
- clearTimeout(intentTimerRef.current);
3540
- intentTimerRef.current = null;
3541
- }
3542
- };
3543
- const handleFocus = (e) => {
3544
- onFocus?.(e);
3545
- if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3546
- triggerPrefetch();
3547
- }
3548
- };
3549
- return createElement("a", {
3550
- ref: anchorRef,
3551
- href,
3552
- onClick: handleClick,
3553
- onMouseEnter: handleMouseEnter,
3554
- onMouseLeave: handleMouseLeave,
3555
- onFocus: handleFocus,
3556
- ...isActive ? { "data-status": "active" } : {},
3557
- ...anchorProps,
3558
- ...extraProps,
3559
- ...disabled ? { "aria-disabled": true } : {}
3560
- }, resolvedChildren);
3561
- }
3562
- var SSR_FALLBACK_ROUTER = {
3563
- basePath: "",
3564
- currentHref: "/",
3565
- navigate: () => Promise.resolve(),
3566
- prefetch: () => {},
3567
- invalidatePrefetch: () => {},
3568
- refresh: () => Promise.resolve(),
3569
- isNavigating: false,
3570
- defaultPreload: "intent",
3571
- defaultPreloadDelay: 50,
3572
- defaultPreloadStaleTime: 30000
3573
- };
3574
- function renderLinkElement(props, router) {
3575
- const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
3576
- const {
3577
- to: _to,
3578
- search: _search,
3579
- hash: _hash,
3580
- children: _children,
3581
- activeProps: _ap,
3582
- inactiveProps: _ip,
3583
- disabled,
3584
- preload: _p,
3585
- preloadDelay: _pd,
3586
- preloadStaleTime: _ps,
3587
- replace: _r,
3588
- resetScroll: _rs,
3589
- onClick: _oc,
3590
- onMouseEnter: _ome,
3591
- onMouseLeave: _oml,
3592
- onFocus: _of,
3593
- ...anchorProps
3594
- } = props;
3595
- return createElement("a", {
3596
- href,
3597
- ...isActive ? { "data-status": "active" } : {},
3598
- ...anchorProps,
3599
- ...extraProps,
3600
- ...disabled ? { "aria-disabled": true } : {}
3601
- }, resolvedChildren);
3602
- }
3603
- function Link(props) {
3604
- if (typeof window === "undefined") {
3605
- return createElement(RouterContext.Consumer, {
3606
- children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
3607
- });
3608
- }
3609
- return createElement(LinkInteractive, props);
3610
- }
3611
3748
 
3612
3749
  // src/render/cache.ts
3613
3750
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
@@ -3615,7 +3752,7 @@ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3615
3752
  // src/context-logger.ts
3616
3753
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3617
3754
 
3618
- // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
3755
+ // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/elysia/index.mjs
3619
3756
  import { AsyncLocalStorage } from "async_hooks";
3620
3757
  import { Elysia } from "elysia";
3621
3758
  var storage = new AsyncLocalStorage;
@@ -3658,33 +3795,139 @@ async function runInSyntheticRenderScope(fn, initialContext) {
3658
3795
  }
3659
3796
  }
3660
3797
 
3661
- // src/render/cache.ts
3662
- var MAX_SSG_CACHE_SIZE = 1000;
3663
- var isrCache = new Map;
3664
- var ssgCache = new Map;
3665
- function evictOldest(map, maxSize) {
3666
- if (map.size > maxSize) {
3667
- const oldest = map.keys().next().value;
3798
+ // src/render/route-cache.ts
3799
+ function defaultPathFromKey(key) {
3800
+ return key;
3801
+ }
3802
+ function matchesPath(urlPath, path, type) {
3803
+ if (type === "page") {
3804
+ return urlPath === path;
3805
+ }
3806
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
3807
+ return urlPath === path || urlPath.startsWith(prefix);
3808
+ }
3809
+ function createRouteCache(options) {
3810
+ const store = new Map;
3811
+ const pathFromKey = options.pathFromKey ?? defaultPathFromKey;
3812
+ const evictOldest = () => {
3813
+ if (options.maxSize === undefined || store.size <= options.maxSize) {
3814
+ return;
3815
+ }
3816
+ const oldest = store.keys().next().value;
3668
3817
  if (oldest !== undefined) {
3669
- map.delete(oldest);
3818
+ deleteEntry(oldest);
3670
3819
  }
3671
- }
3820
+ };
3821
+ const deleteEntry = (key) => {
3822
+ const entry = store.get(key);
3823
+ if (entry === undefined) {
3824
+ return false;
3825
+ }
3826
+ store.delete(key);
3827
+ options.onDelete?.(key, entry);
3828
+ return true;
3829
+ };
3830
+ return {
3831
+ name: options.name,
3832
+ store,
3833
+ get size() {
3834
+ return store.size;
3835
+ },
3836
+ get(key) {
3837
+ const entry = store.get(key);
3838
+ if (entry !== undefined && options.maxSize !== undefined) {
3839
+ store.delete(key);
3840
+ store.set(key, entry);
3841
+ }
3842
+ return entry;
3843
+ },
3844
+ set(key, entry) {
3845
+ const previous = store.get(key);
3846
+ if (previous !== undefined) {
3847
+ store.delete(key);
3848
+ }
3849
+ store.set(key, entry);
3850
+ options.onSet?.(key, entry, previous);
3851
+ evictOldest();
3852
+ },
3853
+ delete(key) {
3854
+ return deleteEntry(key);
3855
+ },
3856
+ clear() {
3857
+ for (const key of [...store.keys()]) {
3858
+ deleteEntry(key);
3859
+ }
3860
+ store.clear();
3861
+ },
3862
+ has(key) {
3863
+ return store.has(key);
3864
+ },
3865
+ entries() {
3866
+ return store.entries();
3867
+ },
3868
+ keys() {
3869
+ return store.keys();
3870
+ },
3871
+ invalidatePath(path, type) {
3872
+ let deleted = false;
3873
+ const purgedPaths = [];
3874
+ for (const key of [...store.keys()]) {
3875
+ const urlPath = pathFromKey(key);
3876
+ if (urlPath === null || !matchesPath(urlPath, path, type)) {
3877
+ continue;
3878
+ }
3879
+ deleteEntry(key);
3880
+ deleted = true;
3881
+ purgedPaths.push(urlPath);
3882
+ }
3883
+ return { deleted, purgedPaths: [...new Set(purgedPaths)] };
3884
+ }
3885
+ };
3672
3886
  }
3887
+
3888
+ // src/render/cache.ts
3889
+ var MAX_ISR_CACHE_SIZE = 1000;
3890
+ var MAX_SSG_CACHE_SIZE = 1000;
3891
+ var isrRouteCache = createRouteCache({
3892
+ maxSize: MAX_ISR_CACHE_SIZE,
3893
+ name: "render:isr-html"
3894
+ });
3895
+ var ssgRouteCache = createRouteCache({
3896
+ maxSize: MAX_SSG_CACHE_SIZE,
3897
+ name: "render:ssg-html"
3898
+ });
3899
+ var isrCache = isrRouteCache.store;
3900
+ var ssgCache = ssgRouteCache.store;
3673
3901
  function getSSGCache(key) {
3674
- const entry = ssgCache.get(key);
3675
- if (entry !== undefined) {
3676
- ssgCache.delete(key);
3677
- ssgCache.set(key, entry);
3678
- }
3679
- return entry;
3902
+ return ssgRouteCache.get(key);
3680
3903
  }
3681
3904
  function setSSGCache(key, entry) {
3682
- ssgCache.delete(key);
3683
- ssgCache.set(key, entry);
3684
- evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
3905
+ ssgRouteCache.set(key, entry);
3685
3906
  }
3686
3907
  var _requestInvalidationScope = new AsyncLocalStorage3;
3687
3908
  var _globalPendingInvalidations = new Set;
3909
+ var _cacheInvalidators = new Map;
3910
+ function registerCacheInvalidator(invalidator) {
3911
+ const existing = _cacheInvalidators.get(invalidator.name);
3912
+ if (existing !== undefined && existing !== invalidator) {
3913
+ throw new Error(`Cache invalidator "${invalidator.name}" is already registered with a different instance.`);
3914
+ }
3915
+ if (existing === invalidator) {
3916
+ return () => {
3917
+ if (_cacheInvalidators.get(invalidator.name) === invalidator) {
3918
+ _cacheInvalidators.delete(invalidator.name);
3919
+ }
3920
+ };
3921
+ }
3922
+ _cacheInvalidators.set(invalidator.name, invalidator);
3923
+ return () => {
3924
+ if (_cacheInvalidators.get(invalidator.name) === invalidator) {
3925
+ _cacheInvalidators.delete(invalidator.name);
3926
+ }
3927
+ };
3928
+ }
3929
+ registerCacheInvalidator(isrRouteCache);
3930
+ registerCacheInvalidator(ssgRouteCache);
3688
3931
 
3689
3932
  // src/render/element.tsx
3690
3933
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
@@ -3874,11 +4117,11 @@ var IS_DEV = true;
3874
4117
 
3875
4118
  // src/render/index.ts
3876
4119
  function withSSRRouterContext(element, contextValue) {
3877
- return createElement2(RouterContext.Provider, { value: contextValue }, element);
4120
+ return createElement3(RouterContext.Provider, { value: contextValue }, element);
3878
4121
  }
3879
- async function prepareRender(route, ctx, root, basePath, throwOnFailure) {
4122
+ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult) {
3880
4123
  const loaderStart = Date.now();
3881
- const loaderResult = await runLoaders(route, ctx, root.route);
4124
+ const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx, root.route);
3882
4125
  const loader_ms = Date.now() - loaderStart;
3883
4126
  if (loaderResult.type === "redirect") {
3884
4127
  return loaderResult.response;
@@ -3954,7 +4197,7 @@ function renderForPath(route, params, root, origin, mode, basePath) {
3954
4197
  set: { headers: {} },
3955
4198
  path: resolvedPath
3956
4199
  };
3957
- const prepared = await prepareRender(route, ctx, root, basePath, true);
4200
+ const prepared = await prepareRender(route, ctx, root, basePath, true, undefined);
3958
4201
  if (prepared instanceof Response) {
3959
4202
  return prepared;
3960
4203
  }
@@ -3981,7 +4224,7 @@ function renderForPath(route, params, root, origin, mode, basePath) {
3981
4224
  async function prerenderSSG(route, params, root, origin, basePath) {
3982
4225
  const resolvedPath = resolvePath(route.pattern, params);
3983
4226
  const cached = getSSGCache(resolvedPath);
3984
- if (cached && !IS_DEV) {
4227
+ if (cached) {
3985
4228
  return cached;
3986
4229
  }
3987
4230
  const renderResult = await renderForPath(route, params, root, origin, "ssg", basePath);
@@ -3990,9 +4233,7 @@ async function prerenderSSG(route, params, root, origin, basePath) {
3990
4233
  }
3991
4234
  const result = renderResult;
3992
4235
  const entry = { html: result.html, cachedAt: Date.now(), status: result.status };
3993
- if (!IS_DEV) {
3994
- setSSGCache(resolvedPath, entry);
3995
- }
4236
+ setSSGCache(resolvedPath, entry);
3996
4237
  return entry;
3997
4238
  }
3998
4239
  var pendingRevalidations = new Set;
@@ -4194,6 +4435,57 @@ function getCompileContext() {
4194
4435
  return _compileCtx;
4195
4436
  }
4196
4437
 
4438
+ // src/render/dev-cache.ts
4439
+ var sourceFileToCacheKeys = new Map;
4440
+ function indexEntryDependencies(cacheKey, deps) {
4441
+ for (const dep of deps) {
4442
+ let bucket = sourceFileToCacheKeys.get(dep);
4443
+ if (!bucket) {
4444
+ bucket = new Set;
4445
+ sourceFileToCacheKeys.set(dep, bucket);
4446
+ }
4447
+ bucket.add(cacheKey);
4448
+ }
4449
+ }
4450
+ function unindexEntryDependencies(cacheKey, deps) {
4451
+ for (const dep of deps) {
4452
+ const bucket = sourceFileToCacheKeys.get(dep);
4453
+ if (!bucket) {
4454
+ continue;
4455
+ }
4456
+ bucket.delete(cacheKey);
4457
+ if (bucket.size === 0) {
4458
+ sourceFileToCacheKeys.delete(dep);
4459
+ }
4460
+ }
4461
+ }
4462
+ function createDevLoaderCache(name) {
4463
+ return createRouteCache({
4464
+ name,
4465
+ onDelete: (key, entry) => {
4466
+ unindexEntryDependencies(key, entry.dependencies);
4467
+ },
4468
+ onSet: (key, entry, previous) => {
4469
+ if (previous) {
4470
+ unindexEntryDependencies(key, previous.dependencies);
4471
+ }
4472
+ indexEntryDependencies(key, entry.dependencies);
4473
+ },
4474
+ pathFromKey: urlPathFromCacheKey
4475
+ });
4476
+ }
4477
+ var devISRLoaderCache = createDevLoaderCache("render:dev-isr-loader");
4478
+ var devSSGLoaderCache = createDevLoaderCache("render:dev-ssg-loader");
4479
+ function urlPathFromCacheKey(key) {
4480
+ const sep2 = key.lastIndexOf(":/");
4481
+ if (sep2 === -1) {
4482
+ return null;
4483
+ }
4484
+ return key.slice(sep2 + 1);
4485
+ }
4486
+ registerCacheInvalidator(devISRLoaderCache);
4487
+ registerCacheInvalidator(devSSGLoaderCache);
4488
+
4197
4489
  // src/utils.ts
4198
4490
  function isFurinPage(value) {
4199
4491
  return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
@@ -4267,13 +4559,16 @@ async function scanRootLayout(pagesDir) {
4267
4559
  };
4268
4560
  }
4269
4561
  var CONVENTION_FILE_NAMES = ["not-found", "error"];
4562
+ var SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
4270
4563
  function isConventionFileName(name) {
4271
4564
  return CONVENTION_FILE_NAMES.includes(name);
4272
4565
  }
4566
+ function getSourceModuleCandidates(dir, name) {
4567
+ return SOURCE_MODULE_EXTENSIONS.map((ext) => `${dir}/${name}${ext}`);
4568
+ }
4273
4569
  async function loadConventionComponent(dir, name) {
4274
4570
  const ctx = getCompileContext();
4275
- for (const ext of [".tsx", ".ts", ".jsx", ".js"]) {
4276
- const filePath = `${dir}/${name}${ext}`;
4571
+ for (const filePath of getSourceModuleCandidates(dir, name)) {
4277
4572
  if (existsSync6(filePath) || ctx?.modules[filePath]) {
4278
4573
  const mod = ctx?.modules[filePath] ?? await import(filePath);
4279
4574
  if (mod.default) {
@@ -4288,7 +4583,7 @@ async function scanPageFiles(pagesDir, root) {
4288
4583
  const notFoundCache = new Map;
4289
4584
  const errorCache = new Map;
4290
4585
  for (const absolutePath of await collectPageFilePaths(pagesDir)) {
4291
- if (![".tsx", ".ts", ".jsx", ".js"].some((ext) => absolutePath.endsWith(ext))) {
4586
+ if (!SOURCE_MODULE_EXTENSIONS.some((ext) => absolutePath.endsWith(ext))) {
4292
4587
  continue;
4293
4588
  }
4294
4589
  const relativePath = absolutePath.replace(`${pagesDir}/`, "");