@teyik0/furin 0.2.0-alpha.4 → 0.2.0-alpha.5

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 (67) hide show
  1. package/dist/adapter/bun.d.ts +17 -1
  2. package/dist/adapter/package.d.ts +26 -0
  3. package/dist/build/client.d.ts +1 -1
  4. package/dist/build/compile-entry.d.ts +3 -3
  5. package/dist/build/compile-entry.ts +88 -83
  6. package/dist/build/entry-template.d.ts +35 -9
  7. package/dist/build/entry-template.ts +106 -56
  8. package/dist/build/hydrate.d.ts +1 -1
  9. package/dist/build/index.js +643 -247
  10. package/dist/build/scan-server.d.ts +10 -4
  11. package/dist/build/server-routes-entry.d.ts +3 -3
  12. package/dist/build/server-routes-entry.ts +5 -11
  13. package/dist/build/ssg-cache.d.ts +1 -1
  14. package/dist/build/types.d.ts +36 -1
  15. package/dist/cli/config.d.ts +6 -1
  16. package/dist/cli/index.js +662 -260
  17. package/dist/config.d.ts +11 -2
  18. package/dist/config.js +5 -1
  19. package/dist/furin.d.ts +36 -18
  20. package/dist/furin.js +630 -310
  21. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  22. package/dist/server/cache/dev-loader.d.ts +3 -2
  23. package/dist/server/cache/invalidation.d.ts +19 -0
  24. package/dist/server/cache/isr.d.ts +6 -2
  25. package/dist/server/cache/registry.d.ts +3 -3
  26. package/dist/server/cache/ssg.d.ts +6 -2
  27. package/dist/server/cache/store-view.d.ts +11 -0
  28. package/dist/server/instance.d.ts +86 -0
  29. package/dist/server/internal.d.ts +16 -1
  30. package/dist/server/internal.js +72 -5
  31. package/dist/server/render/template.d.ts +3 -2
  32. package/dist/server/sync/config.d.ts +11 -0
  33. package/dist/server/sync/stream.d.ts +8 -1
  34. package/dist/shared/prefix.d.ts +15 -0
  35. package/package.json +6 -1
  36. package/src/adapter/bun.ts +113 -50
  37. package/src/adapter/package.ts +206 -0
  38. package/src/build/client.ts +9 -3
  39. package/src/build/compile-entry.ts +88 -83
  40. package/src/build/entry-template.ts +106 -56
  41. package/src/build/hydrate.ts +4 -2
  42. package/src/build/index.ts +99 -28
  43. package/src/build/scan-server.ts +23 -7
  44. package/src/build/server-routes-entry.ts +5 -11
  45. package/src/build/ssg-cache.ts +6 -2
  46. package/src/build/types.ts +37 -1
  47. package/src/cli/config.ts +9 -3
  48. package/src/cli/index.ts +21 -3
  49. package/src/config.ts +14 -1
  50. package/src/furin.ts +297 -143
  51. package/src/server/auto-invalidate/registry.ts +23 -1
  52. package/src/server/auto-invalidate/runtime.ts +29 -4
  53. package/src/server/cache/dev-loader.ts +77 -38
  54. package/src/server/cache/invalidation.ts +71 -30
  55. package/src/server/cache/isr.ts +20 -5
  56. package/src/server/cache/registry.ts +17 -20
  57. package/src/server/cache/ssg.ts +19 -4
  58. package/src/server/cache/store-view.ts +30 -0
  59. package/src/server/instance.ts +252 -0
  60. package/src/server/internal.ts +100 -5
  61. package/src/server/render/not-found.ts +9 -3
  62. package/src/server/render/ssr.ts +16 -4
  63. package/src/server/render/template.ts +57 -24
  64. package/src/server/sync/config.ts +32 -1
  65. package/src/server/sync/plugin.ts +4 -5
  66. package/src/server/sync/stream.ts +19 -9
  67. package/src/shared/prefix.ts +38 -0
package/dist/furin.js CHANGED
@@ -2355,6 +2355,120 @@ var init_context_logger = __esm(() => {
2355
2355
  syntheticRenderStorage = new AsyncLocalStorage2;
2356
2356
  });
2357
2357
 
2358
+ // src/server/instance.ts
2359
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2360
+ function createInstance(prefix, pagesDir) {
2361
+ return {
2362
+ prefix,
2363
+ pagesDir,
2364
+ syncStreamPath: undefined,
2365
+ buildId: "",
2366
+ registrationEpoch: 0,
2367
+ state: new Map
2368
+ };
2369
+ }
2370
+ function markTraffic() {
2371
+ _trafficEpoch++;
2372
+ }
2373
+ function defaultInstance() {
2374
+ if (!_defaultInstance) {
2375
+ _defaultInstance = createInstance("", "");
2376
+ }
2377
+ return _defaultInstance;
2378
+ }
2379
+ function defaultInstanceBucket() {
2380
+ return defaultInstance();
2381
+ }
2382
+ function normalizePrefix(prefix) {
2383
+ if (prefix === undefined || prefix === "" || prefix === "/") {
2384
+ return "";
2385
+ }
2386
+ if (!prefix.startsWith("/")) {
2387
+ throw new Error(`[furin] prefix must start with "/" (got "${prefix}").`);
2388
+ }
2389
+ if (prefix.includes("//") || WHITESPACE_RE.test(prefix)) {
2390
+ throw new Error(`[furin] invalid prefix "${prefix}".`);
2391
+ }
2392
+ return prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
2393
+ }
2394
+ function assertPrefixAvailable(prefix, pagesDir) {
2395
+ const existing = _instances.get(prefix);
2396
+ if (existing && existing.pagesDir !== pagesDir && existing.registrationEpoch === _trafficEpoch) {
2397
+ throw new Error(`[furin] prefix "${prefix || "/"}" is already mounted by pagesDir "${existing.pagesDir}" ` + `(attempted to mount "${pagesDir}"). Give each furin() instance a unique prefix.`);
2398
+ }
2399
+ }
2400
+ function registerInstance(instance) {
2401
+ assertPrefixAvailable(instance.prefix, instance.pagesDir);
2402
+ instance.registrationEpoch = _trafficEpoch;
2403
+ _instances.set(instance.prefix, instance);
2404
+ return instance;
2405
+ }
2406
+ function resolveInstanceByPath(pathname) {
2407
+ let best = null;
2408
+ for (const [prefix, instance] of _instances) {
2409
+ if (prefix === "") {
2410
+ best ??= instance;
2411
+ continue;
2412
+ }
2413
+ if ((pathname === prefix || pathname.startsWith(prefix) && pathname.charCodeAt(prefix.length) === 47) && (!best || prefix.length > best.prefix.length || best.prefix === "")) {
2414
+ best = instance;
2415
+ }
2416
+ }
2417
+ if (best) {
2418
+ return best;
2419
+ }
2420
+ return defaultInstance();
2421
+ }
2422
+ function currentInstance() {
2423
+ const scope = _requestScope.getStore();
2424
+ if (scope) {
2425
+ return scope.instance;
2426
+ }
2427
+ if (_instances.size === 1) {
2428
+ const only = _instances.values().next().value;
2429
+ if (only) {
2430
+ return only;
2431
+ }
2432
+ }
2433
+ return defaultInstance();
2434
+ }
2435
+ function allInstances() {
2436
+ if (_instances.size === 0) {
2437
+ return [defaultInstance()];
2438
+ }
2439
+ return [..._instances.values()];
2440
+ }
2441
+ function hasRequestScope() {
2442
+ return _requestScope.getStore() !== undefined;
2443
+ }
2444
+ function requestPendingInvalidations() {
2445
+ return _requestScope.getStore()?.pending;
2446
+ }
2447
+ function runWithInstanceScope(instance, fn) {
2448
+ return _requestScope.run({ instance, pending: new Set }, fn);
2449
+ }
2450
+ function withInstance(instance, fn) {
2451
+ return runWithInstanceScope(instance, fn);
2452
+ }
2453
+ function instanceSlot(init) {
2454
+ const key = Symbol("furin-instance-slot");
2455
+ return (instance) => {
2456
+ const target = instance ?? currentInstance();
2457
+ if (target.state.has(key)) {
2458
+ return target.state.get(key);
2459
+ }
2460
+ const value = init(target);
2461
+ target.state.set(key, value);
2462
+ return value;
2463
+ };
2464
+ }
2465
+ var _requestScope, WHITESPACE_RE, _instances, _defaultInstance = null, _trafficEpoch = 0;
2466
+ var init_instance = __esm(() => {
2467
+ _requestScope = new AsyncLocalStorage3;
2468
+ WHITESPACE_RE = /\s/;
2469
+ _instances = new Map;
2470
+ });
2471
+
2358
2472
  // src/server/auto-invalidate/registry.ts
2359
2473
  class AutoInvalidateRegistry {
2360
2474
  pathToTags = new Map;
@@ -2407,37 +2521,42 @@ class AutoInvalidateRegistry {
2407
2521
  this.tagToPaths.clear();
2408
2522
  }
2409
2523
  }
2410
- var autoInvalidateRegistry;
2524
+ function getAutoInvalidateRegistry(instance) {
2525
+ return instanceAutoInvalidateRegistry(instance);
2526
+ }
2527
+ var instanceAutoInvalidateRegistry, autoInvalidateRegistry;
2411
2528
  var init_registry = __esm(() => {
2412
- autoInvalidateRegistry = new AutoInvalidateRegistry;
2529
+ init_instance();
2530
+ instanceAutoInvalidateRegistry = instanceSlot(() => new AutoInvalidateRegistry);
2531
+ autoInvalidateRegistry = {
2532
+ registerLoaderTags: (urlPath, tags) => instanceAutoInvalidateRegistry().registerLoaderTags(urlPath, tags),
2533
+ pathsForTags: (tags) => instanceAutoInvalidateRegistry().pathsForTags(tags),
2534
+ unregisterPath: (urlPath) => instanceAutoInvalidateRegistry().unregisterPath(urlPath),
2535
+ reset: () => instanceAutoInvalidateRegistry().reset()
2536
+ };
2413
2537
  });
2414
2538
 
2415
2539
  // src/server/cache/registry.ts
2416
- function registerCacheInvalidator(invalidator) {
2417
- const existing = _cacheInvalidators.get(invalidator.name);
2540
+ function registerCacheInvalidator(invalidator, instance) {
2541
+ const invalidators = instanceInvalidators(instance);
2542
+ const existing = invalidators.get(invalidator.name);
2418
2543
  if (existing !== undefined && existing !== invalidator) {
2419
- throw new Error(`Cache invalidator "${invalidator.name}" is already registered with a different instance.`);
2544
+ throw new Error(`Cache invalidator "${invalidator.name}" is already registered for this furin instance with a different invalidator object.`);
2420
2545
  }
2421
- if (existing === invalidator) {
2422
- return () => {
2423
- if (_cacheInvalidators.get(invalidator.name) === invalidator) {
2424
- _cacheInvalidators.delete(invalidator.name);
2425
- }
2426
- };
2427
- }
2428
- _cacheInvalidators.set(invalidator.name, invalidator);
2546
+ invalidators.set(invalidator.name, invalidator);
2429
2547
  return () => {
2430
- if (_cacheInvalidators.get(invalidator.name) === invalidator) {
2431
- _cacheInvalidators.delete(invalidator.name);
2548
+ if (invalidators.get(invalidator.name) === invalidator) {
2549
+ invalidators.delete(invalidator.name);
2432
2550
  }
2433
2551
  };
2434
2552
  }
2435
- function getCacheInvalidators() {
2436
- return _cacheInvalidators.values();
2553
+ function getCacheInvalidators(instance) {
2554
+ return instanceInvalidators(instance).values();
2437
2555
  }
2438
- var _cacheInvalidators;
2556
+ var instanceInvalidators;
2439
2557
  var init_registry2 = __esm(() => {
2440
- _cacheInvalidators = new Map;
2558
+ init_instance();
2559
+ instanceInvalidators = instanceSlot(() => new Map);
2441
2560
  });
2442
2561
 
2443
2562
  // src/server/cache/route-cache.ts
@@ -2532,33 +2651,33 @@ function createRouteCache(options) {
2532
2651
 
2533
2652
  // src/server/cache/dev-loader.ts
2534
2653
  import { statSync } from "fs";
2535
- function indexEntryDependencies(cacheKey, deps) {
2654
+ function indexEntryDependencies(index, cacheKey, deps) {
2536
2655
  for (const dep of deps) {
2537
- let bucket = sourceFileToCacheKeys.get(dep);
2656
+ let bucket = index.get(dep);
2538
2657
  if (!bucket) {
2539
2658
  bucket = new Set;
2540
- sourceFileToCacheKeys.set(dep, bucket);
2659
+ index.set(dep, bucket);
2541
2660
  }
2542
2661
  bucket.add(cacheKey);
2543
2662
  }
2544
2663
  }
2545
- function unindexEntryDependencies(cacheKey, deps) {
2664
+ function unindexEntryDependencies(index, cacheKey, deps) {
2546
2665
  for (const dep of deps) {
2547
- const bucket = sourceFileToCacheKeys.get(dep);
2666
+ const bucket = index.get(dep);
2548
2667
  if (!bucket) {
2549
2668
  continue;
2550
2669
  }
2551
2670
  bucket.delete(cacheKey);
2552
2671
  if (bucket.size === 0) {
2553
- sourceFileToCacheKeys.delete(dep);
2672
+ index.delete(dep);
2554
2673
  }
2555
2674
  }
2556
2675
  }
2557
- function createDevLoaderCache(name) {
2676
+ function createDevLoaderCache(name, index) {
2558
2677
  return createRouteCache({
2559
2678
  name,
2560
2679
  onDelete: (key, entry) => {
2561
- unindexEntryDependencies(key, entry.dependencies);
2680
+ unindexEntryDependencies(index, key, entry.dependencies);
2562
2681
  const urlPath = urlPathFromCacheKey(key);
2563
2682
  if (urlPath) {
2564
2683
  autoInvalidateRegistry.unregisterPath(urlPath);
@@ -2566,27 +2685,24 @@ function createDevLoaderCache(name) {
2566
2685
  },
2567
2686
  onSet: (key, entry, previous) => {
2568
2687
  if (previous) {
2569
- unindexEntryDependencies(key, previous.dependencies);
2688
+ unindexEntryDependencies(index, key, previous.dependencies);
2570
2689
  }
2571
- indexEntryDependencies(key, entry.dependencies);
2690
+ indexEntryDependencies(index, key, entry.dependencies);
2572
2691
  },
2573
2692
  pathFromKey: urlPathFromCacheKey
2574
2693
  });
2575
2694
  }
2576
- function setEntry(handle, key, entry) {
2577
- handle.cache.set(key, entry);
2578
- }
2579
2695
  function getDevISRLoaderCache(key) {
2580
- return devISRLoaderCache.get(key);
2696
+ return instanceDevLoaderState().isr.cache.get(key);
2581
2697
  }
2582
2698
  function setDevISRLoaderCache(key, entry) {
2583
- setEntry(isrHandle, key, entry);
2699
+ instanceDevLoaderState().isr.cache.set(key, entry);
2584
2700
  }
2585
2701
  function getDevSSGLoaderCache(key) {
2586
- return devSSGLoaderCache.get(key);
2702
+ return instanceDevLoaderState().ssg.cache.get(key);
2587
2703
  }
2588
2704
  function setDevSSGLoaderCache(key, entry) {
2589
- setEntry(ssgHandle, key, entry);
2705
+ instanceDevLoaderState().ssg.cache.set(key, entry);
2590
2706
  }
2591
2707
  function urlPathFromCacheKey(key) {
2592
2708
  const sep = key.lastIndexOf(":/");
@@ -2596,7 +2712,8 @@ function urlPathFromCacheKey(key) {
2596
2712
  return key.slice(sep + 1);
2597
2713
  }
2598
2714
  function invalidateDevLoaderCacheBySource(filePath) {
2599
- const keys = sourceFileToCacheKeys.get(filePath);
2715
+ const state = instanceDevLoaderState();
2716
+ const keys = state.sourceFileToCacheKeys.get(filePath);
2600
2717
  if (!keys || keys.size === 0) {
2601
2718
  return { cleared: [], isr: 0, ssg: 0 };
2602
2719
  }
@@ -2605,16 +2722,16 @@ function invalidateDevLoaderCacheBySource(filePath) {
2605
2722
  let ssg = 0;
2606
2723
  const snapshot = [...keys];
2607
2724
  for (const key of snapshot) {
2608
- const isrEntry = devISRLoaderCache.get(key);
2725
+ const isrEntry = state.isr.cache.get(key);
2609
2726
  if (isrEntry) {
2610
- devISRLoaderCache.delete(key);
2727
+ state.isr.cache.delete(key);
2611
2728
  cleared.push(key);
2612
2729
  isr++;
2613
2730
  continue;
2614
2731
  }
2615
- const ssgEntry = devSSGLoaderCache.get(key);
2732
+ const ssgEntry = state.ssg.cache.get(key);
2616
2733
  if (ssgEntry) {
2617
- devSSGLoaderCache.delete(key);
2734
+ state.ssg.cache.delete(key);
2618
2735
  cleared.push(key);
2619
2736
  ssg++;
2620
2737
  }
@@ -2642,19 +2759,28 @@ function isDevLoaderCacheValid(entry) {
2642
2759
  return true;
2643
2760
  }
2644
2761
  function getAllDevISRLoaderEntries() {
2645
- return [...devISRLoaderCache.entries()];
2762
+ return [...instanceDevLoaderState().isr.cache.entries()];
2646
2763
  }
2647
2764
  function getAllDevSSGLoaderEntries() {
2648
- return [...devSSGLoaderCache.entries()];
2765
+ return [...instanceDevLoaderState().ssg.cache.entries()];
2649
2766
  }
2650
- var sourceFileToCacheKeys, devISRLoaderCache, devSSGLoaderCache, isrHandle, ssgHandle;
2767
+ var instanceDevLoaderState;
2651
2768
  var init_dev_loader = __esm(() => {
2652
2769
  init_registry();
2653
- sourceFileToCacheKeys = new Map;
2654
- devISRLoaderCache = createDevLoaderCache("render:dev-isr-loader");
2655
- devSSGLoaderCache = createDevLoaderCache("render:dev-ssg-loader");
2656
- isrHandle = { cache: devISRLoaderCache, kind: "isr" };
2657
- ssgHandle = { cache: devSSGLoaderCache, kind: "ssg" };
2770
+ init_instance();
2771
+ init_registry2();
2772
+ instanceDevLoaderState = instanceSlot((instance) => {
2773
+ const sourceFileToCacheKeys = new Map;
2774
+ const isrCache = createDevLoaderCache("render:dev-isr-loader", sourceFileToCacheKeys);
2775
+ const ssgCache = createDevLoaderCache("render:dev-ssg-loader", sourceFileToCacheKeys);
2776
+ registerCacheInvalidator(isrCache, instance);
2777
+ registerCacheInvalidator(ssgCache, instance);
2778
+ return {
2779
+ isr: { cache: isrCache, kind: "isr" },
2780
+ sourceFileToCacheKeys,
2781
+ ssg: { cache: ssgCache, kind: "ssg" }
2782
+ };
2783
+ });
2658
2784
  });
2659
2785
 
2660
2786
  // src/server/cache/isr-ssg.ts
@@ -2672,44 +2798,131 @@ var init_isr_ssg = __esm(() => {
2672
2798
  init_registry();
2673
2799
  });
2674
2800
 
2801
+ // src/server/cache/store-view.ts
2802
+ function createStoreView(resolve) {
2803
+ return {
2804
+ clear: () => resolve().clear(),
2805
+ delete: (key) => resolve().delete(key),
2806
+ entries: () => resolve().entries(),
2807
+ get: (key) => resolve().get(key),
2808
+ has: (key) => resolve().has(key),
2809
+ keys: () => resolve().keys(),
2810
+ set: (key, entry) => {
2811
+ resolve().set(key, entry);
2812
+ },
2813
+ get size() {
2814
+ return resolve().size;
2815
+ }
2816
+ };
2817
+ }
2818
+
2675
2819
  // src/server/cache/isr.ts
2676
2820
  function getISRCache(key) {
2677
- return isrRouteCache.get(key);
2821
+ return instanceIsrCache().get(key);
2678
2822
  }
2679
2823
  function deleteISRCache(key) {
2680
- return isrRouteCache.delete(key);
2824
+ return instanceIsrCache().delete(key);
2681
2825
  }
2682
2826
  function setISRCache(key, entry) {
2683
- isrRouteCache.set(key, entry);
2827
+ instanceIsrCache().set(key, entry);
2684
2828
  }
2685
- var isrRouteCache, isrCache;
2829
+ var instanceIsrCache, isrCache;
2686
2830
  var init_isr = __esm(() => {
2831
+ init_instance();
2687
2832
  init_isr_ssg();
2688
- isrRouteCache = createHtmlRouteCache("isr");
2689
- isrCache = isrRouteCache.store;
2833
+ init_registry2();
2834
+ instanceIsrCache = instanceSlot((instance) => {
2835
+ const cache = createHtmlRouteCache("isr");
2836
+ registerCacheInvalidator(cache, instance);
2837
+ return cache;
2838
+ });
2839
+ isrCache = createStoreView(() => instanceIsrCache().store);
2690
2840
  });
2691
2841
 
2692
2842
  // src/server/cache/ssg.ts
2693
2843
  function getSSGCache(key) {
2694
- return ssgRouteCache.get(key);
2844
+ return instanceSsgCache().get(key);
2695
2845
  }
2696
2846
  function setSSGCache(key, entry) {
2697
- ssgRouteCache.set(key, entry);
2847
+ instanceSsgCache().set(key, entry);
2698
2848
  autoInvalidateRegistry.registerLoaderTags(key, entry.tags);
2699
2849
  }
2700
- var ssgRouteCache, ssgCache;
2850
+ var instanceSsgCache, ssgCache;
2701
2851
  var init_ssg = __esm(() => {
2702
2852
  init_registry();
2853
+ init_instance();
2703
2854
  init_isr_ssg();
2704
- ssgRouteCache = createHtmlRouteCache("ssg");
2705
- ssgCache = ssgRouteCache.store;
2855
+ init_registry2();
2856
+ instanceSsgCache = instanceSlot((instance) => {
2857
+ const cache = createHtmlRouteCache("ssg");
2858
+ registerCacheInvalidator(cache, instance);
2859
+ return cache;
2860
+ });
2861
+ ssgCache = createStoreView(() => instanceSsgCache().store);
2706
2862
  });
2707
2863
 
2708
2864
  // src/server/internal.ts
2709
- function getCompileContext() {
2710
- return _compileCtx;
2865
+ function normalizeContextKey(path) {
2866
+ return path.replaceAll("\\", "/");
2867
+ }
2868
+ function pagesDirOf(ctx) {
2869
+ const rootPath = normalizeContextKey(ctx.rootPath);
2870
+ const lastSlash = rootPath.lastIndexOf("/");
2871
+ return lastSlash === -1 ? rootPath : rootPath.slice(0, lastSlash);
2872
+ }
2873
+ function contextKey(pagesDir, prefix) {
2874
+ return `${pagesDir}\x00${prefix}`;
2875
+ }
2876
+ function getCompileContext(pagesDir, prefix) {
2877
+ if (pagesDir !== undefined) {
2878
+ const dir = normalizeContextKey(pagesDir);
2879
+ if (prefix !== undefined) {
2880
+ const exact = _compileContexts.get(contextKey(dir, prefix));
2881
+ if (exact) {
2882
+ return exact;
2883
+ }
2884
+ }
2885
+ const dirMatch = soleContextForPagesDir(dir);
2886
+ if (dirMatch) {
2887
+ return dirMatch;
2888
+ }
2889
+ }
2890
+ if (prefix !== undefined) {
2891
+ const prefixMatch = contextForPrefix(prefix);
2892
+ if (prefixMatch) {
2893
+ return prefixMatch;
2894
+ }
2895
+ }
2896
+ if (_compileContexts.size === 1) {
2897
+ return _compileContexts.values().next().value ?? null;
2898
+ }
2899
+ return null;
2900
+ }
2901
+ function soleContextForPagesDir(dir) {
2902
+ let match = null;
2903
+ for (const ctx of _compileContexts.values()) {
2904
+ if (pagesDirOf(ctx) !== dir) {
2905
+ continue;
2906
+ }
2907
+ if (match) {
2908
+ return null;
2909
+ }
2910
+ match = ctx;
2911
+ }
2912
+ return match;
2913
+ }
2914
+ function contextForPrefix(prefix) {
2915
+ for (const ctx of _compileContexts.values()) {
2916
+ if ((ctx.prefix ?? "") === prefix) {
2917
+ return ctx;
2918
+ }
2919
+ }
2920
+ return null;
2711
2921
  }
2712
- var _compileCtx = null;
2922
+ var _compileContexts;
2923
+ var init_internal = __esm(() => {
2924
+ _compileContexts = new Map;
2925
+ });
2713
2926
 
2714
2927
  // src/shared/digest.ts
2715
2928
  function computeErrorDigest(err) {
@@ -2984,6 +3197,12 @@ function normalizeHref(href) {
2984
3197
  }
2985
3198
  return pathname + url.search + url.hash;
2986
3199
  }
3200
+ function toLogical(physicalPathname, basePath) {
3201
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
3202
+ return physicalPathname.slice(basePath.length) || "/";
3203
+ }
3204
+ return physicalPathname;
3205
+ }
2987
3206
  var init_link_utils = () => {};
2988
3207
 
2989
3208
  // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
@@ -5160,13 +5379,26 @@ function resolveSyncStreamPath(sync) {
5160
5379
  return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
5161
5380
  }
5162
5381
  function getSyncStreamPath() {
5163
- return requestSyncStreamPath.getStore();
5382
+ const override = requestSyncStreamPath.getStore();
5383
+ if (override !== undefined) {
5384
+ return override;
5385
+ }
5386
+ return currentInstance().syncStreamPath;
5164
5387
  }
5165
- function runWithSyncStreamPath(path, fn) {
5166
- return requestSyncStreamPath.run(path, fn);
5388
+ function syncPublishChannels() {
5389
+ const override = requestSyncStreamPath.getStore();
5390
+ if (override !== undefined) {
5391
+ return [override];
5392
+ }
5393
+ const channels = allInstances().filter((instance) => instance.syncStreamPath !== undefined).map((instance) => `${instance.prefix}${instance.syncStreamPath}`);
5394
+ if (channels.length > 0) {
5395
+ return channels;
5396
+ }
5397
+ return [SYNC_STREAM_DEFAULT_PATH];
5167
5398
  }
5168
5399
  var SYNC_STREAM_DEFAULT_PATH = "/_furin/sync", requestSyncStreamPath;
5169
5400
  var init_config = __esm(() => {
5401
+ init_instance();
5170
5402
  requestSyncStreamPath = new AsyncLocalStorage4;
5171
5403
  });
5172
5404
 
@@ -5596,41 +5828,57 @@ var init_loaders = __esm(() => {
5596
5828
  // src/server/render/template.ts
5597
5829
  import { readFileSync } from "fs";
5598
5830
  async function getDevTemplate(origin) {
5599
- if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
5600
- return _devTemplateCache.html;
5831
+ const instance = currentInstance();
5832
+ const state = instanceTemplateState(instance);
5833
+ if (state.devCache && Date.now() - state.devCache.ts < DEV_TEMPLATE_TTL_MS) {
5834
+ return state.devCache.html;
5601
5835
  }
5602
- const r = await fetch(`${origin}/_bun_hmr_entry`);
5836
+ const entryPath = `${instance.prefix}/_bun_hmr_entry`;
5837
+ const r = await fetch(`${origin}${entryPath}`);
5603
5838
  if (!r.ok) {
5604
- throw new Error(`/_bun_hmr_entry returned ${r.status}`);
5839
+ throw new Error(`${entryPath} returned ${r.status}`);
5605
5840
  }
5606
5841
  const html = await r.text();
5607
- _devTemplateCache = { html, ts: Date.now() };
5842
+ state.devCache = { html, ts: Date.now() };
5608
5843
  return html;
5609
5844
  }
5610
- function setProductionTemplatePath(path) {
5611
- _prodTemplatePath = path;
5612
- _prodTemplateContent = null;
5845
+ function setProductionTemplatePath(path, instance) {
5846
+ const state = instanceTemplateState(instance);
5847
+ state.prodPath = path;
5848
+ state.prodContent = null;
5613
5849
  }
5614
- function setProductionTemplateContent(content) {
5615
- _prodTemplatePath = null;
5616
- _prodTemplateContent = content;
5850
+ function setProductionTemplateContent(content, instance) {
5851
+ const state = instanceTemplateState(instance);
5852
+ state.prodPath = null;
5853
+ state.prodContent = content;
5617
5854
  }
5618
5855
  function getProductionTemplate() {
5619
- if (_prodTemplateContent !== null) {
5620
- return _prodTemplateContent;
5856
+ const own = readTemplate(instanceTemplateState());
5857
+ if (own !== null) {
5858
+ return own;
5859
+ }
5860
+ const fallback = instanceTemplateState(defaultInstanceBucket());
5861
+ return readTemplate(fallback);
5862
+ }
5863
+ function readTemplate(state) {
5864
+ if (state.prodContent !== null) {
5865
+ return state.prodContent;
5621
5866
  }
5622
- if (!_prodTemplatePath) {
5867
+ if (!state.prodPath) {
5623
5868
  return null;
5624
5869
  }
5625
5870
  try {
5626
- _prodTemplateContent = readFileSync(_prodTemplatePath, "utf8");
5627
- return _prodTemplateContent;
5871
+ state.prodContent = readFileSync(state.prodPath, "utf8");
5872
+ return state.prodContent;
5628
5873
  } catch {
5629
5874
  return null;
5630
5875
  }
5631
5876
  }
5632
- var _prodTemplatePath = null, _prodTemplateContent = null, _devTemplateCache = null, DEV_TEMPLATE_TTL_MS = 1000;
5633
- var init_template = () => {};
5877
+ var instanceTemplateState, DEV_TEMPLATE_TTL_MS = 1000;
5878
+ var init_template = __esm(() => {
5879
+ init_instance();
5880
+ instanceTemplateState = instanceSlot(() => ({ devCache: null, prodContent: null, prodPath: null }));
5881
+ });
5634
5882
 
5635
5883
  // src/server/render/ssr.ts
5636
5884
  import { createElement as createElement3 } from "react";
@@ -5657,10 +5905,10 @@ function assertDeferredModeAllowed(route, deferredPromises) {
5657
5905
  throw new Error(`[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` + "defer() streams data progressively and is only supported in SSR. " + "Return the data directly (await it inside the loader) or switch the route to SSR mode.");
5658
5906
  }
5659
5907
  }
5660
- function currentHrefFromContext(ctx) {
5908
+ function currentHrefFromContext(ctx, basePath) {
5661
5909
  const pathUrl = new URL(ctx.path, "http://furin.local");
5662
5910
  const requestUrl = new URL(ctx.request.url);
5663
- return normalizeHref(pathUrl.pathname) + (pathUrl.search || requestUrl.search);
5911
+ return normalizeHref(toLogical(pathUrl.pathname, basePath)) + (pathUrl.search || requestUrl.search);
5664
5912
  }
5665
5913
  function buildSuccessRender(route, root, componentProps, throwOnFailure) {
5666
5914
  try {
@@ -5722,9 +5970,10 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
5722
5970
  errorDigest = success.errorDigest;
5723
5971
  status = success.status;
5724
5972
  }
5973
+ const resolvedBasePath = basePath ?? currentInstance().prefix;
5725
5974
  const ssrContext = {
5726
- basePath: basePath ?? "",
5727
- currentHref: currentHrefFromContext(ctx),
5975
+ basePath: resolvedBasePath,
5976
+ currentHref: currentHrefFromContext(ctx, resolvedBasePath),
5728
5977
  search: ctx.query ?? {},
5729
5978
  searchRoutes: searchRoutes ?? [],
5730
5979
  navigate: (_href, _opts) => Promise.resolve(),
@@ -5897,6 +6146,7 @@ var init_ssr = __esm(() => {
5897
6146
  init_search_store();
5898
6147
  init_registry();
5899
6148
  init_context_logger();
6149
+ init_instance();
5900
6150
  init_assemble();
5901
6151
  init_element();
5902
6152
  init_loaders();
@@ -6136,9 +6386,10 @@ async function renderRootNotFound(root, request) {
6136
6386
  template = generateIndexHtml();
6137
6387
  }
6138
6388
  const notFoundError = new FurinNotFoundError(undefined);
6389
+ const basePath = currentInstance().prefix;
6139
6390
  const notFoundContext = {
6140
- basePath: "",
6141
- currentHref: request ? normalizeHref(new URL(request.url).pathname) : "/",
6391
+ basePath,
6392
+ currentHref: request ? normalizeHref(toLogical(new URL(request.url).pathname, basePath)) : "/",
6142
6393
  search: {},
6143
6394
  searchRoutes: [],
6144
6395
  navigate: (_href, _opts) => Promise.resolve(),
@@ -6182,6 +6433,7 @@ var init_not_found2 = __esm(() => {
6182
6433
  init_router();
6183
6434
  init_not_found();
6184
6435
  init_context_logger();
6436
+ init_instance();
6185
6437
  init_assemble();
6186
6438
  init_element();
6187
6439
  init_shell();
@@ -6778,6 +7030,7 @@ async function collectPageFilePaths(dir) {
6778
7030
  }
6779
7031
  var CONVENTION_FILE_NAMES, SOURCE_MODULE_EXTENSIONS, DIR_SCAN_CONCURRENCY = 8;
6780
7032
  var init_discovery = __esm(() => {
7033
+ init_internal();
6781
7034
  init_patterns();
6782
7035
  CONVENTION_FILE_NAMES = ["not-found", "error"];
6783
7036
  SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
@@ -6950,6 +7203,7 @@ function computeRouteDependencies(pagePath, rootPath) {
6950
7203
  var init_hmr = __esm(() => {
6951
7204
  init_registry();
6952
7205
  init_dev_loader();
7206
+ init_internal();
6953
7207
  init_assemble();
6954
7208
  init_render();
6955
7209
  init_discovery();
@@ -7971,7 +8225,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
7971
8225
  });
7972
8226
  `;
7973
8227
  }
7974
- function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging }, projectRoot) {
8228
+ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot) {
7975
8229
  if (!existsSync4(outDir)) {
7976
8230
  mkdirSync(outDir, { recursive: true });
7977
8231
  }
@@ -7987,7 +8241,9 @@ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging },
7987
8241
  if (indexHtml !== existingIndex) {
7988
8242
  writeFileSync2(indexPath, indexHtml);
7989
8243
  }
7990
- writeRouteTypes(routes, projectRoot);
8244
+ if (!skipRouteTypes) {
8245
+ writeRouteTypes(routes, projectRoot);
8246
+ }
7991
8247
  console.log("[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)");
7992
8248
  }
7993
8249
  var init_hydrate = __esm(() => {
@@ -8008,29 +8264,11 @@ import { Elysia as Elysia7, file } from "elysia";
8008
8264
 
8009
8265
  // src/server/cache/invalidation.ts
8010
8266
  init_context_logger();
8011
- init_dev_loader();
8012
- init_isr();
8267
+ init_instance();
8013
8268
  init_registry2();
8014
- init_ssg();
8015
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
8016
- registerCacheInvalidator(isrRouteCache);
8017
- registerCacheInvalidator(ssgRouteCache);
8018
- registerCacheInvalidator(devISRLoaderCache);
8019
- registerCacheInvalidator(devSSGLoaderCache);
8020
- var _buildId = "";
8021
- function setBuildId(id) {
8022
- _buildId = id;
8023
- }
8024
- function getBuildId() {
8025
- return _buildId;
8026
- }
8027
- var _requestInvalidationScope = new AsyncLocalStorage3;
8028
8269
  var _globalPendingInvalidations = new Set;
8029
8270
  function _activeInvalidationSet() {
8030
- return _requestInvalidationScope.getStore() ?? _globalPendingInvalidations;
8031
- }
8032
- function _runWithRequestInvalidationScope(fn) {
8033
- return _requestInvalidationScope.run(new Set, fn);
8271
+ return requestPendingInvalidations() ?? _globalPendingInvalidations;
8034
8272
  }
8035
8273
  function consumePendingInvalidations() {
8036
8274
  const set = _activeInvalidationSet();
@@ -8062,23 +8300,37 @@ function callCachePurger(paths) {
8062
8300
  });
8063
8301
  }
8064
8302
  function revalidatePath(path, type) {
8065
- _activeInvalidationSet().add(type === "layout" ? `${path}:layout` : path);
8066
8303
  let deleted = false;
8067
8304
  const purgedPaths = [];
8068
- for (const invalidator of getCacheInvalidators()) {
8069
- const result = invalidator.invalidatePath(path, type);
8305
+ for (const instance of allInstances()) {
8306
+ const result = revalidatePathForInstance(instance, path, type);
8070
8307
  deleted = result.deleted || deleted;
8071
8308
  purgedPaths.push(...result.purgedPaths);
8072
8309
  }
8073
8310
  callCachePurger(dedupePaths([...purgedPaths, path]));
8074
8311
  return deleted;
8075
8312
  }
8313
+ function revalidatePathForInstance(instance, path, type) {
8314
+ _activeInvalidationSet().add(type === "layout" ? `${path}:layout` : path);
8315
+ let deleted = false;
8316
+ const purgedPaths = [];
8317
+ withInstance(instance, () => {
8318
+ for (const invalidator of getCacheInvalidators(instance)) {
8319
+ const result = invalidator.invalidatePath(path, type);
8320
+ deleted = result.deleted || deleted;
8321
+ purgedPaths.push(...result.purgedPaths);
8322
+ }
8323
+ });
8324
+ return { deleted, purgedPaths };
8325
+ }
8076
8326
  function dedupePaths(paths) {
8077
8327
  return [...new Set(paths)];
8078
8328
  }
8079
8329
 
8080
8330
  // src/furin.ts
8081
8331
  init_ssg();
8332
+ init_instance();
8333
+ init_internal();
8082
8334
  init_render();
8083
8335
  init_template();
8084
8336
  init_router2();
@@ -8087,9 +8339,10 @@ init_router2();
8087
8339
  init_config();
8088
8340
 
8089
8341
  // src/server/sync/plugin.ts
8090
- import { Elysia as Elysia3 } from "elysia";
8342
+ import { Elysia as Elysia4 } from "elysia";
8091
8343
 
8092
8344
  // src/server/auto-invalidate/runtime.ts
8345
+ init_instance();
8093
8346
  init_registry();
8094
8347
  function toRules(input) {
8095
8348
  return Array.isArray(input) ? input : [input];
@@ -8182,9 +8435,18 @@ function appendPendingInvalidationHeader(set) {
8182
8435
  function revalidateTag(tags) {
8183
8436
  const tagList = typeof tags === "string" ? [tags] : [...tags];
8184
8437
  let deleted = false;
8185
- for (const path of autoInvalidateRegistry.pathsForTags(tagList)) {
8186
- deleted = revalidatePath(path, "page") || deleted;
8438
+ const purgedPaths = new Set;
8439
+ for (const instance of allInstances()) {
8440
+ for (const path of getAutoInvalidateRegistry(instance).pathsForTags(tagList)) {
8441
+ const result = revalidatePathForInstance(instance, path, "page");
8442
+ deleted = result.deleted || deleted;
8443
+ purgedPaths.add(`${instance.prefix}${path}`);
8444
+ for (const purged of result.purgedPaths) {
8445
+ purgedPaths.add(`${instance.prefix}${purged}`);
8446
+ }
8447
+ }
8187
8448
  }
8449
+ callCachePurger([...purgedPaths]);
8188
8450
  return deleted;
8189
8451
  }
8190
8452
  function runInvalidationRules(input) {
@@ -8200,9 +8462,6 @@ function runInvalidationRules(input) {
8200
8462
  return deleted;
8201
8463
  }
8202
8464
 
8203
- // src/server/sync/plugin.ts
8204
- init_config();
8205
-
8206
8465
  // src/server/sync/fingerprint.ts
8207
8466
  function compareCodePoints(left, right) {
8208
8467
  if (left === right) {
@@ -8443,6 +8702,130 @@ function replayResponse(stored) {
8443
8702
  });
8444
8703
  }
8445
8704
 
8705
+ // src/server/sync/stream.ts
8706
+ init_config();
8707
+ import { Elysia as Elysia3 } from "elysia";
8708
+ var DEFAULT_CHANGE_LIMIT = 100;
8709
+ var MAX_CHANGE_LIMIT = 500;
8710
+ var CURSOR_PATTERN = /^\d+$/;
8711
+ var defaultStreamPath = "/_furin/sync";
8712
+ var encoder = new TextEncoder;
8713
+ var streams = new Map;
8714
+ function encodeSseChange(change) {
8715
+ return encoder.encode(`id: ${change.cursor}
8716
+ event: furin.sync
8717
+ retry: 3000
8718
+ data: ${JSON.stringify({ cursor: change.cursor })}
8719
+
8720
+ `);
8721
+ }
8722
+ function getStreamState(path) {
8723
+ const existing = streams.get(path);
8724
+ if (existing) {
8725
+ return existing;
8726
+ }
8727
+ const state = {
8728
+ clients: new Set,
8729
+ heartbeats: new Set,
8730
+ unsubscribe: undefined
8731
+ };
8732
+ state.unsubscribe = memorySyncAdapter.subscribe(path, (change) => {
8733
+ const chunk = encodeSseChange(change);
8734
+ for (const client of [...state.clients]) {
8735
+ try {
8736
+ client.enqueue(chunk);
8737
+ } catch {
8738
+ state.clients.delete(client);
8739
+ }
8740
+ }
8741
+ });
8742
+ streams.set(path, state);
8743
+ return state;
8744
+ }
8745
+ function parseChangeQuery(request) {
8746
+ const url = new URL(request.url);
8747
+ const after = url.searchParams.get("after") ?? undefined;
8748
+ if (after !== undefined && !CURSOR_PATTERN.test(after)) {
8749
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_CURSOR" }, { status: 400 }) };
8750
+ }
8751
+ const limitValue = url.searchParams.get("limit");
8752
+ if (limitValue !== null && !CURSOR_PATTERN.test(limitValue)) {
8753
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
8754
+ }
8755
+ const limit = limitValue === null ? DEFAULT_CHANGE_LIMIT : Number.parseInt(limitValue, 10);
8756
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_CHANGE_LIMIT) {
8757
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
8758
+ }
8759
+ return { after, limit };
8760
+ }
8761
+ function publishSyncInvalidation(invalidations) {
8762
+ if (invalidations.length === 0) {
8763
+ return;
8764
+ }
8765
+ for (const channel of syncPublishChannels()) {
8766
+ memorySyncAdapter.appendChanges({
8767
+ invalidations,
8768
+ path: channel
8769
+ });
8770
+ }
8771
+ }
8772
+ function createSyncStreamPlugin(path, channel) {
8773
+ const streamPath = path ?? defaultStreamPath;
8774
+ const channelKey = channel ?? streamPath;
8775
+ return new Elysia3({ name: `furin-sync-stream-${channelKey}` }).get(`${streamPath}/changes`, ({ request, set }) => {
8776
+ set.headers["cache-control"] = "no-store";
8777
+ const query = parseChangeQuery(request);
8778
+ if ("error" in query) {
8779
+ return query.error;
8780
+ }
8781
+ return memorySyncAdapter.readChanges({ ...query, path: channelKey });
8782
+ }).get(streamPath, () => {
8783
+ const state = getStreamState(channelKey);
8784
+ let controllerRef;
8785
+ let heartbeat;
8786
+ const stream = new ReadableStream({
8787
+ start(controller) {
8788
+ controllerRef = controller;
8789
+ state.clients.add(controller);
8790
+ controller.enqueue(encoder.encode(`: connected
8791
+ retry: 3000
8792
+
8793
+ `));
8794
+ heartbeat = setInterval(() => {
8795
+ try {
8796
+ controller.enqueue(encoder.encode(`: heartbeat
8797
+
8798
+ `));
8799
+ } catch {
8800
+ state.clients.delete(controller);
8801
+ if (heartbeat) {
8802
+ clearInterval(heartbeat);
8803
+ state.heartbeats.delete(heartbeat);
8804
+ }
8805
+ }
8806
+ }, 15000);
8807
+ state.heartbeats.add(heartbeat);
8808
+ },
8809
+ cancel() {
8810
+ if (controllerRef) {
8811
+ state.clients.delete(controllerRef);
8812
+ }
8813
+ if (heartbeat) {
8814
+ clearInterval(heartbeat);
8815
+ state.heartbeats.delete(heartbeat);
8816
+ }
8817
+ }
8818
+ });
8819
+ return new Response(stream, {
8820
+ headers: {
8821
+ "cache-control": "no-cache, no-transform",
8822
+ connection: "keep-alive",
8823
+ "content-type": "text/event-stream; charset=utf-8"
8824
+ }
8825
+ });
8826
+ });
8827
+ }
8828
+
8446
8829
  // src/server/sync/plugin.ts
8447
8830
  var routeMetadata = new WeakMap;
8448
8831
  var activeMutations = new WeakMap;
@@ -8529,7 +8912,7 @@ async function abortMutation(request) {
8529
8912
  await memorySyncAdapter.abortMutation(active);
8530
8913
  }
8531
8914
  function furinSync() {
8532
- return new Elysia3({ name: "furin-sync" }).macro({
8915
+ return new Elysia4({ name: "furin-sync" }).macro({
8533
8916
  sync(input) {
8534
8917
  return {
8535
8918
  transform({ request }) {
@@ -8558,123 +8941,18 @@ function furinSync() {
8558
8941
  await memorySyncAdapter.commitMutation({ ...active, response });
8559
8942
  activeMutations.delete(ctx.request);
8560
8943
  if (pending.length > 0) {
8561
- await memorySyncAdapter.appendChanges({
8562
- invalidations: pending,
8563
- path: getSyncStreamPath() ?? "/_furin/sync"
8564
- });
8944
+ publishSyncInvalidation(pending);
8565
8945
  }
8566
8946
  }).onError({ as: "global" }, ({ request }) => abortMutation(request));
8567
8947
  }
8568
- // src/server/sync/stream.ts
8569
- import { Elysia as Elysia4 } from "elysia";
8570
- var DEFAULT_CHANGE_LIMIT = 100;
8571
- var MAX_CHANGE_LIMIT = 500;
8572
- var CURSOR_PATTERN = /^\d+$/;
8573
- var defaultStreamPath = "/_furin/sync";
8574
- var encoder = new TextEncoder;
8575
- var streams = new Map;
8576
- function encodeSseChange(change) {
8577
- return encoder.encode(`id: ${change.cursor}
8578
- event: furin.sync
8579
- retry: 3000
8580
- data: ${JSON.stringify({ cursor: change.cursor })}
8581
-
8582
- `);
8583
- }
8584
- function getStreamState(path) {
8585
- const existing = streams.get(path);
8586
- if (existing) {
8587
- return existing;
8588
- }
8589
- const state = {
8590
- clients: new Set,
8591
- heartbeats: new Set,
8592
- unsubscribe: undefined
8593
- };
8594
- state.unsubscribe = memorySyncAdapter.subscribe(path, (change) => {
8595
- const chunk = encodeSseChange(change);
8596
- for (const client of [...state.clients]) {
8597
- try {
8598
- client.enqueue(chunk);
8599
- } catch {
8600
- state.clients.delete(client);
8601
- }
8602
- }
8603
- });
8604
- streams.set(path, state);
8605
- return state;
8948
+ // src/shared/prefix.ts
8949
+ function clientDirNameForPrefix(prefix) {
8950
+ return prefix === "" ? "client" : `client-${prefixSlug(prefix)}`;
8606
8951
  }
8607
- function parseChangeQuery(request) {
8608
- const url = new URL(request.url);
8609
- const after = url.searchParams.get("after") ?? undefined;
8610
- if (after !== undefined && !CURSOR_PATTERN.test(after)) {
8611
- return { error: Response.json({ code: "FURIN_INVALID_SYNC_CURSOR" }, { status: 400 }) };
8612
- }
8613
- const limitValue = url.searchParams.get("limit");
8614
- if (limitValue !== null && !CURSOR_PATTERN.test(limitValue)) {
8615
- return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
8616
- }
8617
- const limit = limitValue === null ? DEFAULT_CHANGE_LIMIT : Number.parseInt(limitValue, 10);
8618
- if (!Number.isInteger(limit) || limit < 1 || limit > MAX_CHANGE_LIMIT) {
8619
- return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
8620
- }
8621
- return { after, limit };
8952
+ function prefixSlug(prefix) {
8953
+ return prefix.slice(1).replaceAll("/", "-");
8622
8954
  }
8623
- function createSyncStreamPlugin(path) {
8624
- const streamPath = path ?? defaultStreamPath;
8625
- return new Elysia4({ name: `furin-sync-stream-${streamPath}` }).get(`${streamPath}/changes`, ({ request, set }) => {
8626
- set.headers["cache-control"] = "no-store";
8627
- const query = parseChangeQuery(request);
8628
- if ("error" in query) {
8629
- return query.error;
8630
- }
8631
- return memorySyncAdapter.readChanges({ ...query, path: streamPath });
8632
- }).get(streamPath, () => {
8633
- const state = getStreamState(streamPath);
8634
- let controllerRef;
8635
- let heartbeat;
8636
- const stream = new ReadableStream({
8637
- start(controller) {
8638
- controllerRef = controller;
8639
- state.clients.add(controller);
8640
- controller.enqueue(encoder.encode(`: connected
8641
- retry: 3000
8642
8955
 
8643
- `));
8644
- heartbeat = setInterval(() => {
8645
- try {
8646
- controller.enqueue(encoder.encode(`: heartbeat
8647
-
8648
- `));
8649
- } catch {
8650
- state.clients.delete(controller);
8651
- if (heartbeat) {
8652
- clearInterval(heartbeat);
8653
- state.heartbeats.delete(heartbeat);
8654
- }
8655
- }
8656
- }, 15000);
8657
- state.heartbeats.add(heartbeat);
8658
- },
8659
- cancel() {
8660
- if (controllerRef) {
8661
- state.clients.delete(controllerRef);
8662
- }
8663
- if (heartbeat) {
8664
- clearInterval(heartbeat);
8665
- state.heartbeats.delete(heartbeat);
8666
- }
8667
- }
8668
- });
8669
- return new Response(stream, {
8670
- headers: {
8671
- "cache-control": "no-cache, no-transform",
8672
- connection: "keep-alive",
8673
- "content-type": "text/event-stream; charset=utf-8"
8674
- }
8675
- });
8676
- });
8677
- }
8678
8956
  // src/furin.ts
8679
8957
  init_boundaries();
8680
8958
  init_client();
@@ -8700,17 +8978,19 @@ function furinInvalidate() {
8700
8978
  init_render();
8701
8979
  init_await();
8702
8980
  init_not_found();
8703
- function resolveClientDirFromArgv() {
8704
- return resolveClientDirFromEnv() ?? resolveClientDirFromModuleUrl() ?? resolveClientDirFromProcessArgs() ?? resolveFallbackClientDir();
8981
+ function resolveClientDirFromArgv(prefix) {
8982
+ const dirName = clientDirNameForPrefix(prefix);
8983
+ return resolveClientDirFromEnv(dirName) ?? resolveClientDirFromModuleUrl(dirName) ?? resolveClientDirFromProcessArgs(dirName) ?? resolveFallbackClientDir(dirName);
8705
8984
  }
8706
- function resolveClientDirFromEnv() {
8985
+ function resolveClientDirFromEnv(dirName) {
8707
8986
  const envClientDir = process.env.FURIN_CLIENT_DIR;
8708
8987
  if (!envClientDir) {
8709
8988
  return null;
8710
8989
  }
8711
- return envClientDir.startsWith("/") ? envClientDir : resolve2(process.cwd(), envClientDir);
8990
+ const base = envClientDir.startsWith("/") ? envClientDir : resolve2(process.cwd(), envClientDir);
8991
+ return dirName === "client" ? base : join4(dirname2(base), dirName);
8712
8992
  }
8713
- function resolveClientDirFromModuleUrl() {
8993
+ function resolveClientDirFromModuleUrl(dirName) {
8714
8994
  try {
8715
8995
  const moduleUrl = new URL(import.meta.url);
8716
8996
  if (moduleUrl.protocol !== "file:") {
@@ -8720,14 +9000,14 @@ function resolveClientDirFromModuleUrl() {
8720
9000
  if (modulePath.includes("/$bunfs/")) {
8721
9001
  return null;
8722
9002
  }
8723
- const moduleClientDir = join4(dirname2(modulePath), "client");
9003
+ const moduleClientDir = join4(dirname2(modulePath), dirName);
8724
9004
  if (existsSync5(join4(moduleClientDir, "index.html"))) {
8725
9005
  return moduleClientDir;
8726
9006
  }
8727
9007
  } catch {}
8728
9008
  return null;
8729
9009
  }
8730
- function resolveClientDirFromProcessArgs() {
9010
+ function resolveClientDirFromProcessArgs(dirName) {
8731
9011
  const candidates = [
8732
9012
  process.argv[1],
8733
9013
  process.argv[0],
@@ -8735,14 +9015,14 @@ function resolveClientDirFromProcessArgs() {
8735
9015
  process.execPath
8736
9016
  ].filter((value) => typeof value === "string" && value.length > 0);
8737
9017
  for (const candidate of candidates) {
8738
- const resolved = resolveClientDirFromCandidate(candidate);
9018
+ const resolved = resolveClientDirFromCandidate(candidate, dirName);
8739
9019
  if (resolved) {
8740
9020
  return resolved;
8741
9021
  }
8742
9022
  }
8743
9023
  return null;
8744
9024
  }
8745
- function resolveClientDirFromCandidate(candidate) {
9025
+ function resolveClientDirFromCandidate(candidate, dirName) {
8746
9026
  const name = basename(candidate);
8747
9027
  if (name === "bun" || name === "node") {
8748
9028
  return null;
@@ -8752,73 +9032,55 @@ function resolveClientDirFromCandidate(candidate) {
8752
9032
  }
8753
9033
  const absolute = candidate.startsWith("/") ? candidate : resolve2(process.cwd(), candidate);
8754
9034
  if (existsSync5(absolute)) {
8755
- return join4(dirname2(absolute), "client");
9035
+ return join4(dirname2(absolute), dirName);
8756
9036
  }
8757
9037
  if (!candidate.includes("/")) {
8758
- return resolveClientDirFromPath(candidate);
9038
+ return resolveClientDirFromPath(candidate, dirName);
8759
9039
  }
8760
9040
  return null;
8761
9041
  }
8762
- function resolveClientDirFromPath(candidate) {
9042
+ function resolveClientDirFromPath(candidate, dirName) {
8763
9043
  const pathEntries = process.env.PATH?.split(":") ?? [];
8764
9044
  for (const dir of pathEntries) {
8765
9045
  const fullPath = join4(dir, candidate);
8766
9046
  if (existsSync5(fullPath)) {
8767
- return join4(dirname2(fullPath), "client");
9047
+ return join4(dirname2(fullPath), dirName);
8768
9048
  }
8769
9049
  }
8770
9050
  return null;
8771
9051
  }
8772
- function resolveFallbackClientDir() {
8773
- const defaultClientDir = resolve2(process.cwd(), ".furin/build/bun/client");
9052
+ function resolveFallbackClientDir(dirName) {
9053
+ const defaultClientDir = resolve2(process.cwd(), ".furin/build/bun", dirName);
8774
9054
  if (existsSync5(join4(defaultClientDir, "index.html"))) {
8775
9055
  return defaultClientDir;
8776
9056
  }
8777
- return join4(process.cwd(), "client");
9057
+ return join4(process.cwd(), dirName);
8778
9058
  }
8779
- async function setupProdTemplate(embedded, clientDir) {
9059
+ async function setupProdTemplate(embedded, clientDir, instance) {
8780
9060
  if (embedded) {
8781
9061
  if (!embedded.template) {
8782
9062
  throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
8783
9063
  }
8784
9064
  const html = await Bun.file(embedded.template).text();
8785
- setProductionTemplateContent(html);
9065
+ setProductionTemplateContent(html, instance);
8786
9066
  return;
8787
9067
  }
8788
9068
  const templatePath = join4(clientDir, "index.html");
8789
9069
  if (!existsSync5(templatePath)) {
8790
9070
  throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
8791
9071
  }
8792
- setProductionTemplatePath(templatePath);
8793
- }
8794
- function wrapWithRequestScope(app, syncStreamPath) {
8795
- return app.wrap((handler, _request) => (ctx) => runWithSyncStreamPath(syncStreamPath, () => _runWithRequestInvalidationScope(() => handler(ctx))));
8796
- }
8797
- function hydrateSSGCacheFromCompileContext(ctx) {
8798
- if (!ctx.ssgCache) {
8799
- return;
8800
- }
8801
- for (const [path, entry] of Object.entries(ctx.ssgCache)) {
8802
- setSSGCache(path, entry);
8803
- }
9072
+ setProductionTemplatePath(templatePath, instance);
8804
9073
  }
8805
- async function furin({
8806
- pagesDir,
8807
- logger,
8808
- clientLogging,
8809
- sync
8810
- }) {
8811
- const syncStreamPath = resolveSyncStreamPath(sync);
9074
+ function createLoggerPlugin(prefix, syncStreamPath, logger) {
8812
9075
  const { exclude: userExclude, ...evlogOptions } = logger ?? {};
8813
- initLogger({ env: { service: "furin" } });
8814
- const loggerPlugin = new Elysia7().use(evlog({
9076
+ return new Elysia7().use(evlog({
8815
9077
  ...evlogOptions,
8816
9078
  exclude: [
8817
- "/_client/**",
8818
- "/public/**",
8819
- "/favicon.ico",
8820
- "/_bun_hmr_entry/**",
8821
- ...syncStreamPath ? [syncStreamPath] : [],
9079
+ `${prefix}/_client/**`,
9080
+ `${prefix}/public/**`,
9081
+ `${prefix}/favicon.ico`,
9082
+ `${prefix}/_bun_hmr_entry/**`,
9083
+ ...syncStreamPath ? [`${prefix}${syncStreamPath}`] : [],
8822
9084
  ...userExclude ?? []
8823
9085
  ]
8824
9086
  })).post("/_furin/ingest", ({ body, log, status }) => {
@@ -8846,12 +9108,50 @@ async function furin({
8846
9108
  }
8847
9109
  return status("No Content");
8848
9110
  }, { parse: "json" });
9111
+ }
9112
+ function wrapWithRequestScope(app) {
9113
+ return app.wrap((handler, request) => (ctx) => {
9114
+ if (hasRequestScope()) {
9115
+ return handler(ctx);
9116
+ }
9117
+ markTraffic();
9118
+ const req = request ?? ctx?.request;
9119
+ const pathname = req ? new URL(req.url).pathname : "/";
9120
+ return runWithInstanceScope(resolveInstanceByPath(pathname), () => handler(ctx));
9121
+ });
9122
+ }
9123
+ function hydrateSSGCacheFromCompileContext(ctx) {
9124
+ if (!ctx.ssgCache) {
9125
+ return;
9126
+ }
9127
+ for (const [path, entry] of Object.entries(ctx.ssgCache)) {
9128
+ setSSGCache(path, entry);
9129
+ }
9130
+ }
9131
+ async function furin({
9132
+ pagesDir,
9133
+ prefix: rawPrefix,
9134
+ clientDir: explicitClientDir,
9135
+ logger,
9136
+ clientLogging,
9137
+ sync
9138
+ } = {}) {
9139
+ const prefix = normalizePrefix(rawPrefix);
9140
+ const syncStreamPath = resolveSyncStreamPath(sync);
9141
+ initLogger({ env: { service: "furin" } });
9142
+ const loggerPlugin = createLoggerPlugin(prefix, syncStreamPath, logger);
8849
9143
  const cwd = process.cwd();
8850
- const ctx = getCompileContext();
8851
- const resolvedPagesDir = ctx?.rootPath ? dirname2(ctx.rootPath) : resolve2(cwd, pagesDir ?? "src/pages");
8852
- const instanceName = `furin-${resolvedPagesDir.replaceAll("\\", "/")}`;
9144
+ const paramPagesDir = resolve2(cwd, pagesDir ?? "src/pages");
9145
+ const ctx = getCompileContext(paramPagesDir, prefix);
9146
+ const resolvedPagesDir = ctx?.rootPath ? dirname2(ctx.rootPath) : paramPagesDir;
9147
+ const instanceName = `furin-${prefix}-${resolvedPagesDir.replaceAll("\\", "/")}`;
9148
+ const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
9149
+ assertPrefixAvailable(prefix, normalizedPagesDir);
9150
+ const instance = createInstance(prefix, normalizedPagesDir);
9151
+ instance.syncStreamPath = syncStreamPath;
8853
9152
  if (IS_DEV) {
8854
- const furinDir = resolve2(cwd, ".furin");
9153
+ const instanceSlug = prefix === "" ? "" : prefix.slice(1).replaceAll("/", "__");
9154
+ const furinDir = resolve2(cwd, ".furin", instanceSlug);
8855
9155
  const { registerDevPagePlugin: registerDevPagePlugin2 } = await Promise.resolve().then(() => (init_dev_page_plugin(), exports_dev_page_plugin));
8856
9156
  registerDevPagePlugin2();
8857
9157
  const { createDevInspectorPlugin: createDevInspectorPlugin2 } = await Promise.resolve().then(() => (init_dev_inspector(), exports_dev_inspector));
@@ -8862,28 +9162,29 @@ async function furin({
8862
9162
  writeDevFiles2(routes2, {
8863
9163
  outDir: furinDir,
8864
9164
  rootLayout: root2.path,
8865
- basePath: "",
8866
- publicPath: "/_client/",
8867
- clientLogging: clientLogging ?? false
9165
+ basePath: prefix,
9166
+ publicPath: `${prefix}/_client/`,
9167
+ clientLogging: clientLogging ?? false,
9168
+ skipRouteTypes: prefix !== ""
8868
9169
  }, cwd);
8869
9170
  const publicDir = resolve2(cwd, "public");
8870
9171
  const publicExists = existsSync5(publicDir);
8871
- const devApp = new Elysia7({ name: instanceName, seed: resolvedPagesDir }).use(loggerPlugin).onError({ as: "global" }, async ({ code, request }) => {
9172
+ const devApp = new Elysia7({
9173
+ name: instanceName,
9174
+ seed: resolvedPagesDir,
9175
+ prefix: prefix || undefined
9176
+ }).use(loggerPlugin).onError(async ({ code, request }) => {
8872
9177
  if (code === "NOT_FOUND") {
8873
9178
  return await renderRootNotFound(root2, request);
8874
9179
  }
8875
- }).onAfterHandle({ as: "global" }, ({ set }) => {
9180
+ }).onAfterHandle(({ set }) => {
8876
9181
  const pending = consumePendingInvalidations();
8877
9182
  if (pending.length > 0) {
8878
9183
  set.headers["x-furin-revalidate"] = pending.join(",");
8879
9184
  }
8880
- }).use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true })).use(publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia7).get("/favicon.ico", publicExists ? file(join4(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use(createDevInspectorPlugin2()).use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia7).use(createDataEndpoint(routes2)).use((app) => {
8881
- for (const route of routes2) {
8882
- app.use(createRoutePlugin(route, root2, undefined, searchRoutes2));
8883
- }
8884
- return app;
8885
- });
8886
- return wrapWithRequestScope(devApp, syncStreamPath);
9185
+ }).use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true })).use(publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia7).get("/favicon.ico", publicExists ? file(join4(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use(createDevInspectorPlugin2()).use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath, `${prefix}${syncStreamPath}`) : new Elysia7).use(createDataEndpoint(routes2)).use((app) => routes2.reduce((chain, route) => chain.use(createRoutePlugin(route, root2, undefined, searchRoutes2)), app)).use(createNotFoundHandling(prefix, routes2, root2));
9186
+ registerInstance(instance);
9187
+ return wrapWithRequestScope(devApp);
8887
9188
  }
8888
9189
  if (!ctx) {
8889
9190
  throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
@@ -8891,33 +9192,39 @@ async function furin({
8891
9192
  const { root, routes } = loadProdRoutes(ctx);
8892
9193
  const searchRoutes = createSearchRouteMetadata(routes);
8893
9194
  const prodBuildId = ctx.buildId ?? "";
8894
- setBuildId(prodBuildId);
8895
- hydrateSSGCacheFromCompileContext(ctx);
9195
+ instance.buildId = prodBuildId;
9196
+ withInstance(instance, () => {
9197
+ hydrateSSGCacheFromCompileContext(ctx);
9198
+ });
8896
9199
  const embedded = ctx?.embedded;
8897
- const clientDir = embedded ? "" : resolveClientDirFromArgv();
8898
- await setupProdTemplate(embedded, clientDir);
8899
- const prodApp = new Elysia7({ name: instanceName, seed: resolvedPagesDir }).use(loggerPlugin).onError({ as: "global" }, async ({ code, request }) => {
9200
+ const clientDir = embedded ? "" : explicitClientDir ?? resolveClientDirFromArgv(prefix);
9201
+ await setupProdTemplate(embedded, clientDir, instance);
9202
+ const clientAssetPrefix = `${prefix}/_client/`;
9203
+ const prodApp = new Elysia7({
9204
+ name: instanceName,
9205
+ seed: resolvedPagesDir,
9206
+ prefix: prefix || undefined
9207
+ }).use(loggerPlugin).onError(async ({ code, request }) => {
8900
9208
  if (code === "NOT_FOUND") {
8901
9209
  return await renderRootNotFound(root, request);
8902
9210
  }
8903
- }).onAfterHandle({ as: "global" }, ({ path, set }) => {
8904
- if (path.startsWith("/_client/")) {
9211
+ }).onAfterHandle(({ path, set }) => {
9212
+ if (path.startsWith(clientAssetPrefix)) {
8905
9213
  set.headers["cache-control"] = "public, max-age=31536000, immutable";
8906
9214
  }
8907
9215
  const pending = consumePendingInvalidations();
8908
9216
  if (pending.length > 0) {
8909
9217
  set.headers["x-furin-revalidate"] = pending.join(",");
8910
9218
  }
8911
- const buildId = getBuildId();
8912
- if (buildId) {
8913
- set.headers["x-furin-build-id"] = buildId;
9219
+ if (instance.buildId) {
9220
+ set.headers["x-furin-build-id"] = instance.buildId;
8914
9221
  }
8915
9222
  }).onStart(async ({ server }) => {
8916
9223
  if (ctx.ssgCache) {
8917
9224
  return;
8918
9225
  }
8919
9226
  const origin = server?.url?.origin ?? "http://localhost:3000";
8920
- await warmSSGCache(routes, root, origin, searchRoutes);
9227
+ await withInstance(instance, () => warmSSGCache(routes, root, origin, searchRoutes));
8921
9228
  }).use(await (async () => {
8922
9229
  if (embedded) {
8923
9230
  return new Elysia7().get("/favicon.ico", ({ status }) => {
@@ -8947,13 +9254,25 @@ async function furin({
8947
9254
  }
8948
9255
  app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
8949
9256
  return app;
8950
- })()).use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia7).use(createDataEndpoint(routes)).use((app) => {
8951
- for (const route of routes) {
8952
- app.use(createRoutePlugin(route, root, prodBuildId, searchRoutes));
8953
- }
9257
+ })()).use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath, `${prefix}${syncStreamPath}`) : new Elysia7).use(createDataEndpoint(routes)).use((app) => routes.reduce((chain, route) => chain.use(createRoutePlugin(route, root, prodBuildId, searchRoutes)), app)).use(createNotFoundHandling(prefix, routes, root));
9258
+ registerInstance(instance);
9259
+ return wrapWithRequestScope(prodApp);
9260
+ }
9261
+ function createNotFoundHandling(prefix, routes, root) {
9262
+ const app = new Elysia7;
9263
+ if (prefix === "") {
9264
+ app.onError({ as: "global" }, async ({ code, request }) => {
9265
+ if (code === "NOT_FOUND") {
9266
+ return await renderRootNotFound(root, request);
9267
+ }
9268
+ });
8954
9269
  return app;
8955
- });
8956
- return wrapWithRequestScope(prodApp, syncStreamPath);
9270
+ }
9271
+ if (routes.some((route) => route.pattern === "/*")) {
9272
+ return app;
9273
+ }
9274
+ app.get("/*", ({ request }) => renderRootNotFound(root, request));
9275
+ return app;
8957
9276
  }
8958
9277
  export {
8959
9278
  useAsyncValue,
@@ -8969,6 +9288,7 @@ export {
8969
9288
  furinInvalidate,
8970
9289
  furin,
8971
9290
  defer,
9291
+ clientDirNameForPrefix,
8972
9292
  buildErrorElement,
8973
9293
  buildElement,
8974
9294
  FurinNotFoundBoundary,