@vesk/vesk-cli 0.2.93 → 0.2.95

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 (2) hide show
  1. package/dist/cli.js +1502 -667
  2. package/package.json +5 -5
package/dist/cli.js CHANGED
@@ -608,6 +608,14 @@ var init_errors = __esm({
608
608
  });
609
609
 
610
610
  // ../compiler/src/ir.ts
611
+ function regionMarkerId(node) {
612
+ const ast = node.condition.ast;
613
+ if (ast && typeof ast.start === "number") return `s${ast.start}`;
614
+ const raw2 = node.condition.raw;
615
+ let hash = 5381;
616
+ for (let i = 0; i < raw2.length; i++) hash = (hash << 5) + hash + raw2.charCodeAt(i) | 0;
617
+ return `h${(hash >>> 0).toString(36)}`;
618
+ }
611
619
  var Expression, IRRoot, ComponentIR, StaticNode, TextNode, DynamicBinding, OpaqueDynamicRegion, MapRegion, ComponentRef, ComponentCall, SlotNode, PropSlot, PropSlotRender, WhileLoop, SwitchCase, SwitchBlock, TryCatch, TrackDecl, RuntimeStatement, BreakSignal, ForLoop, ServerBlock, ClientBlock, HeadBlock;
612
620
  var init_ir = __esm({
613
621
  "../compiler/src/ir.ts"() {
@@ -895,7 +903,7 @@ var init_ir = __esm({
895
903
  });
896
904
 
897
905
  // ../runtime/src/ripple-constants.ts
898
- var ROOT_BLOCK, RENDER_BLOCK, EFFECT_BLOCK, BRANCH_BLOCK, FOR_BLOCK, TRY_BLOCK, IF_BLOCK, SWITCH_BLOCK, COMPOSITE_BLOCK, ASYNC_BLOCK, HEAD_BLOCK, PRE_EFFECT_BLOCK, DIRECT_CHILD_BLOCK, CONTAINS_UPDATE, CONTAINS_TEARDOWN, BLOCK_HAS_RUN, TRACKED, DERIVED, DEFERRED, PAUSED, DESTROYED, UPDATE_SOURCE, CONTROL_FLOW_BLOCK, UNINITIALIZED, TRACKED_ARRAY, TRACKED_OBJECT, COMPUTED_PROPERTY, HMR, ARRAY_SET_INDEX_AT, MAX_ARRAY_LENGTH, TRACKED_UPDATED, SUSPENSE_PENDING, SUSPENSE_REJECTED, ASYNC_DERIVED_READ_THROWN;
906
+ var ROOT_BLOCK, RENDER_BLOCK, EFFECT_BLOCK, BRANCH_BLOCK, FOR_BLOCK, TRY_BLOCK, IF_BLOCK, SWITCH_BLOCK, COMPOSITE_BLOCK, ASYNC_BLOCK, HEAD_BLOCK, PRE_EFFECT_BLOCK, DIRECT_CHILD_BLOCK, CONTAINS_UPDATE, CONTAINS_TEARDOWN, BLOCK_HAS_RUN, TRACKED, DERIVED, DEFERRED, PAUSED, DESTROYED, UPDATE_SOURCE, MANAGED_CHILDREN, CONTROL_FLOW_BLOCK, UNINITIALIZED, TRACKED_ARRAY, TRACKED_OBJECT, COMPUTED_PROPERTY, HMR, ARRAY_SET_INDEX_AT, MAX_ARRAY_LENGTH, TRACKED_UPDATED, SUSPENSE_PENDING, SUSPENSE_REJECTED, ASYNC_DERIVED_READ_THROWN;
899
907
  var init_ripple_constants = __esm({
900
908
  "../runtime/src/ripple-constants.ts"() {
901
909
  "use strict";
@@ -921,6 +929,7 @@ var init_ripple_constants = __esm({
921
929
  PAUSED = 1 << 20;
922
930
  DESTROYED = 1 << 21;
923
931
  UPDATE_SOURCE = 1 << 22;
932
+ MANAGED_CHILDREN = 1 << 23;
924
933
  CONTROL_FLOW_BLOCK = FOR_BLOCK | IF_BLOCK | SWITCH_BLOCK | TRY_BLOCK | COMPOSITE_BLOCK;
925
934
  UNINITIALIZED = Symbol("uninitialized");
926
935
  TRACKED_ARRAY = Symbol();
@@ -955,8 +964,8 @@ function user_effect(fn) {
955
964
  }
956
965
  return block(EFFECT_BLOCK, fn);
957
966
  }
958
- function effect(fn) {
959
- return block(EFFECT_BLOCK, fn);
967
+ function effect(fn, managed = false) {
968
+ return block(EFFECT_BLOCK | (managed ? MANAGED_CHILDREN : 0), fn);
960
969
  }
961
970
  function pre_effect(fn) {
962
971
  return block(PRE_EFFECT_BLOCK, fn);
@@ -1031,16 +1040,12 @@ function destroy_block_children(parent, remove_dom = false) {
1031
1040
  }
1032
1041
  function destroy_non_branch_children(parent, remove_dom = false) {
1033
1042
  let block2 = parent.first;
1034
- if ((parent.f & CONTAINS_TEARDOWN) === 0 && parent.first !== null && (parent.first.f & BRANCH_BLOCK) === 0) {
1035
- parent.first = parent.last = null;
1036
- } else {
1037
- while (block2 !== null) {
1038
- const next = block2.next;
1039
- if ((block2.f & BRANCH_BLOCK) === 0) {
1040
- destroy_block(block2, remove_dom);
1041
- }
1042
- block2 = next;
1043
+ while (block2 !== null) {
1044
+ const next = block2.next;
1045
+ if ((block2.f & BRANCH_BLOCK) === 0) {
1046
+ destroy_block(block2, remove_dom);
1043
1047
  }
1048
+ block2 = next;
1044
1049
  }
1045
1050
  }
1046
1051
  function unlink_block(block2) {
@@ -1283,7 +1288,9 @@ function run_block(block2) {
1283
1288
  active_reaction = block2;
1284
1289
  unsubscribe_reaction(block2);
1285
1290
  active_component = block2.co;
1286
- destroy_non_branch_children(block2);
1291
+ if ((block2.f & MANAGED_CHILDREN) === 0) {
1292
+ destroy_non_branch_children(block2);
1293
+ }
1287
1294
  run_teardown(block2);
1288
1295
  tracking = (block2.f & (ROOT_BLOCK | BRANCH_BLOCK)) === 0;
1289
1296
  active_dependency = null;
@@ -1337,7 +1344,7 @@ function track(v, b, get2, set2) {
1337
1344
  }
1338
1345
  function create_dependency(tracked2) {
1339
1346
  const reaction = active_reaction;
1340
- if (is_orphan(tracked2.b)) {
1347
+ if (is_orphan(tracked2.b) || (tracked2.f & DERIVED) !== 0) {
1341
1348
  (tracked2.r ??= /* @__PURE__ */ new Set()).add(reaction);
1342
1349
  }
1343
1350
  const existing2 = reaction.d;
@@ -1579,7 +1586,7 @@ function unsubscribe_reaction(reaction) {
1579
1586
  let dep = reaction.d;
1580
1587
  while (dep !== null) {
1581
1588
  const t = dep.t;
1582
- if (is_orphan(t.b) && t.r !== null) {
1589
+ if (t.r !== null) {
1583
1590
  t.r.delete(reaction);
1584
1591
  }
1585
1592
  dep = dep.n;
@@ -2144,7 +2151,7 @@ function buildRequestInit(options) {
2144
2151
  function resolveFetchUrl(url) {
2145
2152
  if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith("//")) return url;
2146
2153
  const ctx2 = g().__vesk_request;
2147
- const resolver = ctx2 && typeof ctx2.resolveUrl === "function" ? ctx2.resolveUrl : null;
2154
+ const resolver = ctx2 && typeof ctx2.resolveUrl === "function" ? ctx2.resolveUrl.bind(ctx2) : null;
2148
2155
  if (resolver) return resolver(url);
2149
2156
  const reqUrl = ctx2?.url;
2150
2157
  let base = typeof reqUrl === "string" && /^https?:\/\//i.test(reqUrl) ? reqUrl : globalThis.__vesk_ssr_base_url || "";
@@ -2435,7 +2442,17 @@ function mutate(key, data2) {
2435
2442
  }
2436
2443
  function createResourceAccessor(handle2) {
2437
2444
  const state = handle2.state;
2438
- const accessor = {};
2445
+ const read = async () => {
2446
+ for (; ; ) {
2447
+ const s = get(state);
2448
+ if (!s.loading) {
2449
+ if (s.error) throw s.error;
2450
+ return s.data;
2451
+ }
2452
+ await handle2.settled;
2453
+ }
2454
+ };
2455
+ const accessor = new ResourcePromise(read);
2439
2456
  Object.defineProperty(accessor, "loading", {
2440
2457
  get() {
2441
2458
  return get(state).loading;
@@ -2452,19 +2469,6 @@ function createResourceAccessor(handle2) {
2452
2469
  }
2453
2470
  });
2454
2471
  accessor._state = state;
2455
- const toData = async () => {
2456
- for (; ; ) {
2457
- const s = get(state);
2458
- if (!s.loading) {
2459
- if (s.error) throw s.error;
2460
- return s.data;
2461
- }
2462
- await handle2.settled;
2463
- }
2464
- };
2465
- accessor.then = (onFulfilled, onRejected) => toData().then(onFulfilled, onRejected);
2466
- accessor.catch = (onRejected) => toData().catch(onRejected);
2467
- accessor.finally = (onFinally) => toData().finally(onFinally);
2468
2472
  accessor.refresh = () => revalidate(handle2);
2469
2473
  accessor.abort = () => {
2470
2474
  if (!isServer()) handle2.controller?.abort();
@@ -2547,7 +2551,7 @@ async function resolveSsrResources() {
2547
2551
  delete g().__vsk_ssr_failures;
2548
2552
  return data2;
2549
2553
  }
2550
- var HttpError, TimeoutError, g, isServer, ssrSink, DEFAULT_FAILURE_TTL;
2554
+ var HttpError, TimeoutError, g, isServer, ssrSink, DEFAULT_FAILURE_TTL, ResourcePromise;
2551
2555
  var init_resource = __esm({
2552
2556
  "../runtime/src/resource.ts"() {
2553
2557
  "use strict";
@@ -2573,6 +2577,23 @@ var init_resource = __esm({
2573
2577
  isServer = () => !!g().__vsk_ssr;
2574
2578
  ssrSink = null;
2575
2579
  DEFAULT_FAILURE_TTL = 1e4;
2580
+ ResourcePromise = class extends Promise {
2581
+ read;
2582
+ constructor(read) {
2583
+ super(() => {
2584
+ });
2585
+ this.read = read;
2586
+ }
2587
+ then(onfulfilled, onrejected) {
2588
+ return this.read().then(onfulfilled, onrejected);
2589
+ }
2590
+ catch(onrejected) {
2591
+ return this.read().catch(onrejected);
2592
+ }
2593
+ finally(onfinally) {
2594
+ return this.read().finally(onfinally);
2595
+ }
2596
+ };
2576
2597
  useFetch.text = (url, options) => useFetch(async () => {
2577
2598
  const res = await doFetch(resolveFetchUrl(url), buildRequestInit(options ?? {}));
2578
2599
  if (!res.ok) throw new HttpError(res.status, res.statusText);
@@ -2964,6 +2985,47 @@ function adoptElementRaw(root3, marker, tag) {
2964
2985
  recordAdopted(root3, el, tag || el.tagName.toLowerCase());
2965
2986
  return el;
2966
2987
  }
2988
+ function classTokens(value) {
2989
+ const out = [];
2990
+ let token = "";
2991
+ for (let i = 0; i < value.length; i++) {
2992
+ const ch = value[i];
2993
+ if (ch === " " || ch === "\n" || ch === " " || ch === "\r" || ch === "\f") {
2994
+ if (token) {
2995
+ out.push(token);
2996
+ token = "";
2997
+ }
2998
+ } else {
2999
+ token += ch;
3000
+ }
3001
+ }
3002
+ if (token) out.push(token);
3003
+ return out;
3004
+ }
3005
+ function descriptorMatches(el, descriptor) {
3006
+ if (!descriptor || !descriptor.class) return true;
3007
+ const wanted = classTokens(descriptor.class);
3008
+ if (wanted.length === 0) return true;
3009
+ const actual = el.classList;
3010
+ if (actual) {
3011
+ for (const token of wanted) {
3012
+ if (!actual.contains(token)) return false;
3013
+ }
3014
+ return true;
3015
+ }
3016
+ const raw2 = el.getAttribute("class") ?? el.className ?? "";
3017
+ const present2 = classTokens(String(raw2));
3018
+ for (const token of wanted) {
3019
+ if (!present2.includes(token)) return false;
3020
+ }
3021
+ return true;
3022
+ }
3023
+ function structuralBranchMatches(el, branch2) {
3024
+ const actualTag = el.tagName.toLowerCase();
3025
+ if (branch2.tag && actualTag !== branch2.tag) return false;
3026
+ if (branch2.descriptor) return descriptorMatches(el, branch2.descriptor);
3027
+ return !!branch2.tag;
3028
+ }
2967
3029
  function createHydrateWalker(container, markerList) {
2968
3030
  const markers = markerList || (container ? collectVskMarkers(container) : []);
2969
3031
  if (!markerList && container && markers.length === 0 && container.children.length > 0) {
@@ -3576,7 +3638,7 @@ ${String(this.root.outerHTML).slice(0, 800)}` : ""),
3576
3638
  this.inheritOffset = 0;
3577
3639
  return n;
3578
3640
  }
3579
- claimAt(tag, skipK, raw2) {
3641
+ claimAt(tag, skipK, raw2, descriptor) {
3580
3642
  if (globalThis.__vesk_hydrate_debug) {
3581
3643
  console.error("[hyd-dbg] claimAt", tag, "skip=", skipK, "idx=", this.idx, "els=", this.els.length);
3582
3644
  }
@@ -3588,14 +3650,18 @@ ${String(this.root.outerHTML).slice(0, 800)}` : ""),
3588
3650
  if (target > this.els.length) target = this.idx;
3589
3651
  while (target < this.els.length) {
3590
3652
  const el = this.els[target];
3591
- if (tag && el.tagName.toLowerCase() !== tag) {
3653
+ const actualTag = el.tagName.toLowerCase();
3654
+ const tagMismatch = !!tag && actualTag !== tag;
3655
+ const descriptorMismatch = !tagMismatch && !descriptorMatches(el, descriptor);
3656
+ if (tagMismatch || descriptorMismatch) {
3592
3657
  this.idx = this.advancePastSkippable(target + 1);
3658
+ const expectedTag = tag || "div";
3593
3659
  const ghost = {
3594
3660
  state: "ghost",
3595
3661
  el,
3596
3662
  owner: this.root,
3597
- expectedTag: tag || "div",
3598
- actualTag: el.tagName.toLowerCase(),
3663
+ expectedTag,
3664
+ actualTag,
3599
3665
  detached: false
3600
3666
  };
3601
3667
  recordClaim(this.root, ghost);
@@ -3606,20 +3672,18 @@ ${String(this.root.outerHTML).slice(0, 800)}` : ""),
3606
3672
  } catch {
3607
3673
  }
3608
3674
  }
3609
- const fresh2 = document.createElement(tag || "div");
3675
+ const fresh2 = document.createElement(expectedTag);
3610
3676
  recordClaim(this.root, {
3611
3677
  state: "fresh",
3612
3678
  el: fresh2,
3613
3679
  owner: this.root,
3614
- expectedTag: tag || "div",
3680
+ expectedTag,
3615
3681
  actualTag: fresh2.tagName.toLowerCase(),
3616
3682
  detached: false
3617
3683
  });
3618
- reportMiss(
3619
- "tag-mismatch",
3620
- `descriptor wanted <${tag}> but the SSR slot holds <${el.tagName.toLowerCase()}>; consumed one slot, detached the local ghost, and rendered fresh.`,
3621
- false
3622
- );
3684
+ const actualClass = el.getAttribute("class") || "";
3685
+ const detail = descriptorMismatch ? `descriptor wanted <${expectedTag} class="${descriptor?.class || ""}"> but the SSR slot holds <${actualTag} class="${actualClass}">; consumed one slot, detached the local ghost, and rendered fresh.` : `descriptor wanted <${tag}> but the SSR slot holds <${actualTag}>; consumed one slot, detached the local ghost, and rendered fresh.`;
3686
+ reportMiss(descriptorMismatch ? "descriptor-mismatch" : "tag-mismatch", detail, false);
3623
3687
  return fresh2;
3624
3688
  }
3625
3689
  if (this.adopted.has(el)) {
@@ -3653,11 +3717,74 @@ ${String(this.root.outerHTML).slice(0, 800)}` : ""),
3653
3717
  );
3654
3718
  return fresh;
3655
3719
  }
3656
- nextElement(tag, skipK = 0) {
3657
- return this.claimAt(tag, skipK, false);
3720
+ nextElement(tag, skipK = 0, descriptor) {
3721
+ return this.claimAt(tag, skipK, false, descriptor);
3658
3722
  }
3659
- claimOnly(tag, skipK = 0) {
3660
- return this.claimAt(tag, skipK, true);
3723
+ claimOnly(tag, skipK = 0, descriptor) {
3724
+ return this.claimAt(tag, skipK, true, descriptor);
3725
+ }
3726
+ discardStructuralRegion(branches, selected, skipK = 0) {
3727
+ if (!branches || branches.length === 0) return false;
3728
+ let offset2 = skipK || 0;
3729
+ if (!offset2) offset2 = this.inheritOffset;
3730
+ let target = this.advancePastSkippable(this.idx + offset2);
3731
+ if (target > this.els.length) target = this.idx;
3732
+ target = this.advancePastSkippable(target);
3733
+ while (target < this.els.length) {
3734
+ const el = this.els[target];
3735
+ if (this.adopted.has(el)) {
3736
+ target = this.advancePastSkippable(target + 1);
3737
+ continue;
3738
+ }
3739
+ let matchCount = 0;
3740
+ let matchIdx = -1;
3741
+ for (let i = 0; i < branches.length; i++) {
3742
+ if (structuralBranchMatches(el, branches[i])) {
3743
+ matchCount++;
3744
+ matchIdx = i;
3745
+ }
3746
+ }
3747
+ if (matchCount !== 1 || matchIdx === selected) return false;
3748
+ const count = branches[matchIdx].count;
3749
+ if (!count || count < 1) return false;
3750
+ this.inheritOffset = 0;
3751
+ let p = target;
3752
+ let removed = 0;
3753
+ while (removed < count && p < this.els.length) {
3754
+ const candidate = this.els[p];
3755
+ if (this.adopted.has(candidate)) {
3756
+ p = this.advancePastSkippable(p + 1);
3757
+ continue;
3758
+ }
3759
+ const actualTag = candidate.tagName.toLowerCase();
3760
+ const ghost = {
3761
+ state: "ghost",
3762
+ el: candidate,
3763
+ owner: this.root,
3764
+ expectedTag: branches[matchIdx].tag || actualTag,
3765
+ actualTag,
3766
+ detached: false
3767
+ };
3768
+ recordClaim(this.root, ghost);
3769
+ if (this.root && candidate.parentNode === this.root) {
3770
+ try {
3771
+ candidate.remove();
3772
+ ghost.detached = true;
3773
+ } catch {
3774
+ }
3775
+ }
3776
+ p = this.advancePastSkippable(p + 1);
3777
+ removed++;
3778
+ }
3779
+ this.idx = p;
3780
+ reportMiss(
3781
+ "descriptor-mismatch",
3782
+ `structural region reconciliation removed SSR branch ${matchIdx}; the client selected branch ${selected}.`,
3783
+ false
3784
+ );
3785
+ return true;
3786
+ }
3787
+ return false;
3661
3788
  }
3662
3789
  subWalker(rootEl) {
3663
3790
  if (globalThis.__vesk_hydrate_debug) {
@@ -5511,6 +5638,19 @@ async function renderErrorPage(router, match, container, error, navToken) {
5511
5638
  container.innerHTML = dom;
5512
5639
  }
5513
5640
  }
5641
+ function trackHydration(promise) {
5642
+ const g5 = globalThis;
5643
+ g5.__vesk_hydrated = false;
5644
+ promise.then(
5645
+ () => {
5646
+ g5.__vesk_hydrated = true;
5647
+ },
5648
+ () => {
5649
+ g5.__vesk_hydrated = true;
5650
+ }
5651
+ );
5652
+ return promise;
5653
+ }
5514
5654
  async function hydrateInitial(router, match, container, strategy) {
5515
5655
  const hydrationNavToken = router._navToken || 0;
5516
5656
  const chain = match.matchChain;
@@ -5822,13 +5962,15 @@ function createRouter(routes, options = {}) {
5822
5962
  const match = matchRoute(this.routeTree, url.pathname);
5823
5963
  if (match) {
5824
5964
  match.pathname = url.pathname;
5825
- hydrateInitial(this, match, container, hydrateStrategy);
5965
+ trackHydration(hydrateInitial(this, match, container, hydrateStrategy));
5826
5966
  this._currentMatch = match;
5827
5967
  } else {
5828
5968
  this.navigate(path, { replace: true });
5969
+ globalThis.__vesk_hydrated = true;
5829
5970
  }
5830
5971
  } else {
5831
5972
  this.navigate(path, { replace: true });
5973
+ globalThis.__vesk_hydrated = true;
5832
5974
  }
5833
5975
  return this;
5834
5976
  },
@@ -5862,7 +6004,9 @@ function createRouter(routes, options = {}) {
5862
6004
  const updateUrl = () => {
5863
6005
  const fullPath = url.pathname + url.search;
5864
6006
  const target = mode ? fullPath.startsWith("/") ? "#" + fullPath : "#" + fullPath : fullPath;
5865
- if (!opts.replace) {
6007
+ const liveFull = window.location.pathname + window.location.search + window.location.hash;
6008
+ if (!opts.replace && target === liveFull) {
6009
+ } else if (!opts.replace) {
5866
6010
  window.history.pushState({ path: url.pathname }, "", target);
5867
6011
  } else {
5868
6012
  window.history.replaceState({ path: url.pathname }, "", target);
@@ -6057,6 +6201,41 @@ function createFileRouter(routeTree, options = {}) {
6057
6201
  const renderFn = options.render || renderMatch;
6058
6202
  const hydrateStrategy = options.hydrate || "full";
6059
6203
  const hashMode = options.hash === true;
6204
+ const serverMiddlewareCache = /* @__PURE__ */ new Map();
6205
+ let serverMiddlewareDisabled = false;
6206
+ const runServerMiddleware = async (ctx2, next) => {
6207
+ if (options.serverMiddleware !== true || typeof window === "undefined" || serverMiddlewareDisabled) return next();
6208
+ const path = String(ctx2.url || "/");
6209
+ const cached = serverMiddlewareCache.get(path);
6210
+ if (cached && Date.now() - cached.at < 2500) {
6211
+ if (cached.body && typeof cached.body.redirect === "string" && cached.body.redirect) {
6212
+ return { redirect: cached.body.redirect };
6213
+ }
6214
+ if (cached.body && typeof cached.body.rewrite === "string" && cached.body.rewrite) return next(cached.body.rewrite);
6215
+ return next();
6216
+ }
6217
+ const endpoint = globalThis.__veskServerMiddlewareEndpoint ?? "/_vesk/middleware";
6218
+ try {
6219
+ const res = await fetch(`${endpoint}?path=${encodeURIComponent(path)}`, {
6220
+ credentials: "include",
6221
+ headers: { Accept: "application/json" },
6222
+ cache: "no-store"
6223
+ });
6224
+ if (res.status === 404) {
6225
+ serverMiddlewareDisabled = true;
6226
+ return next();
6227
+ }
6228
+ const body = await res.json().catch(() => null);
6229
+ serverMiddlewareCache.set(path, { at: Date.now(), body });
6230
+ if (body && typeof body.redirect === "string" && body.redirect) {
6231
+ return { redirect: body.redirect };
6232
+ }
6233
+ if (body && typeof body.rewrite === "string" && body.rewrite) return next(body.rewrite);
6234
+ return next();
6235
+ } catch {
6236
+ return next();
6237
+ }
6238
+ };
6060
6239
  const router = {
6061
6240
  _hydrateStrategy: hydrateStrategy,
6062
6241
  routeTree,
@@ -6169,13 +6348,15 @@ function createFileRouter(routeTree, options = {}) {
6169
6348
  const match = matchRoute(routeTree, path);
6170
6349
  if (match) {
6171
6350
  match.pathname = path;
6172
- hydrateInitial(router, match, container, hydrateStrategy);
6351
+ trackHydration(hydrateInitial(router, match, container, hydrateStrategy));
6173
6352
  router._currentMatch = match;
6174
6353
  } else {
6175
6354
  router.navigate(path, { replace: true });
6355
+ globalThis.__vesk_hydrated = true;
6176
6356
  }
6177
6357
  } else {
6178
6358
  router.navigate(path, { replace: true });
6359
+ globalThis.__vesk_hydrated = true;
6179
6360
  }
6180
6361
  return router;
6181
6362
  },
@@ -6229,12 +6410,17 @@ function createFileRouter(routeTree, options = {}) {
6229
6410
  navDebug("navigate", url.pathname, "token=" + router._navToken, "pendingChunks", hasPendingChunks(match.matchChain));
6230
6411
  const navToken = router._navToken;
6231
6412
  loadingStart();
6232
- const middlewareFns = Array.isArray(middleware) ? middleware : middleware ? [middleware] : [];
6413
+ const middlewareFns = [
6414
+ ...options.serverMiddleware === true ? [runServerMiddleware] : [],
6415
+ ...Array.isArray(middleware) ? middleware : middleware ? [middleware] : []
6416
+ ];
6233
6417
  let firstRenderFailed = false;
6234
6418
  const updateUrl = () => {
6235
6419
  const fullUrl = url.pathname + url.search;
6236
6420
  const target = mode ? fullUrl.startsWith("/") ? "#" + fullUrl : "#" + fullUrl : fullUrl;
6237
- if (!opts.replace) {
6421
+ const liveFull = window.location.pathname + window.location.search + window.location.hash;
6422
+ if (!opts.replace && target === liveFull) {
6423
+ } else if (!opts.replace) {
6238
6424
  window.history.pushState({ path: fullUrl }, "", target);
6239
6425
  } else {
6240
6426
  window.history.replaceState({ path: fullUrl }, "", target);
@@ -20663,9 +20849,59 @@ function stripOuterQuotes(s) {
20663
20849
  function exportGetter(lines, key, valueExpr) {
20664
20850
  lines.push(`Object.defineProperty(exports, ${JSON.stringify(key)}, { get: () => ${valueExpr}, enumerable: true });`);
20665
20851
  }
20666
- function esmToCjs(body) {
20852
+ function promiseOfRequire(sourceNode) {
20853
+ return {
20854
+ type: "CallExpression",
20855
+ optional: false,
20856
+ callee: {
20857
+ type: "MemberExpression",
20858
+ optional: false,
20859
+ computed: false,
20860
+ object: {
20861
+ type: "CallExpression",
20862
+ optional: false,
20863
+ callee: {
20864
+ type: "MemberExpression",
20865
+ optional: false,
20866
+ computed: false,
20867
+ object: { type: "Identifier", name: "Promise" },
20868
+ property: { type: "Identifier", name: "resolve" }
20869
+ },
20870
+ arguments: []
20871
+ },
20872
+ property: { type: "Identifier", name: "then" }
20873
+ },
20874
+ arguments: [
20875
+ {
20876
+ type: "ArrowFunctionExpression",
20877
+ id: null,
20878
+ expression: true,
20879
+ generator: false,
20880
+ async: false,
20881
+ params: [],
20882
+ body: {
20883
+ type: "CallExpression",
20884
+ optional: false,
20885
+ callee: { type: "Identifier", name: "require" },
20886
+ arguments: [sourceNode]
20887
+ }
20888
+ }
20889
+ ]
20890
+ };
20891
+ }
20892
+ function rewriteDynamicImports(node, specs) {
20893
+ return walk2(node, null, {
20894
+ ImportExpression(n) {
20895
+ const spec = stringLiteralValue(n.source);
20896
+ if (!spec || !specs.has(spec)) return;
20897
+ return promiseOfRequire(n.source);
20898
+ }
20899
+ });
20900
+ }
20901
+ function esmToCjs(body, rewriteImports) {
20902
+ const statements = rewriteImports ? body.map((stmt) => rewriteDynamicImports(stmt, rewriteImports)) : body;
20667
20903
  const lines = [];
20668
- for (const stmt of body) {
20904
+ for (const stmt of statements) {
20669
20905
  switch (stmt.type) {
20670
20906
  case "ImportDeclaration": {
20671
20907
  const source = printNode(stmt.source);
@@ -20760,6 +20996,19 @@ function esmToCjs(body) {
20760
20996
  }
20761
20997
  return lines.join("\n");
20762
20998
  }
20999
+ function moduleKeyFor(absPath) {
21000
+ const seeds = [2166136261, 2654435761, 2246822507, 3266489909];
21001
+ let hex = "";
21002
+ for (const seed of seeds) {
21003
+ let h = seed >>> 0;
21004
+ for (let i = 0; i < absPath.length; i++) {
21005
+ h ^= absPath.charCodeAt(i);
21006
+ h = Math.imul(h, 16777619) >>> 0;
21007
+ }
21008
+ hex += h.toString(16).padStart(8, "0");
21009
+ }
21010
+ return `__veskMod${hex}`;
21011
+ }
20763
21012
  function stringLiteralValue(node) {
20764
21013
  const n = node;
20765
21014
  if (n && (n.type === "Literal" || n.type === "StringLiteral") && typeof n.value === "string") {
@@ -20770,31 +21019,40 @@ function stringLiteralValue(node) {
20770
21019
  function collectModuleSpecifiers(ast) {
20771
21020
  const specs = /* @__PURE__ */ new Set();
20772
21021
  walk2(ast, null, {
20773
- ImportDeclaration(node) {
20774
- if (node.importKind === "type") return;
20775
- const v = stringLiteralValue(node.source);
20776
- if (v) specs.add(v);
21022
+ ImportDeclaration(node, ctx2) {
21023
+ if (node.importKind !== "type") {
21024
+ const v = stringLiteralValue(node.source);
21025
+ if (v) specs.add(v);
21026
+ }
21027
+ ctx2.next();
20777
21028
  },
20778
- ExportNamedDeclaration(node) {
20779
- if (node.exportKind === "type" || !node.source) return;
20780
- const v = stringLiteralValue(node.source);
20781
- if (v) specs.add(v);
21029
+ ExportNamedDeclaration(node, ctx2) {
21030
+ if (node.exportKind !== "type" && node.source) {
21031
+ const v = stringLiteralValue(node.source);
21032
+ if (v) specs.add(v);
21033
+ }
21034
+ ctx2.next();
20782
21035
  },
20783
- ExportAllDeclaration(node) {
20784
- if (node.exportKind === "type") return;
20785
- const v = stringLiteralValue(node.source);
20786
- if (v) specs.add(v);
21036
+ ExportAllDeclaration(node, ctx2) {
21037
+ if (node.exportKind !== "type") {
21038
+ const v = stringLiteralValue(node.source);
21039
+ if (v) specs.add(v);
21040
+ }
21041
+ ctx2.next();
20787
21042
  },
20788
- CallExpression(node) {
21043
+ CallExpression(node, ctx2) {
20789
21044
  const callee = node.callee;
20790
- if (!callee || callee.type !== "Identifier" || callee.name !== "require") return;
20791
- const args2 = node.arguments || [];
20792
- const v = stringLiteralValue(args2[0]);
20793
- if (v) specs.add(v);
21045
+ if (callee && callee.type === "Identifier" && callee.name === "require") {
21046
+ const args2 = node.arguments || [];
21047
+ const v = stringLiteralValue(args2[0]);
21048
+ if (v) specs.add(v);
21049
+ }
21050
+ ctx2.next();
20794
21051
  },
20795
- ImportExpression(node) {
21052
+ ImportExpression(node, ctx2) {
20796
21053
  const v = stringLiteralValue(node.source);
20797
21054
  if (v) specs.add(v);
21055
+ ctx2.next();
20798
21056
  }
20799
21057
  });
20800
21058
  return specs;
@@ -20820,6 +21078,7 @@ function collectModuleBundled(absPath, registry) {
20820
21078
  const cached = mtimeMs >= 0 ? bundledCodeCache.get(absPath) : void 0;
20821
21079
  let code;
20822
21080
  let specifiers;
21081
+ let deps = null;
20823
21082
  if (cached && cached.mtimeMs === mtimeMs) {
20824
21083
  code = cached.code;
20825
21084
  specifiers = cached.specifiers;
@@ -20834,10 +21093,15 @@ function collectModuleBundled(absPath, registry) {
20834
21093
  if (hasTsSyntax(src2.ast)) stripped = stripTsTypes(src2.ast);
20835
21094
  stripped.body = (stripped.body || []).filter((n) => n ? !isTypeOnlyStatement(n) : false);
20836
21095
  specifiers = [...collectModuleSpecifiers(src2.ast)];
20837
- code = esmToCjs(stripped.body);
21096
+ deps = resolveBundledDeps(specifiers, dir, registry);
21097
+ code = esmToCjs(stripped.body, new Set(Object.keys(deps)));
20838
21098
  bundledCodeCache.set(absPath, { mtimeMs, code, specifiers });
20839
21099
  evict(bundledCodeCache);
20840
21100
  }
21101
+ if (!deps) deps = resolveBundledDeps(specifiers, dir, registry);
21102
+ return registry.register(absPath, { code, dir, deps });
21103
+ }
21104
+ function resolveBundledDeps(specifiers, dir, registry) {
20841
21105
  const deps = {};
20842
21106
  for (const spec of specifiers) {
20843
21107
  if (isCompilerOwnedTarget(spec) || isValueLessTarget(spec)) continue;
@@ -20845,7 +21109,7 @@ function collectModuleBundled(absPath, registry) {
20845
21109
  if (!depPath || isBuiltinPath(depPath)) continue;
20846
21110
  deps[spec] = collectModuleBundled(depPath, registry);
20847
21111
  }
20848
- return registry.register(absPath, { code, dir, deps });
21112
+ return deps;
20849
21113
  }
20850
21114
  function collectModuleBundle(importStrs, fromDir, registry, collector) {
20851
21115
  const bindings = [];
@@ -20904,13 +21168,13 @@ var init_module_imports = __esm({
20904
21168
  get size() {
20905
21169
  return this.data.size;
20906
21170
  }
20907
- /** Register a module's transpiled body, returning its globally-unique key. */
21171
+ /** Register a module's transpiled body, returning its stable key. */
20908
21172
  register(absPath, entry) {
20909
21173
  const existing2 = this.keysByAbs.get(absPath);
20910
21174
  if (existing2) return existing2;
20911
- const key = `__veskMod${this.data.size}`;
21175
+ const key = moduleKeyFor(absPath);
20912
21176
  this.keysByAbs.set(absPath, key);
20913
- this.data.set(key, entry);
21177
+ this.data.set(key, { ...entry, absPath });
20914
21178
  return key;
20915
21179
  }
20916
21180
  getModule(key) {
@@ -32277,6 +32541,7 @@ function emitNode(ctx2, node, tracked2, effectsVar, parentVar, compPrefix = "__c
32277
32541
  ctx2.push(` const __slot = createLayoutSlot(${ctx2.walker}, ${parentVar});`);
32278
32542
  ctx2.push(` const __child = props.children(__slot.walker);`);
32279
32543
  ctx2.push(` if (__child && typeof __child.then === 'function') __pendingChild = __slot.track(__child);`);
32544
+ ctx2.push(` else if (__child && __child.nodeType === 11) ${parentVar}.appendChild(__child);`);
32280
32545
  ctx2.push(` } else {`);
32281
32546
  ctx2.push(` ${parentVar}.appendChild(props.children);`);
32282
32547
  ctx2.push(` }`);
@@ -32315,6 +32580,17 @@ function emitNode(ctx2, node, tracked2, effectsVar, parentVar, compPrefix = "__c
32315
32580
  }
32316
32581
  return null;
32317
32582
  }
32583
+ function staticClassDescriptor(node) {
32584
+ const hasDynamicClass = node.children.some(
32585
+ (child) => child instanceof DynamicBinding && child.kind === "attribute" && child.target === "class"
32586
+ );
32587
+ if (hasDynamicClass) return null;
32588
+ const attr = node.attributes.find((a) => a.name === "class");
32589
+ if (!attr) return null;
32590
+ const value = attr.value.trim();
32591
+ if (!value) return null;
32592
+ return JSON.stringify({ class: value });
32593
+ }
32318
32594
  function emitStatic(ctx2, node, tracked2, effectsVar, skipK = 0, regionBudget) {
32319
32595
  const el = ctx2.n();
32320
32596
  if (ctx2.hydrate) {
@@ -32325,7 +32601,11 @@ function emitStatic(ctx2, node, tracked2, effectsVar, skipK = 0, regionBudget) {
32325
32601
  ctx2.rootClaim = false;
32326
32602
  const skipExpr = regionBudget && ctx2.markerless ? markerlessSkipExpr(regionBudget, skipK) : skipK;
32327
32603
  const skipArg = ctx2.markerless ? `, ${skipExpr}` : "";
32328
- const claimedExpr = rootClaim ? `__root || document.createElement(${JSON.stringify(node.tag)})` : `${ctx2.walker}.nextElement(${JSON.stringify(node.tag)}${skipArg})`;
32604
+ const wantsDescriptor = ctx2.markerless && ctx2.descriptorClaim;
32605
+ ctx2.descriptorClaim = false;
32606
+ const descriptor = wantsDescriptor && !rootClaim ? staticClassDescriptor(node) : null;
32607
+ const descriptorArg = descriptor ? `, ${descriptor}` : "";
32608
+ const claimedExpr = rootClaim ? `__root || document.createElement(${JSON.stringify(node.tag)})` : `${ctx2.walker}.nextElement(${JSON.stringify(node.tag)}${skipArg}${descriptorArg})`;
32329
32609
  ctx2.push(`const ${el} = ${claimedExpr};`);
32330
32610
  if (regionBudget && ctx2.markerless) ctx2.push(`${regionBudget} = 0;`);
32331
32611
  } else {
@@ -32650,6 +32930,33 @@ function emitFragment(ctx2, nodes, tracked2, effectsVar) {
32650
32930
  ctx2.push(`return $f; })();`);
32651
32931
  return frag;
32652
32932
  }
32933
+ function containsSlot(nodes) {
32934
+ for (const node of nodes) {
32935
+ if (node instanceof SlotNode) return true;
32936
+ if (node instanceof StaticNode) {
32937
+ if (containsSlot(node.children)) return true;
32938
+ } else if (node instanceof ComponentCall) {
32939
+ if (containsSlot(node.children)) return true;
32940
+ } else if (node instanceof OpaqueDynamicRegion) {
32941
+ if (containsSlot(node.consequentNodes) || containsSlot(node.alternateNodes)) return true;
32942
+ } else if (node instanceof MapRegion) {
32943
+ if (containsSlot(node.bodyTemplate) || containsSlot(node.alternateNodes)) return true;
32944
+ } else if (node instanceof WhileLoop) {
32945
+ if (containsSlot(node.bodyTemplate)) return true;
32946
+ } else if (node instanceof ForLoop) {
32947
+ if (containsSlot(node.bodyTemplate)) return true;
32948
+ } else if (node instanceof SwitchBlock) {
32949
+ for (const c of node.cases) if (containsSlot(c.body)) return true;
32950
+ } else if (node instanceof TryCatch) {
32951
+ if (containsSlot(node.bodyTemplate) || containsSlot(node.catchBody)) return true;
32952
+ } else if (node instanceof ServerBlock || node instanceof ClientBlock || node instanceof HeadBlock) {
32953
+ if (containsSlot(node.children)) return true;
32954
+ } else if (node instanceof PropSlot) {
32955
+ if (containsSlot(node.body)) return true;
32956
+ }
32957
+ }
32958
+ return false;
32959
+ }
32653
32960
  function emitComponentCall(ctx2, node, tracked2, effectsVar, parentVar, compPrefix = "__components", skipK = 0, regionBudget) {
32654
32961
  const propsEntries = node.props.map((p) => {
32655
32962
  if (typeof p.value === "string") return `${JSON.stringify(p.name)}: ${JSON.stringify(p.value)}`;
@@ -32682,6 +32989,7 @@ function emitComponentCall(ctx2, node, tracked2, effectsVar, parentVar, compPref
32682
32989
  }
32683
32990
  const callArgs = () => plainTarget ? `reactiveProps({ ${propsEntries.join(", ")} })` : `{ ${propsEntries.join(", ")} }`;
32684
32991
  if (ctx2.hydrate) {
32992
+ ctx2.descriptorClaim = false;
32685
32993
  const access = calleeExpr ?? (ctx2.importedNames.has(node.componentName) ? node.componentName : `${ctx2.hydrateRegistry}[${JSON.stringify(node.componentName)}]`);
32686
32994
  if (!calleeExpr && !ctx2.importedNames.has(node.componentName)) {
32687
32995
  ctx2.push(`if (${access} == null) throw new Error(${JSON.stringify(`Component "${node.componentName}" was not found while rendering. Declare it with the \`component\` keyword, import it, or register it in the component registry.`)});`);
@@ -32708,18 +33016,45 @@ function emitComponentCall(ctx2, node, tracked2, effectsVar, parentVar, compPref
32708
33016
  const wipeMount = ctx2.linkNames.has(node.componentName);
32709
33017
  const savedHydrate = ctx2.hydrate;
32710
33018
  if (wipeMount || ctx2.selfClaimNames.has(node.componentName)) ctx2.hydrate = false;
32711
- ctx2.push(`const ${frag} = (() => { const $f = document.createDocumentFragment();`);
32712
- const savedEffects = ctx2.effects;
32713
- ctx2.effects = [];
32714
- for (const child of regChildren) {
32715
- const childVar = emitNode(ctx2, child, tracked2, effectsVar, "$f");
32716
- if (childVar) ctx2.push(`$f.appendChild(${childVar});`);
33019
+ const lazySlotChildren = ctx2.hydrate && !plainTarget && !ctx2.selfClaimNames.has(node.componentName) && containsSlot(regChildren);
33020
+ if (lazySlotChildren) {
33021
+ const fnVar = ctx2.n();
33022
+ const savedLines = ctx2.lines;
33023
+ const savedEffects = ctx2.effects;
33024
+ const savedWalker = ctx2.walker;
33025
+ ctx2.lines = [];
33026
+ ctx2.effects = [];
33027
+ ctx2.walker = "__childWalker";
33028
+ ctx2.push(`const $f = document.createDocumentFragment();`);
33029
+ for (const child of regChildren) {
33030
+ const childVar = emitNode(ctx2, child, tracked2, effectsVar, "$f");
33031
+ if (childVar) ctx2.push(`$f.appendChild(${childVar});`);
33032
+ }
33033
+ for (const eff of ctx2.effects) ctx2.push(effectsVar ? `${effectsVar}.push(${effectBlockToHandlerExpr(eff)});` : eff);
33034
+ ctx2.push(`return $f;`);
33035
+ const body = ctx2.lines.join("\n");
33036
+ ctx2.lines = savedLines;
33037
+ ctx2.effects = savedEffects;
33038
+ ctx2.walker = savedWalker;
33039
+ const asyncKw = ctx2.isAsyncScope ? "async " : "";
33040
+ ctx2.push(`const ${fnVar} = ${asyncKw}(__childWalker) => {`);
33041
+ ctx2.push(indent2(body));
33042
+ ctx2.push(`};`);
33043
+ propsEntries.push(`children: ${fnVar}`);
33044
+ } else {
33045
+ ctx2.push(`const ${frag} = (() => { const $f = document.createDocumentFragment();`);
33046
+ const savedEffects = ctx2.effects;
33047
+ ctx2.effects = [];
33048
+ for (const child of regChildren) {
33049
+ const childVar = emitNode(ctx2, child, tracked2, effectsVar, "$f");
33050
+ if (childVar) ctx2.push(`$f.appendChild(${childVar});`);
33051
+ }
33052
+ for (const eff of ctx2.effects) ctx2.push(effectsVar ? `${effectsVar}.push(${effectBlockToHandlerExpr(eff)});` : eff);
33053
+ ctx2.effects = savedEffects;
33054
+ ctx2.push(`return $f; })();`);
33055
+ propsEntries.push(`children: ${frag}`);
32717
33056
  }
32718
- for (const eff of ctx2.effects) ctx2.push(effectsVar ? `${effectsVar}.push(${effectBlockToHandlerExpr(eff)});` : eff);
32719
- ctx2.effects = savedEffects;
32720
33057
  ctx2.hydrate = savedHydrate;
32721
- ctx2.push(`return $f; })();`);
32722
- propsEntries.push(`children: ${frag}`);
32723
33058
  }
32724
33059
  if (ctx2.markerless && promptExpr) {
32725
33060
  ctx2.push(`${walkerArg}.injectSkipK(${promptExpr});`);
@@ -32869,7 +33204,7 @@ function emitTryCatch(ctx2, node, tracked2, effectsVar, parentVar, skipK = 0, re
32869
33204
  ${effArr}.length = 0;
32870
33205
  __cleanup(${anchor}, ${endAnchor});
32871
33206
  try { ${asyncKw}${tryRenderComp}(); } catch(${catchParam}) { ${hasCatch ? `${asyncKw}${catchRenderComp}(${catchParam});` : "throw ${catchParam};"} }
32872
- });
33207
+ }, true);
32873
33208
  }`);
32874
33209
  return null;
32875
33210
  }
@@ -32877,13 +33212,14 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
32877
33212
  const hyd = ctx2.hydrate;
32878
33213
  const parent = parentVar || "$root";
32879
33214
  const budget = hyd ? regionBudgetVar(ctx2, skipK, regionBudget) : null;
33215
+ const rid = regionMarkerId(node);
32880
33216
  const isOpaque = (n) => !!n && typeof n.condition !== "undefined";
32881
33217
  if (hyd && node.alternateNodes.length === 1 && isOpaque(node.alternateNodes[0])) {
32882
33218
  const chain = [];
32883
33219
  let cur = node;
32884
33220
  let finalElse = null;
32885
33221
  while (cur) {
32886
- chain.push({ cond: transformTracked(cur.condition, tracked2), nodes: cur.consequentNodes });
33222
+ chain.push({ cond: transformTracked(cur.condition, tracked2), nodes: cur.consequentNodes, id: regionMarkerId(cur) });
32887
33223
  if (cur.alternateNodes.length === 1 && isOpaque(cur.alternateNodes[0])) {
32888
33224
  cur = cur.alternateNodes[0];
32889
33225
  } else {
@@ -32907,6 +33243,8 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
32907
33243
  ctx2.push(`const ${rn} = ${fnOpen2}`);
32908
33244
  const cl = ctx2.n();
32909
33245
  ctx2.push(indent2(`const ${cl} = [];`));
33246
+ const savedDescriptor = ctx2.descriptorClaim;
33247
+ if (hyd && ctx2.markerless) ctx2.descriptorClaim = true;
32910
33248
  for (const n of chain[i].nodes) {
32911
33249
  const savedClaim = ctx2.claimStatic;
32912
33250
  if (hyd) ctx2.claimStatic = true;
@@ -32914,6 +33252,7 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
32914
33252
  ctx2.claimStatic = savedClaim;
32915
33253
  if (v) ctx2.push(indent2(`${cl}.push(${v});`));
32916
33254
  }
33255
+ ctx2.descriptorClaim = savedDescriptor;
32917
33256
  ctx2.push(indent2(`__place(${anchor2}, ${endAnchor2}, ${cl}, ${parent});`));
32918
33257
  ctx2.push(`};`);
32919
33258
  }
@@ -32923,6 +33262,8 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
32923
33262
  ctx2.push(`const ${finalRender} = ${fnOpen2}`);
32924
33263
  const cl2 = ctx2.n();
32925
33264
  ctx2.push(indent2(`const ${cl2} = [];`));
33265
+ const savedDescriptor = ctx2.descriptorClaim;
33266
+ if (hyd && ctx2.markerless) ctx2.descriptorClaim = true;
32926
33267
  for (const n of finalElse) {
32927
33268
  const savedClaim = ctx2.claimStatic;
32928
33269
  if (hyd) ctx2.claimStatic = true;
@@ -32930,23 +33271,34 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
32930
33271
  ctx2.claimStatic = savedClaim;
32931
33272
  if (v) ctx2.push(indent2(`${cl2}.push(${v});`));
32932
33273
  }
33274
+ ctx2.descriptorClaim = savedDescriptor;
32933
33275
  ctx2.push(indent2(`__place(${anchor2}, ${endAnchor2}, ${cl2}, ${parent});`));
32934
33276
  ctx2.push(`};`);
32935
33277
  }
32936
- let init = `if (${chain[0].cond}) { ${asyncKw2}${renderNames[0]}(); }`;
32937
- for (let i = 1; i < chain.length; i++) init += ` else if (${chain[i].cond}) { ${asyncKw2}${renderNames[i]}(); }`;
32938
- if (finalRender) init += ` else { ${asyncKw2}${finalRender}(); }`;
32939
- ctx2.push(init);
32940
33278
  let branchInitFallback = finalRender ? `${chain.length}` : "-1";
32941
33279
  for (let i = chain.length - 1; i >= 0; i--) {
32942
33280
  branchInitFallback = `(${chain[i].cond} ? ${i} : ${branchInitFallback})`;
32943
33281
  }
32944
33282
  const branchInit = `(${branchInitFallback})`;
33283
+ const branchSnapshot = ctx2.n();
33284
+ ctx2.push(`const ${branchSnapshot} = ${branchInit};`);
33285
+ if (!ctx2.markerless) {
33286
+ for (let i = 0; i < chain.length; i++) {
33287
+ ctx2.push(`if (__hydrate) __reconcileRegion(${parent}, '${chain[i].id}', ${branchSnapshot} === ${i} ? 0 : 1, ${ctx2.walker});`);
33288
+ }
33289
+ } else {
33290
+ const chainBranches = chain.map((c) => c.nodes);
33291
+ if (finalElse) chainBranches.push(finalElse);
33292
+ emitStructuralRegionDiscard(ctx2, chainBranches, branchSnapshot, budget);
33293
+ }
33294
+ let init = `if (${branchSnapshot} === 0) { ${asyncKw2}${renderNames[0]}(); }`;
33295
+ for (let i = 1; i < chain.length; i++) init += ` else if (${branchSnapshot} === ${i}) { ${asyncKw2}${renderNames[i]}(); }`;
33296
+ if (finalRender) init += ` else { ${asyncKw2}${finalRender}(); }`;
33297
+ ctx2.push(init);
32945
33298
  let effInner = `if (__new === 0) { ${asyncKw2}${renderNames[0]}(); }`;
32946
33299
  for (let i = 1; i < chain.length; i++) effInner += ` else if (__new === ${i}) { ${asyncKw2}${renderNames[i]}(); }`;
32947
33300
  if (finalRender) effInner += ` else { ${asyncKw2}${finalRender}(); }`;
32948
33301
  const effBody = `effect(${ctx2.isAsyncScope ? "async () => {" : "() => {"}
32949
- if (__first) { __first = false; __iv = ${branchInit}; return; }
32950
33302
  const __new = ${branchInit};
32951
33303
  if (__new !== __iv) {
32952
33304
  for (const e of ${effectsVar2}) destroy_block(e);
@@ -32955,17 +33307,15 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
32955
33307
  ${effInner}
32956
33308
  __iv = __new;
32957
33309
  }
32958
- });`;
33310
+ }, true);`;
32959
33311
  if (effTarget) {
32960
33312
  ctx2.push(`${effTarget}.push((() => {
32961
- let __iv = ${branchInit};
32962
- let __first = true;
33313
+ let __iv = ${branchSnapshot};
32963
33314
  return ${effBody}
32964
33315
  })());`);
32965
33316
  } else {
32966
33317
  ctx2.effects.push(`{
32967
- let __iv = ${branchInit};
32968
- let __first = true;
33318
+ let __iv = ${branchSnapshot};
32969
33319
  ${effBody}
32970
33320
  }`);
32971
33321
  }
@@ -32989,6 +33339,8 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
32989
33339
  const conFrag = ctx2.n();
32990
33340
  if (!hyd) ctx2.push(indent2(`const ${conFrag} = document.createDocumentFragment();`));
32991
33341
  if (hyd) ctx2.push(indent2(`const __cl = [];`));
33342
+ const savedConDescriptor = ctx2.descriptorClaim;
33343
+ if (hyd && ctx2.markerless) ctx2.descriptorClaim = true;
32992
33344
  for (const n of node.consequentNodes) {
32993
33345
  const savedClaim = ctx2.claimStatic;
32994
33346
  if (hyd) ctx2.claimStatic = true;
@@ -32999,6 +33351,7 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
32999
33351
  else ctx2.push(indent2(`${conFrag}.appendChild(${v});`));
33000
33352
  }
33001
33353
  }
33354
+ ctx2.descriptorClaim = savedConDescriptor;
33002
33355
  if (hyd) ctx2.push(indent2(`__place(${anchor}, ${endAnchor}, __cl, ${parent});`));
33003
33356
  else ctx2.push(indent2(`__p.insertBefore(${conFrag}, ${endAnchor});`));
33004
33357
  ctx2.push(`};`);
@@ -33010,6 +33363,8 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33010
33363
  const altFrag = ctx2.n();
33011
33364
  if (!hyd) ctx2.push(indent2(`const ${altFrag} = document.createDocumentFragment();`));
33012
33365
  if (hyd) ctx2.push(indent2(`const __cl = [];`));
33366
+ const savedAltDescriptor = ctx2.descriptorClaim;
33367
+ if (hyd && ctx2.markerless) ctx2.descriptorClaim = true;
33013
33368
  for (const n of node.alternateNodes) {
33014
33369
  const savedAltClaim = ctx2.claimStatic;
33015
33370
  if (hyd) ctx2.claimStatic = true;
@@ -33020,15 +33375,19 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33020
33375
  else ctx2.push(indent2(`${altFrag}.appendChild(${v});`));
33021
33376
  }
33022
33377
  }
33378
+ ctx2.descriptorClaim = savedAltDescriptor;
33023
33379
  if (hyd) ctx2.push(indent2(`__place(${anchor}, ${endAnchor}, __cl, ${parent});`));
33024
33380
  else ctx2.push(indent2(`__p.insertBefore(${altFrag}, ${endAnchor});`));
33025
33381
  ctx2.push(`};`);
33026
33382
  }
33027
33383
  if (!hyd) ctx2.push(`${parent}.appendChild(${endAnchor});`);
33028
- ctx2.push(`if (${condExpr}) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : ""));
33384
+ const condSnapshot = ctx2.n();
33385
+ ctx2.push(`const ${condSnapshot} = ${condExpr};`);
33386
+ if (hyd && !ctx2.markerless) ctx2.push(`if (__hydrate) __reconcileRegion(${parent}, '${rid}', ${condSnapshot} ? 0 : 1, ${ctx2.walker});`);
33387
+ if (hyd && ctx2.markerless) emitStructuralRegionDiscard(ctx2, [node.consequentNodes, node.alternateNodes], hasElse ? `(${condSnapshot} ? 0 : 1)` : `(${condSnapshot} ? 0 : -1)`, budget);
33388
+ ctx2.push(`if (${condSnapshot}) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : ""));
33029
33389
  const renderBranch = `if (__nv) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : "");
33030
33390
  const effectBody = `effect(${ctx2.isAsyncScope ? "async () => {" : "() => {"}
33031
- if (__first) { __first = false; __iv = ${condExpr}; return; }
33032
33391
  const __nv = ${condExpr};
33033
33392
  if (__nv !== __iv) {
33034
33393
  for (const e of ${effectsVar}) destroy_block(e);
@@ -33037,18 +33396,16 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33037
33396
  ${renderBranch}
33038
33397
  __iv = __nv;
33039
33398
  }
33040
- });`;
33399
+ }, true);`;
33041
33400
  if (!isReactiveExpression(node.condition, tracked2)) return null;
33042
33401
  if (effTarget) {
33043
33402
  ctx2.push(`${effTarget}.push((() => {
33044
- let __iv = ${condExpr};
33045
- let __first = true;
33403
+ let __iv = ${condSnapshot};
33046
33404
  return ${effectBody}
33047
33405
  })());`);
33048
33406
  } else {
33049
33407
  ctx2.effects.push(`{
33050
- let __iv = ${condExpr};
33051
- let __first = true;
33408
+ let __iv = ${condSnapshot};
33052
33409
  ${effectBody}
33053
33410
  }`);
33054
33411
  }
@@ -33123,7 +33480,7 @@ function emitWhileLoop(ctx2, node, tracked2, parentVar, skipK = 0, regionBudget)
33123
33480
  __busy = false;
33124
33481
  __iv = (${condExpr});
33125
33482
  }
33126
- });
33483
+ }, true);
33127
33484
  }`);
33128
33485
  return null;
33129
33486
  }
@@ -33207,7 +33564,7 @@ function emitForLoop(ctx2, node, tracked2, parentVar, skipK = 0, regionBudget) {
33207
33564
  __busy = false;
33208
33565
  __iv = (${srcExpr});
33209
33566
  }
33210
- });
33567
+ }, true);
33211
33568
  }`);
33212
33569
  } else {
33213
33570
  const condReactive = isReactiveExpression(node.condition, tracked2);
@@ -33270,7 +33627,7 @@ function emitForLoop(ctx2, node, tracked2, parentVar, skipK = 0, regionBudget) {
33270
33627
  __cleanup(${anchor}, ${endAnchor});
33271
33628
  ${ctx2.isAsyncScope ? "await " : ""}${renderLoop}();
33272
33629
  __busy = false;
33273
- });
33630
+ }, true);
33274
33631
  }`);
33275
33632
  }
33276
33633
  }
@@ -33336,7 +33693,7 @@ function emitSwitchBlock(ctx2, node, tracked2, parentVar, skipK = 0, regionBudge
33336
33693
  __busy = false;
33337
33694
  __iv = (${discExpr});
33338
33695
  }
33339
- });
33696
+ }, true);
33340
33697
  }`);
33341
33698
  return null;
33342
33699
  }
@@ -33429,25 +33786,23 @@ function emitMap(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionBu
33429
33786
  let emptyRenderName = null;
33430
33787
  if (node.alternateNodes.length > 0) {
33431
33788
  emptyRenderName = ctx2.n();
33432
- const emptySig = !hyd ? ctx2.isAsyncScope ? "async () => {" : "() => {" : ctx2.isAsyncScope ? "async (__cl) => {" : "(__cl) => {";
33789
+ const emptyClaims = ctx2.hydrate;
33790
+ const emptySig = !emptyClaims ? ctx2.isAsyncScope ? "async () => {" : "() => {" : ctx2.isAsyncScope ? "async (__cl) => {" : "(__cl) => {";
33433
33791
  ctx2.push(`const ${emptyRenderName} = ${emptySig}`);
33434
33792
  ctx2.push(indent2(`const __p = ${anchor}.parentNode;`));
33435
33793
  const frag = ctx2.n();
33436
- if (!hyd) ctx2.push(indent2(`const ${frag} = document.createDocumentFragment();`));
33794
+ if (!emptyClaims) ctx2.push(indent2(`const ${frag} = document.createDocumentFragment();`));
33437
33795
  const savedClaim = ctx2.claimStatic;
33438
- const savedHydrate = ctx2.hydrate;
33439
- if (hydKeyed) ctx2.hydrate = false;
33440
33796
  for (const n of node.alternateNodes) {
33441
33797
  ctx2.claimStatic = true;
33442
- const v = emitNode(ctx2, n, tracked2, effectsVar, hyd ? void 0 : frag, "__components", 0, budget || void 0);
33798
+ const v = emitNode(ctx2, n, tracked2, effectsVar, emptyClaims ? void 0 : frag, "__components", 0, budget || void 0);
33443
33799
  if (v) {
33444
- if (hyd) ctx2.push(indent2(`if (__cl) __cl.push(${v}); else __p.insertBefore(${v}, ${endAnchor});`));
33800
+ if (emptyClaims) ctx2.push(indent2(`if (__cl) __cl.push(${v}); else __p.insertBefore(${v}, ${endAnchor});`));
33445
33801
  else ctx2.push(indent2(`${frag}.appendChild(${v});`));
33446
33802
  }
33447
33803
  }
33448
33804
  ctx2.claimStatic = savedClaim;
33449
- ctx2.hydrate = savedHydrate;
33450
- if (!hyd) ctx2.push(indent2(`if (${frag}.childNodes.length > 0) __p.insertBefore(${frag}, ${endAnchor});`));
33805
+ if (!emptyClaims) ctx2.push(indent2(`if (${frag}.childNodes.length > 0) __p.insertBefore(${frag}, ${endAnchor});`));
33451
33806
  ctx2.push(`};`);
33452
33807
  }
33453
33808
  if (!hyd && !hydKeyed) ctx2.push(`${parent}.appendChild(${endAnchor});`);
@@ -33467,8 +33822,11 @@ function emitMap(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionBu
33467
33822
  }
33468
33823
  if (emptyRenderName) {
33469
33824
  const isEmptyVar = ctx2.n();
33825
+ const collectVar = hydKeyed ? ctx2.n() : null;
33470
33826
  ctx2.push(`let ${isEmptyVar} = !${hasItems}();`);
33471
- ctx2.push(`if (!${isEmptyVar}) { ${initList}(); } else { ${aw}${emptyRenderName}(); }`);
33827
+ if (collectVar) ctx2.push(`const ${collectVar} = [];`);
33828
+ ctx2.push(`if (!${isEmptyVar}) { ${initList}(); } else { ${aw}${emptyRenderName}(${collectVar || ""}); }`);
33829
+ if (collectVar) ctx2.push(`__place(${anchor}, ${endAnchor}, ${collectVar}, ${parent});`);
33472
33830
  if (!reactiveSource) return null;
33473
33831
  pushEffect(`let __first = true;`, `effect(${effOpen}
33474
33832
  const __new = ${hasItems}();
@@ -33482,7 +33840,7 @@ function emitMap(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionBu
33482
33840
  ${effectsVar}.length = 0;
33483
33841
  __cleanup(${anchor}, ${endAnchor});
33484
33842
  if (__new) { ${initList}(); } else { ${aw}${emptyRenderName}(); }
33485
- })`);
33843
+ }, true)`);
33486
33844
  } else {
33487
33845
  ctx2.push(`${initList}();`);
33488
33846
  if (!reactiveSource) return null;
@@ -33490,7 +33848,7 @@ function emitMap(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionBu
33490
33848
  const __nv = ${arrExpr};
33491
33849
  if (__first) { __first = false; __nv; ${breakReset}${reconciler}(${arrExpr}); return; }
33492
33850
  ${breakVar ? `if (${breakVar}) ${breakVar} = false;` : ""}${reconciler}(${arrExpr});
33493
- })`);
33851
+ }, true)`);
33494
33852
  }
33495
33853
  } else {
33496
33854
  const renderAllItems = (ind, collect) => {
@@ -33539,8 +33897,8 @@ ${renderAllItems(" ", null)}
33539
33897
  __cleanup(${anchor}, ${endAnchor});
33540
33898
  if (__new) {
33541
33899
  ${renderAllItems(" ", null)}
33542
- } else { ${aw}${emptyRenderName}(${collectVar ? collectVar : ""}); }
33543
- })`);
33900
+ } else { ${aw}${emptyRenderName}(); }
33901
+ }, true)`);
33544
33902
  } else {
33545
33903
  const collectVar = hyd ? ctx2.n() : null;
33546
33904
  if (collectVar) ctx2.push(`const ${collectVar} = [];`);
@@ -33554,7 +33912,7 @@ ${renderAllItems(" ", null)}
33554
33912
  ${effectsVar}.length = 0;
33555
33913
  __cleanup(${anchor}, ${endAnchor});
33556
33914
  ${renderAllItems(" ", null)}
33557
- })`);
33915
+ }, true)`);
33558
33916
  }
33559
33917
  }
33560
33918
  return null;
@@ -33630,6 +33988,7 @@ function generateComponent(comp, importedNames = /* @__PURE__ */ new Set(), hydr
33630
33988
  }
33631
33989
  }
33632
33990
  }
33991
+ if (ctx2.hydrate && ctx2.markerless) ctx2.descriptorClaim = true;
33633
33992
  for (const node of comp.body) {
33634
33993
  if (node instanceof TrackDecl) {
33635
33994
  if (deferredTrackDecls.has(node)) emitNode(ctx2, node, tracked2, null);
@@ -33710,6 +34069,33 @@ function buildComponentMap(irRoot, hydrate = false, alloc, markerless = true) {
33710
34069
  const code = generateComponent(comp, directNames, hydrate, asyncComps, linkNames, selfClaimNames, alloc, markerless);
33711
34070
  mapLines.push(`${registry}[${JSON.stringify(comp.name)}] = ${code};`);
33712
34071
  }
34072
+ if (hydrate && !markerless) {
34073
+ mapLines.push(`function __reconcileRegion(parent, id, branch, walker) {`);
34074
+ mapLines.push(` if (!parent) return;`);
34075
+ mapLines.push(` let start = null;`);
34076
+ mapLines.push(` let end = null;`);
34077
+ mapLines.push(` for (let n = parent.firstChild; n; n = n.nextSibling) {`);
34078
+ mapLines.push(` if (n.nodeType !== 8) continue;`);
34079
+ mapLines.push(` const text = n.textContent || '';`);
34080
+ mapLines.push(` if (text === 'vesk-r:' + id + ':0' || text === 'vesk-r:' + id + ':1') start = n;`);
34081
+ mapLines.push(` else if (text === 'vesk-r-end:' + id) end = n;`);
34082
+ mapLines.push(` if (start && end) break;`);
34083
+ mapLines.push(` }`);
34084
+ mapLines.push(` if (!start || !end) return;`);
34085
+ mapLines.push(` const ssrBranch = (start.textContent || '').slice(-2) === ':1' ? 1 : 0;`);
34086
+ mapLines.push(` if (ssrBranch !== branch) {`);
34087
+ mapLines.push(` let n = start.nextSibling;`);
34088
+ mapLines.push(` while (n && n !== end) {`);
34089
+ mapLines.push(` const next = n.nextSibling;`);
34090
+ mapLines.push(` n.remove();`);
34091
+ mapLines.push(` n = next;`);
34092
+ mapLines.push(` }`);
34093
+ mapLines.push(` if (walker && walker.retireDetached) walker.retireDetached();`);
34094
+ mapLines.push(` }`);
34095
+ mapLines.push(` start.remove();`);
34096
+ mapLines.push(` end.remove();`);
34097
+ mapLines.push(`}`);
34098
+ }
33713
34099
  mapLines.push(`function __cleanup(start, end) {`);
33714
34100
  mapLines.push(` let n = start.nextSibling;`);
33715
34101
  mapLines.push(` while (n && n !== end) {`);
@@ -33768,6 +34154,43 @@ function ssrResidueEstimate(node) {
33768
34154
  }
33769
34155
  return 0;
33770
34156
  }
34157
+ function firstBranchRoot(nodes) {
34158
+ for (const n of nodes) {
34159
+ if (n instanceof StaticNode) return { tag: n.tag, descriptor: staticClassDescriptor(n) };
34160
+ if (n instanceof ComponentCall || n instanceof ComponentRef) return null;
34161
+ if (n instanceof OpaqueDynamicRegion) return null;
34162
+ if (n instanceof MapRegion || n instanceof ForLoop || n instanceof WhileLoop) {
34163
+ const child = firstBranchRoot(n.bodyTemplate);
34164
+ if (child) return child;
34165
+ }
34166
+ if (n instanceof SwitchBlock) {
34167
+ for (const c of n.cases) {
34168
+ const child = firstBranchRoot(c.body);
34169
+ if (child) return child;
34170
+ }
34171
+ }
34172
+ if (n instanceof TryCatch) {
34173
+ const child = firstBranchRoot(n.bodyTemplate) || firstBranchRoot(n.catchBody);
34174
+ if (child) return child;
34175
+ }
34176
+ }
34177
+ return null;
34178
+ }
34179
+ function structuralRegionMetadata(branches) {
34180
+ const parts = branches.map((nodes) => {
34181
+ const first = firstBranchRoot(nodes);
34182
+ const tag = first ? JSON.stringify(first.tag) : "undefined";
34183
+ const descriptor = first && first.descriptor ? first.descriptor : "null";
34184
+ return `{ tag: ${tag}, descriptor: ${descriptor}, count: ${ssrResidueEstimate(nodes)} }`;
34185
+ });
34186
+ return `[${parts.join(", ")}]`;
34187
+ }
34188
+ function emitStructuralRegionDiscard(ctx2, branches, selectedExpr, budget) {
34189
+ if (!ctx2.hydrate || !ctx2.markerless) return;
34190
+ const offset2 = budget ? `, ${budget}` : "";
34191
+ const consume = budget ? ` ${budget} = 0;` : "";
34192
+ ctx2.push(`if (${ctx2.walker} && typeof ${ctx2.walker}.discardStructuralRegion === 'function' && ${ctx2.walker}.discardStructuralRegion(${structuralRegionMetadata(branches)}, ${selectedExpr}${offset2})) {${consume}}`);
34193
+ }
33771
34194
  function isStaticIR(body) {
33772
34195
  for (const node of body) {
33773
34196
  if (node instanceof StaticNode) {
@@ -34098,6 +34521,10 @@ var init_client_codegen = __esm({
34098
34521
  markerless = true;
34099
34522
  inTryBody = false;
34100
34523
  claimStatic = false;
34524
+ // Markerless only: the next real claim carries a compiler-generated static
34525
+ // class descriptor so a same-tag but structurally different SSR slot is
34526
+ // substituted instead of adopted (e.g. an empty-state <div> vs a list <div>).
34527
+ descriptorClaim = false;
34101
34528
  // While set, the next StaticNode claimed in hydrate mode uses `__root` (the
34102
34529
  // item element already claimed by key) instead of walking for a new element.
34103
34530
  rootClaim = false;
@@ -34949,15 +35376,19 @@ function dynamicBindingToJS(node, tracked2) {
34949
35376
  function opaqueRegionToJS(node, isAsync = false, tracked2) {
34950
35377
  const lines = [];
34951
35378
  const cond = exprJSX(node.condition, tracked2);
35379
+ const rid = regionMarkerId(node);
35380
+ const mark = __vskHydrate && !__vskMarkerless;
34952
35381
  lines.push(`if (${cond}) {`);
35382
+ if (mark) lines.push(indent(`__out.push('<!--vesk-r:${rid}:0-->');`));
34953
35383
  setVskForceClaim(true);
34954
35384
  for (const n of node.consequentNodes) {
34955
35385
  const code = irNodeToJS(n, null, isAsync, tracked2);
34956
35386
  if (code) lines.push(indent(code));
34957
35387
  }
34958
35388
  setVskForceClaim(false);
35389
+ lines.push(`} else {`);
35390
+ if (mark) lines.push(indent(`__out.push('<!--vesk-r:${rid}:1-->');`));
34959
35391
  if (node.alternateNodes.length > 0) {
34960
- lines.push(`} else {`);
34961
35392
  setVskForceClaim(true);
34962
35393
  for (const n of node.alternateNodes) {
34963
35394
  const code = irNodeToJS(n, null, isAsync, tracked2);
@@ -34966,6 +35397,7 @@ function opaqueRegionToJS(node, isAsync = false, tracked2) {
34966
35397
  setVskForceClaim(false);
34967
35398
  }
34968
35399
  lines.push(`}`);
35400
+ if (mark) lines.push(`__out.push('<!--vesk-r-end:${rid}-->');`);
34969
35401
  return lines.join("\n");
34970
35402
  }
34971
35403
  function mapRegionToJS(node, isAsync = false, tracked2) {
@@ -36173,6 +36605,129 @@ var init_default_pages = __esm({
36173
36605
  }
36174
36606
  });
36175
36607
 
36608
+ // ../adapter/src/server-only.ts
36609
+ import { readFileSync as readFileSync11, readdirSync as readdirSync2, statSync as statSync3 } from "node:fs";
36610
+ import { join as join7 } from "node:path";
36611
+ function tcpDriverPackages() {
36612
+ return [...TCP_DRIVERS].filter((spec) => !spec.startsWith("node:"));
36613
+ }
36614
+ function classifySpecifier(spec) {
36615
+ if (typeof spec !== "string" || spec.length === 0) return null;
36616
+ if (TCP_DRIVERS.has(spec)) return "tcp-driver";
36617
+ if (spec.startsWith("node:")) return "tcp-driver";
36618
+ if (SERVER_ONLY_EXACT.has(spec)) return "server-only-package";
36619
+ return null;
36620
+ }
36621
+ function scanServerOnlyImports(files) {
36622
+ const out = [];
36623
+ for (const file of files) {
36624
+ let ast;
36625
+ try {
36626
+ ast = parse4(file.code);
36627
+ } catch {
36628
+ continue;
36629
+ }
36630
+ for (const node of ast.body ?? []) {
36631
+ if (node?.type !== "ImportDeclaration" && node?.type !== "ExportNamedDeclaration" && node?.type !== "ExportAllDeclaration") continue;
36632
+ const spec = node.source?.value;
36633
+ if (typeof spec !== "string") continue;
36634
+ const kind = classifySpecifier(spec);
36635
+ if (!kind) continue;
36636
+ out.push({
36637
+ kind,
36638
+ specifier: spec,
36639
+ file: file.path,
36640
+ line: lineOf(file.code, node.start),
36641
+ remedy: REMEDY[kind]
36642
+ });
36643
+ }
36644
+ }
36645
+ return out;
36646
+ }
36647
+ function lineOf(code, offset2) {
36648
+ if (typeof offset2 !== "number" || offset2 < 0 || offset2 > code.length) return null;
36649
+ let line = 1;
36650
+ for (let i = 0; i < offset2; i++) {
36651
+ if (code.charCodeAt(i) === 10) line++;
36652
+ }
36653
+ return line;
36654
+ }
36655
+ function edgeDriverBuildError(violations) {
36656
+ const detail = violations.map((v) => ` ${v.file}${v.line ? `:${v.line}` : ""} \u2014 import "${v.specifier}"
36657
+ ${v.remedy}`).join("\n");
36658
+ return new Error(
36659
+ `[vesk] edge-targeted build cannot include a TCP-only driver (${violations.length} found).
36660
+ ${detail}
36661
+
36662
+ This was a build error rather than a runtime one because an edge runtime has no socket: the deployed function would fail on its first query.`
36663
+ );
36664
+ }
36665
+ function isSocketlessTarget(platform, target) {
36666
+ if (target === "edge") return true;
36667
+ return typeof platform === "string" && SOCKETLESS_PLATFORMS.has(platform);
36668
+ }
36669
+ function collectAppSources(dir, out = []) {
36670
+ let entries;
36671
+ try {
36672
+ entries = readdirSync2(dir);
36673
+ } catch {
36674
+ return out;
36675
+ }
36676
+ for (const entry of entries) {
36677
+ if (SKIPPED_DIRS.has(entry) || entry.startsWith(".")) continue;
36678
+ const full = join7(dir, entry);
36679
+ let st;
36680
+ try {
36681
+ st = statSync3(full);
36682
+ } catch {
36683
+ continue;
36684
+ }
36685
+ if (st.isDirectory()) collectAppSources(full, out);
36686
+ else if (st.isFile()) {
36687
+ const dot = entry.lastIndexOf(".");
36688
+ if (dot === -1) continue;
36689
+ if (SOURCE_EXTENSIONS.includes(entry.slice(dot).toLowerCase())) out.push(full);
36690
+ }
36691
+ }
36692
+ return out;
36693
+ }
36694
+ function tcpDriverViolations(appDir) {
36695
+ const files = [];
36696
+ for (const path of collectAppSources(appDir)) {
36697
+ try {
36698
+ files.push({ path, code: readFileSync11(path, "utf-8") });
36699
+ } catch {
36700
+ }
36701
+ }
36702
+ return scanServerOnlyImports(files).filter((v) => v.kind === "tcp-driver");
36703
+ }
36704
+ var SERVER_ONLY_EXACT, TCP_DRIVERS, REMEDY, SOCKETLESS_PLATFORMS, SOURCE_EXTENSIONS, SKIPPED_DIRS;
36705
+ var init_server_only = __esm({
36706
+ "../adapter/src/server-only.ts"() {
36707
+ "use strict";
36708
+ init_parser();
36709
+ SERVER_ONLY_EXACT = /* @__PURE__ */ new Set([
36710
+ "slintorm",
36711
+ "@vesk/adapter"
36712
+ ]);
36713
+ TCP_DRIVERS = /* @__PURE__ */ new Set([
36714
+ "pg",
36715
+ "mysql2",
36716
+ "mongodb",
36717
+ "node:sqlite",
36718
+ "node:net",
36719
+ "node:tls"
36720
+ ]);
36721
+ REMEDY = {
36722
+ "server-only-package": "import it from an API route (app/api/**/route.ts) or a server action instead of a component, or use the package's browser/edge entry point if it ships one.",
36723
+ "tcp-driver": 'this driver opens a TCP socket, which no edge runtime provides. Use the driver\'s HTTP/HTTPS transport (for SlintORM: `driver: "postgrest"`), or build for a Node target.'
36724
+ };
36725
+ SOCKETLESS_PLATFORMS = /* @__PURE__ */ new Set(["edge", "cloudflare", "deno", "coxmos"]);
36726
+ SOURCE_EXTENSIONS = [".vsk", ".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
36727
+ SKIPPED_DIRS = /* @__PURE__ */ new Set(["node_modules", ".vesk", ".git", "dist", ".next", ".output", "coverage"]);
36728
+ }
36729
+ });
36730
+
36176
36731
  // ../adapter/src/paths.ts
36177
36732
  import { resolve as resolve11, sep as sep2 } from "node:path";
36178
36733
  import { existsSync as existsSync12, statSync as statSync5, readFileSync as readFileSync14 } from "node:fs";
@@ -38149,11 +38704,12 @@ export const execSync = () => '';
38149
38704
  }
38150
38705
  });
38151
38706
  }
38707
+ const qrStubPattern = nodeBuiltins ? /^(canvas|@zxing\/(browser|node))(\/|$)/ : /^(vesk-qr|qrcode-generator|canvas|@zxing\/(browser|node))(\/|$)/;
38152
38708
  plugins.push({
38153
- name: "stub-edge-packages",
38709
+ name: "stub-optional-qr-packages",
38154
38710
  setup(build5) {
38155
38711
  build5.onResolve(
38156
- { filter: /^(vesk-qr|qrcode-generator|canvas|@zxing\/(browser|node))(\/|$)/ },
38712
+ { filter: qrStubPattern },
38157
38713
  (args2) => ({ path: args2.path, namespace: "vesk-edge-stub" })
38158
38714
  );
38159
38715
  build5.onLoad({ filter: /.*/, namespace: "vesk-edge-stub" }, () => ({
@@ -38229,10 +38785,50 @@ var init_platform_handler = __esm({
38229
38785
  // ../adapter/src/platform-deploy.ts
38230
38786
  var platform_deploy_exports = {};
38231
38787
  __export(platform_deploy_exports, {
38232
- emitPlatformOutput: () => emitPlatformOutput
38788
+ emitPlatformOutput: () => emitPlatformOutput,
38789
+ shipNodeDriverClosures: () => shipNodeDriverClosures,
38790
+ vercelBootstrapSource: () => vercelBootstrapSource
38233
38791
  });
38234
- import { writeFileSync as writeFileSync11, mkdirSync as mkdirSync10, rmSync as rmSync3, cpSync } from "node:fs";
38235
- import { resolve as resolve20 } from "node:path";
38792
+ import { writeFileSync as writeFileSync11, mkdirSync as mkdirSync10, rmSync as rmSync3, cpSync, readFileSync as readFileSync23, existsSync as existsSync22 } from "node:fs";
38793
+ import { resolve as resolve20, dirname as dirname16, relative as relative3 } from "node:path";
38794
+ function resolveInstalledPackage(projectRoot, name) {
38795
+ let dir = projectRoot;
38796
+ while (true) {
38797
+ const candidate = resolve20(dir, "node_modules", name);
38798
+ if (existsSync22(resolve20(candidate, "package.json"))) return candidate;
38799
+ const parent = dirname16(dir);
38800
+ if (parent === dir) return null;
38801
+ dir = parent;
38802
+ }
38803
+ }
38804
+ function shipNodeDriverClosures(projectRoot, funcDir) {
38805
+ const destModules = resolve20(funcDir, "node_modules");
38806
+ const seen = /* @__PURE__ */ new Set();
38807
+ const queue = tcpDriverPackages();
38808
+ while (queue.length > 0) {
38809
+ const name = queue.shift();
38810
+ if (seen.has(name)) continue;
38811
+ seen.add(name);
38812
+ const pkgDir = resolveInstalledPackage(projectRoot, name);
38813
+ if (!pkgDir) continue;
38814
+ const dest = resolve20(destModules, name);
38815
+ mkdirSync10(dirname16(dest), { recursive: true });
38816
+ cpSync(pkgDir, dest, {
38817
+ recursive: true,
38818
+ filter: (src2) => !relative3(pkgDir, src2).split(/[\\/]/).includes("node_modules")
38819
+ });
38820
+ let pkg = {};
38821
+ try {
38822
+ pkg = JSON.parse(readFileSync23(resolve20(pkgDir, "package.json"), "utf-8"));
38823
+ } catch {
38824
+ }
38825
+ const deps = {
38826
+ ...pkg.dependencies || {},
38827
+ ...pkg.optionalDependencies || {}
38828
+ };
38829
+ for (const dep of Object.keys(deps)) queue.push(dep);
38830
+ }
38831
+ }
38236
38832
  async function emitPlatformOutput(platform, ctx2) {
38237
38833
  if (platform === "node") return null;
38238
38834
  const prerenderedPaths = ctx2.prerenderedRoutes.map((r) => r.path);
@@ -38277,6 +38873,7 @@ ${shell.bootstrap}
38277
38873
  }
38278
38874
  handlerRel = `${shell.functionFile.dir}/${shell.functionFile.file}`;
38279
38875
  await bundlePlatformHandler({ entry, outfile: resolve20(funcDir, shell.functionFile.file), nodeBuiltins: shell.nodeBuiltins });
38876
+ if (shell.nodeBuiltins) shipNodeDriverClosures(projectRoot, funcDir);
38280
38877
  } else {
38281
38878
  handlerRel = shell.outfile || "index.js";
38282
38879
  await bundlePlatformHandler({ entry, outfile: resolve20(outRoot, handlerRel), nodeBuiltins: shell.nodeBuiltins });
@@ -38396,6 +38993,34 @@ function serveEmbeddedStatic(request) {
38396
38993
  return null;
38397
38994
  }`;
38398
38995
  }
38996
+ function vercelBootstrapSource() {
38997
+ return [
38998
+ "export default async function veskNodeEntry(req, res) {",
38999
+ " const __fwdHost = String(req.headers['x-forwarded-host'] || '').split(',')[0].trim();",
39000
+ " const __host = __fwdHost || req.headers.host || 'localhost';",
39001
+ " const __fwdProto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim();",
39002
+ " const __local = __host === 'localhost' || __host.startsWith('127.') || __host === '[::1]';",
39003
+ " const __proto = __fwdProto || (__local ? 'http' : 'https');",
39004
+ " const url = new URL(req.url, `${__proto}://${__host}`);",
39005
+ " const method = req.method || 'GET';",
39006
+ " let body;",
39007
+ " if (method !== 'GET' && method !== 'HEAD') {",
39008
+ " body = await new Promise((resolveBody, reject) => {",
39009
+ " const chunks = [];",
39010
+ " req.on('data', (c) => chunks.push(c));",
39011
+ ' req.on("error", reject);',
39012
+ ' req.on("end", () => resolveBody(Buffer.concat(chunks)));',
39013
+ " });",
39014
+ " }",
39015
+ " const headers = {};",
39016
+ " for (const key in req.headers) headers[key] = req.headers[key];",
39017
+ " const request = new Request(url, { method, headers, body });",
39018
+ " const response = await handleRequest(request);",
39019
+ " res.writeHead(response.status, Object.fromEntries(response.headers));",
39020
+ " res.end(await response.text());",
39021
+ "}"
39022
+ ].join("\n");
39023
+ }
38399
39024
  function shellFor(platform) {
38400
39025
  switch (platform) {
38401
39026
  case "vercel":
@@ -38416,27 +39041,7 @@ function shellFor(platform) {
38416
39041
  shouldAddSourcemapSupport: false,
38417
39042
  supportsResponseStreaming: true
38418
39043
  },
38419
- bootstrap: [
38420
- "export default async function veskNodeEntry(req, res) {",
38421
- " const url = new URL(req.url, 'http://' + (req.headers.host || 'localhost'));",
38422
- " const method = req.method || 'GET';",
38423
- " let body;",
38424
- " if (method !== 'GET' && method !== 'HEAD') {",
38425
- " body = await new Promise((resolveBody, reject) => {",
38426
- " const chunks = [];",
38427
- " req.on('data', (c) => chunks.push(c));",
38428
- ' req.on("error", reject);',
38429
- ' req.on("end", () => resolveBody(Buffer.concat(chunks)));',
38430
- " });",
38431
- " }",
38432
- " const headers = {};",
38433
- " for (const key in req.headers) headers[key] = req.headers[key];",
38434
- " const request = new Request(url, { method, headers, body });",
38435
- " const response = await handleRequest(request);",
38436
- " res.writeHead(response.status, Object.fromEntries(response.headers));",
38437
- " res.end(await response.text());",
38438
- "}"
38439
- ].join("\n")
39044
+ bootstrap: vercelBootstrapSource()
38440
39045
  };
38441
39046
  case "netlify":
38442
39047
  return {
@@ -38579,6 +39184,7 @@ var init_platform_deploy = __esm({
38579
39184
  "use strict";
38580
39185
  init_platform_handler();
38581
39186
  init_platform_output();
39187
+ init_server_only();
38582
39188
  }
38583
39189
  });
38584
39190
 
@@ -49527,20 +50133,16 @@ interface VeskLocals<T extends object> {
49527
50133
  all(): T;
49528
50134
  }
49529
50135
  declare function createLocals<T extends object = Record<string, unknown>>(): VeskLocals<T>;
49530
- // useFetch returns a THENABLE resource, not the data itself. In async
49531
- // components you must \`await\` it before reading/iterating the payload;
49532
- // passing \`into: <tracked cell>\` writes the payload into the cell and makes
49533
- // awaiting unnecessary (the return value can be ignored).
49534
- interface VeskResource<T> {
50136
+ // useFetch returns a real Promise carrying resource state. In async components
50137
+ // you must \`await\` it before reading/iterating the payload; passing
50138
+ // \`into: <tracked cell>\` writes the payload into the cell and makes awaiting
50139
+ // unnecessary (the return value can be ignored).
50140
+ interface VeskResource<T> extends Promise<T> {
49535
50141
  loading: boolean;
49536
50142
  error: unknown;
49537
50143
  data: T | undefined;
49538
50144
  refresh(): void;
49539
50145
  abort(): void;
49540
- then<TResult1 = T, TResult2 = never>(
49541
- onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
49542
- onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null,
49543
- ): PromiseLike<TResult1 | TResult2>;
49544
50146
  }
49545
50147
  interface VeskUseFetchOptions<T> {
49546
50148
  /** Cache/SSR key \u2014 defaults to the URL string. */
@@ -49659,7 +50261,7 @@ __export(codemods_exports, {
49659
50261
  applicableCodemods: () => applicableCodemods,
49660
50262
  compareCore: () => compareCore
49661
50263
  });
49662
- import { readFileSync as readFileSync44, existsSync as existsSync44 } from "node:fs";
50264
+ import { readFileSync as readFileSync44, existsSync as existsSync45 } from "node:fs";
49663
50265
  import { join as join30 } from "node:path";
49664
50266
  import { walk as walk8 } from "zimmerframe";
49665
50267
  function safeParse(source, filePath) {
@@ -49682,7 +50284,7 @@ function typesPackageExports(projectDir) {
49682
50284
  const candidates = [
49683
50285
  projectDir ? join30(projectDir, "node_modules", "@vesk", "types", "dist", "index.d.ts") : null,
49684
50286
  new URL("../../types/dist/index.d.ts", import.meta.url).pathname
49685
- ].filter((p) => typeof p === "string" && existsSync44(p));
50287
+ ].filter((p) => typeof p === "string" && existsSync45(p));
49686
50288
  for (const path of candidates) {
49687
50289
  try {
49688
50290
  const src2 = readFileSync44(path, "utf-8");
@@ -49809,12 +50411,12 @@ __export(migrate_exports, {
49809
50411
  detectInstalledVersion: () => detectInstalledVersion,
49810
50412
  runMigrate: () => runMigrate
49811
50413
  });
49812
- import { readFileSync as readFileSync45, writeFileSync as writeFileSync22, existsSync as existsSync45, statSync as statSync24, readdirSync as readdirSync16 } from "node:fs";
50414
+ import { readFileSync as readFileSync45, writeFileSync as writeFileSync22, existsSync as existsSync46, statSync as statSync24, readdirSync as readdirSync16 } from "node:fs";
49813
50415
  import { join as join31, relative as relative11, extname as extname8 } from "node:path";
49814
50416
  function detectInstalledVersion(projectDir, cliVersion) {
49815
50417
  for (const pkg of ["@vesk/vesk-cli", "@vesk/adapter", "@vesk/compiler"]) {
49816
50418
  const p = join31(projectDir, "node_modules", pkg, "package.json");
49817
- if (!existsSync45(p)) continue;
50419
+ if (!existsSync46(p)) continue;
49818
50420
  try {
49819
50421
  const version2 = JSON.parse(readFileSync45(p, "utf-8")).version;
49820
50422
  if (typeof version2 === "string" && version2) return { version: version2, source: pkg };
@@ -49870,7 +50472,7 @@ function runMigrate(options) {
49870
50472
  for (const relPath of collectTargets(options.projectDir)) {
49871
50473
  const abs = join31(options.projectDir, relPath);
49872
50474
  const ctx2 = { filePath: abs, displayPath: relPath, projectDir: options.projectDir };
49873
- if (!existsSync45(abs)) continue;
50475
+ if (!existsSync46(abs)) continue;
49874
50476
  let source;
49875
50477
  try {
49876
50478
  source = readFileSync45(abs, "utf-8");
@@ -49913,7 +50515,7 @@ var init_migrate = __esm({
49913
50515
  });
49914
50516
 
49915
50517
  // src/index.ts
49916
- import { readFileSync as readFileSync46, writeFileSync as writeFileSync23, mkdirSync as mkdirSync20, existsSync as existsSync46 } from "fs";
50518
+ import { readFileSync as readFileSync46, writeFileSync as writeFileSync23, mkdirSync as mkdirSync20, existsSync as existsSync47 } from "fs";
49917
50519
  import { resolve as resolve41, join as join32 } from "path";
49918
50520
  import { fileURLToPath as fileURLToPath9 } from "url";
49919
50521
  import { createRequire as createRequire8 } from "module";
@@ -50494,7 +51096,7 @@ function setRuntimeModule2(mod) {
50494
51096
  }
50495
51097
 
50496
51098
  // ../adapter/dist/index.js
50497
- import { mkdirSync as mkdirSync11, writeFileSync as writeFileSync12, existsSync as existsSync22, readFileSync as readFileSync24 } from "node:fs";
51099
+ import { mkdirSync as mkdirSync11, writeFileSync as writeFileSync12, existsSync as existsSync23, readFileSync as readFileSync24 } from "node:fs";
50498
51100
  import { resolve as resolve21, dirname as dirname17, relative as relative4, basename as basename3, join as join16 } from "node:path";
50499
51101
  import { fileURLToPath as fileURLToPath5 } from "node:url";
50500
51102
 
@@ -50801,12 +51403,33 @@ function precompileFile(source, sourcePath2, registry) {
50801
51403
  const reg = registry ?? new ModuleRegistry();
50802
51404
  if (sourcePath2 === void 0) return precompileFileInternal(source, sourcePath2, /* @__PURE__ */ new Set(), reg);
50803
51405
  const hit = precompileCache.get(sourcePath2);
50804
- if (hit !== void 0 && hit.source === source) return hit.plan;
51406
+ if (hit !== void 0 && hit.source === source) {
51407
+ for (const { absPath, entry } of hit.modules) reg.register(absPath, entry);
51408
+ return hit.plan;
51409
+ }
50805
51410
  const plan = precompileFileInternal(source, sourcePath2, /* @__PURE__ */ new Set(), reg);
50806
51411
  if (precompileCache.size >= 512) precompileCache.clear();
50807
- precompileCache.set(sourcePath2, { source, plan });
51412
+ precompileCache.set(sourcePath2, { source, plan, modules: collectPlanModules(plan, reg) });
50808
51413
  return plan;
50809
51414
  }
51415
+ function collectPlanModules(plan, registry) {
51416
+ const out = [];
51417
+ const seen = /* @__PURE__ */ new Set();
51418
+ const visitKey = (key) => {
51419
+ if (seen.has(key)) return;
51420
+ seen.add(key);
51421
+ const entry = registry.getModule(key);
51422
+ if (!entry || !entry.absPath) return;
51423
+ out.push({ absPath: entry.absPath, entry });
51424
+ for (const depKey of Object.values(entry.deps)) visitKey(depKey);
51425
+ };
51426
+ const visitPlan = (p) => {
51427
+ for (const mod of p.modules) visitKey(mod.key);
51428
+ for (const sub of p.subFiles) visitPlan(sub.plan);
51429
+ };
51430
+ visitPlan(plan);
51431
+ return out;
51432
+ }
50810
51433
  var precompileCache = /* @__PURE__ */ new Map();
50811
51434
  function precompileFileInternal(source, sourcePath2, seenImportFiles, registry) {
50812
51435
  if (sourcePath2) {
@@ -51286,7 +51909,10 @@ function __getNotFoundCompiled() { if (!_notFoundCompiled) _notFoundCompiled = $
51286
51909
  " }"
51287
51910
  ];
51288
51911
  const dataNavWrap = (body) => [
51289
- " return withSsrStore(async () => {",
51912
+ // Awaited for the same reason as the main render below: the caller restores
51913
+ // `__vesk_request` in a finally, and that must happen only after the async
51914
+ // data render (which reads params through useParams) has fully resolved.
51915
+ " return await withSsrStore(async () => {",
51290
51916
  ...body.map((l) => l ? " " + l : l),
51291
51917
  " });"
51292
51918
  ];
@@ -51314,7 +51940,13 @@ function __getNotFoundCompiled() { if (!_notFoundCompiled) _notFoundCompiled = $
51314
51940
  ...dataNavCleanup
51315
51941
  ]),
51316
51942
  " }",
51317
- " return __renderHtml(params, url.href);"
51943
+ // Awaited so the surrounding try/finally keeps `__vesk_request` installed
51944
+ // for the whole async render. Without the await the finally restores the
51945
+ // previous context synchronously, while the async page body is still
51946
+ // suspended on its SSR fetches; every render pass after the first `await`
51947
+ // then reads an empty params object and `useParams()`-derived keys/URLs
51948
+ // collapse (e.g. a verify page rendering its not-found branch).
51949
+ " return await __renderHtml(params, url.href);"
51318
51950
  ].join("\n");
51319
51951
  } else {
51320
51952
  dataCode = [
@@ -51335,7 +51967,13 @@ function __getNotFoundCompiled() { if (!_notFoundCompiled) _notFoundCompiled = $
51335
51967
  ...dataNavCleanup
51336
51968
  ]),
51337
51969
  " }",
51338
- " return __renderHtml(params, url.href);"
51970
+ // Awaited so the surrounding try/finally keeps `__vesk_request` installed
51971
+ // for the whole async render. Without the await the finally restores the
51972
+ // previous context synchronously, while the async page body is still
51973
+ // suspended on its SSR fetches; every render pass after the first `await`
51974
+ // then reads an empty params object and `useParams()`-derived keys/URLs
51975
+ // collapse (e.g. a verify page rendering its not-found branch).
51976
+ " return await __renderHtml(params, url.href);"
51339
51977
  ].join("\n");
51340
51978
  }
51341
51979
  const hasMiddleware = !!middlewareCode;
@@ -51830,8 +52468,18 @@ function extractMiddlewareParts(src2) {
51830
52468
  decls.push(src2.slice(stmt.declaration.start, stmt.declaration.end).trim());
51831
52469
  }
51832
52470
  }
52471
+ const imports = [];
52472
+ for (const stmt of ast.body) {
52473
+ if (stmt.type !== "ImportDeclaration") continue;
52474
+ if (stmt.importKind === "type") continue;
52475
+ const source = stmt.source?.value;
52476
+ if (typeof source !== "string") continue;
52477
+ if (source.startsWith(".") || source.startsWith("/")) continue;
52478
+ const line = src2.slice(stmt.start, stmt.end).trim();
52479
+ if (line && !imports.includes(line)) imports.push(line);
52480
+ }
51833
52481
  const bodyWithDecls = decls.length > 0 ? decls.join("\n") + "\n" + body.trim() : body.trim();
51834
- return { params, body: bodyWithDecls };
52482
+ return { params, body: bodyWithDecls, imports };
51835
52483
  } catch {
51836
52484
  return fallbackExtractMiddleware(src2);
51837
52485
  }
@@ -51872,7 +52520,7 @@ function fallbackExtractMiddleware(src2) {
51872
52520
  m++;
51873
52521
  }
51874
52522
  const body = src2.slice(b + 1, m - 1);
51875
- return { params, body: body.trim() };
52523
+ return { params, body: body.trim(), imports: [] };
51876
52524
  }
51877
52525
  return null;
51878
52526
  }
@@ -51894,16 +52542,18 @@ ${parts.body}
51894
52542
  function extractMiddlewareBody(src2) {
51895
52543
  const parts = extractMiddlewareParts(src2);
51896
52544
  if (!parts) return null;
51897
- return { params: parts.params, body: parts.body };
52545
+ return { params: parts.params, body: parts.body, imports: parts.imports };
51898
52546
  }
51899
52547
  function compileMiddleware(mwChain, _appDir) {
51900
52548
  if (mwChain.length === 0) return null;
51901
52549
  const parts = [];
52550
+ const imports = [];
51902
52551
  for (let i = 0; i < mwChain.length; i++) {
51903
52552
  const { sourcePath: sourcePath2 } = mwChain[i];
51904
52553
  const src2 = readFileSync10(sourcePath2, "utf-8");
51905
52554
  const extracted = extractMiddlewareBody(src2);
51906
52555
  if (!extracted) continue;
52556
+ for (const line of extracted.imports) if (!imports.includes(line)) imports.push(line);
51907
52557
  parts.push(`async function mw_${i}(${extracted.params}) {
51908
52558
  ${extracted.body}
51909
52559
  }`);
@@ -51912,6 +52562,8 @@ ${extracted.body}
51912
52562
  const code = [
51913
52563
  "// Auto-generated middleware chain \u2014 do not edit",
51914
52564
  "",
52565
+ ...imports,
52566
+ ...imports.length ? [""] : [],
51915
52567
  parts.join("\n\n"),
51916
52568
  "",
51917
52569
  `const chain = [${parts.map((_, i) => `mw_${i}`).join(", ")}];`,
@@ -51981,9 +52633,11 @@ ${extracted.body}
51981
52633
  function compileMiddlewareCode(mwSourceTexts) {
51982
52634
  if (!mwSourceTexts || mwSourceTexts.length === 0) return null;
51983
52635
  const parts = [];
52636
+ const imports = [];
51984
52637
  for (let i = 0; i < mwSourceTexts.length; i++) {
51985
52638
  const extracted = extractMiddlewareBody(mwSourceTexts[i]);
51986
52639
  if (!extracted) continue;
52640
+ for (const line of extracted.imports) if (!imports.includes(line)) imports.push(line);
51987
52641
  parts.push(`async function mw_${i}(${extracted.params}) {
51988
52642
  ${extracted.body}
51989
52643
  }`);
@@ -51992,6 +52646,8 @@ ${extracted.body}
51992
52646
  const code = [
51993
52647
  "// \u2500\u2500 Middleware chain (inline) \u2500\u2500",
51994
52648
  "",
52649
+ ...imports,
52650
+ ...imports.length ? [""] : [],
51995
52651
  parts.join("\n\n"),
51996
52652
  "",
51997
52653
  `const __mwChain = [${parts.map((_, i) => `mw_${i}`).join(", ")}];`,
@@ -52192,123 +52848,8 @@ init_module_imports();
52192
52848
 
52193
52849
  // ../adapter/src/server-only-plugin.ts
52194
52850
  init_parser();
52851
+ init_server_only();
52195
52852
  import { readFileSync as readFileSync12 } from "node:fs";
52196
-
52197
- // ../adapter/src/server-only.ts
52198
- init_parser();
52199
- import { readFileSync as readFileSync11, readdirSync as readdirSync2, statSync as statSync3 } from "node:fs";
52200
- import { join as join7 } from "node:path";
52201
- var SERVER_ONLY_EXACT = /* @__PURE__ */ new Set([
52202
- "slintorm",
52203
- "@vesk/adapter"
52204
- ]);
52205
- var TCP_DRIVERS = /* @__PURE__ */ new Set([
52206
- "pg",
52207
- "mysql2",
52208
- "mongodb",
52209
- "node:sqlite",
52210
- "node:net",
52211
- "node:tls"
52212
- ]);
52213
- function classifySpecifier(spec) {
52214
- if (typeof spec !== "string" || spec.length === 0) return null;
52215
- if (TCP_DRIVERS.has(spec)) return "tcp-driver";
52216
- if (spec.startsWith("node:")) return "tcp-driver";
52217
- if (SERVER_ONLY_EXACT.has(spec)) return "server-only-package";
52218
- return null;
52219
- }
52220
- var REMEDY = {
52221
- "server-only-package": "import it from an API route (app/api/**/route.ts) or a server action instead of a component, or use the package's browser/edge entry point if it ships one.",
52222
- "tcp-driver": 'this driver opens a TCP socket, which no edge runtime provides. Use the driver\'s HTTP/HTTPS transport (for SlintORM: `driver: "postgrest"`), or build for a Node target.'
52223
- };
52224
- function scanServerOnlyImports(files) {
52225
- const out = [];
52226
- for (const file of files) {
52227
- let ast;
52228
- try {
52229
- ast = parse4(file.code);
52230
- } catch {
52231
- continue;
52232
- }
52233
- for (const node of ast.body ?? []) {
52234
- if (node?.type !== "ImportDeclaration" && node?.type !== "ExportNamedDeclaration" && node?.type !== "ExportAllDeclaration") continue;
52235
- const spec = node.source?.value;
52236
- if (typeof spec !== "string") continue;
52237
- const kind = classifySpecifier(spec);
52238
- if (!kind) continue;
52239
- out.push({
52240
- kind,
52241
- specifier: spec,
52242
- file: file.path,
52243
- line: lineOf(file.code, node.start),
52244
- remedy: REMEDY[kind]
52245
- });
52246
- }
52247
- }
52248
- return out;
52249
- }
52250
- function lineOf(code, offset2) {
52251
- if (typeof offset2 !== "number" || offset2 < 0 || offset2 > code.length) return null;
52252
- let line = 1;
52253
- for (let i = 0; i < offset2; i++) {
52254
- if (code.charCodeAt(i) === 10) line++;
52255
- }
52256
- return line;
52257
- }
52258
- function edgeDriverBuildError(violations) {
52259
- const detail = violations.map((v) => ` ${v.file}${v.line ? `:${v.line}` : ""} \u2014 import "${v.specifier}"
52260
- ${v.remedy}`).join("\n");
52261
- return new Error(
52262
- `[vesk] edge-targeted build cannot include a TCP-only driver (${violations.length} found).
52263
- ${detail}
52264
-
52265
- This was a build error rather than a runtime one because an edge runtime has no socket: the deployed function would fail on its first query.`
52266
- );
52267
- }
52268
- var SOCKETLESS_PLATFORMS = /* @__PURE__ */ new Set(["edge", "cloudflare", "deno", "coxmos"]);
52269
- function isSocketlessTarget(platform, target) {
52270
- if (target === "edge") return true;
52271
- return typeof platform === "string" && SOCKETLESS_PLATFORMS.has(platform);
52272
- }
52273
- var SOURCE_EXTENSIONS = [".vsk", ".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
52274
- var SKIPPED_DIRS = /* @__PURE__ */ new Set(["node_modules", ".vesk", ".git", "dist", ".next", ".output", "coverage"]);
52275
- function collectAppSources(dir, out = []) {
52276
- let entries;
52277
- try {
52278
- entries = readdirSync2(dir);
52279
- } catch {
52280
- return out;
52281
- }
52282
- for (const entry of entries) {
52283
- if (SKIPPED_DIRS.has(entry) || entry.startsWith(".")) continue;
52284
- const full = join7(dir, entry);
52285
- let st;
52286
- try {
52287
- st = statSync3(full);
52288
- } catch {
52289
- continue;
52290
- }
52291
- if (st.isDirectory()) collectAppSources(full, out);
52292
- else if (st.isFile()) {
52293
- const dot = entry.lastIndexOf(".");
52294
- if (dot === -1) continue;
52295
- if (SOURCE_EXTENSIONS.includes(entry.slice(dot).toLowerCase())) out.push(full);
52296
- }
52297
- }
52298
- return out;
52299
- }
52300
- function tcpDriverViolations(appDir) {
52301
- const files = [];
52302
- for (const path of collectAppSources(appDir)) {
52303
- try {
52304
- files.push({ path, code: readFileSync11(path, "utf-8") });
52305
- } catch {
52306
- }
52307
- }
52308
- return scanServerOnlyImports(files).filter((v) => v.kind === "tcp-driver");
52309
- }
52310
-
52311
- // ../adapter/src/server-only-plugin.ts
52312
52853
  var STUB_NAMESPACE = "vesk-server-only";
52313
52854
  var stubCounter = 0;
52314
52855
  function importedNamesFor(code, specifier) {
@@ -52483,12 +53024,21 @@ function fileUnchanged(filePath, cached) {
52483
53024
  return false;
52484
53025
  }
52485
53026
  }
52486
- function buildRouterOpts(options) {
53027
+ function hasServerMiddleware(nodes) {
53028
+ for (const node of nodes) {
53029
+ if (node.hasMiddleware) return true;
53030
+ if (node.children?.length && hasServerMiddleware(node.children)) return true;
53031
+ }
53032
+ return false;
53033
+ }
53034
+ function buildRouterOpts(options, serverMiddleware) {
52487
53035
  const ttl = options?.routeDataCache;
53036
+ const opts = [];
53037
+ if (serverMiddleware) opts.push("serverMiddleware: true");
52488
53038
  if (typeof ttl === "number" && ttl > 0) {
52489
- return `, { routeDataCache: ${ttl} }`;
53039
+ opts.push(`routeDataCache: ${ttl}`);
52490
53040
  }
52491
- return "";
53041
+ return opts.length ? `, { ${opts.join(", ")} }` : "";
52492
53042
  }
52493
53043
  function findRuntimeSrc2(appDir) {
52494
53044
  const monorepoRoot = resolve10(__dirname3, "..", "..", "..");
@@ -52536,7 +53086,7 @@ function isAnyImport(node) {
52536
53086
  return node.type === "ImportDeclaration";
52537
53087
  }
52538
53088
  function isRuntimePreamble(node) {
52539
- if (node.type === "FunctionDeclaration" && (node.id?.name === "__cleanup" || node.id?.name === "__place")) {
53089
+ if (node.type === "FunctionDeclaration" && (node.id?.name === "__cleanup" || node.id?.name === "__place" || node.id?.name === "__reconcileRegion")) {
52540
53090
  return true;
52541
53091
  }
52542
53092
  if (node.type === "VariableDeclaration") {
@@ -53471,17 +54021,23 @@ A module-scope statement runs the moment the browser evaluates the chunk, so a s
53471
54021
  loader: { ".js": "tsx" },
53472
54022
  legalComments: "none",
53473
54023
  ...appTsconfig ? { tsconfig: appTsconfig } : {},
53474
- // Stub optional CJS deps (qrcode-generator via vesk-qr, canvas,
53475
- // @zxing/*) so esbuild never bundles their CJS source into the client
53476
- // bundle — that would emit a `__require` shim that throws in the
53477
- // browser. vesk-qr now lazy-loads them via dynamic import; stubbing
53478
- // keeps the bundle valid ESM without shipping dead code.
54024
+ // Stub only the OPTIONAL CJS deps (canvas for raster export, @zxing/*
54025
+ // for scan validation). They degrade gracefully and their absence must
54026
+ // not break the bundle.
54027
+ //
54028
+ // `qrcode-generator` must NOT be stubbed: it is the pure-JS encoder
54029
+ // every client-side QR (vesk-qr's dynamic `import("qrcode-generator")`)
54030
+ // runs on. Stubbing it to `export {}` makes `getQrcode()` resolve to an
54031
+ // empty object, so `CofoundrMatrix.generate()` throws
54032
+ // "QREncodingError: generator is not a function" during hydration and
54033
+ // the page falls back to the client error boundary. esbuild bundles it
54034
+ // as CJS fine; only genuinely Node-only/optional deps belong here.
53479
54035
  plugins: [
53480
54036
  {
53481
54037
  name: "stub-browser-packages",
53482
54038
  setup(b) {
53483
54039
  b.onResolve(
53484
- { filter: /^(qrcode-generator|canvas|@zxing\/(browser|node))(\/|$)/ },
54040
+ { filter: /^(canvas|@zxing\/(browser|node))(\/|$)/ },
53485
54041
  (args2) => ({ path: args2.path, namespace: "browser-stub" })
53486
54042
  );
53487
54043
  b.onLoad({ filter: /.*/, namespace: "browser-stub" }, () => ({
@@ -53691,12 +54247,13 @@ async function buildMainBundle(routeTree, runtimeDir, codeSplit, mono, hmr, impo
53691
54247
  ` : runtimeCode + "\n";
53692
54248
  const cleanupFn = "function __cleanup(start, end) {\n let n = start.nextSibling;\n while (n && n !== end) {\n const next = n.nextSibling;\n n.remove();\n n = next;\n }\n}\n";
53693
54249
  const placeFn = "function __place(start, end, nodes, fallback) {\n if (start.parentNode !== null) {\n const p = start.parentNode;\n for (let i = 0; i < nodes.length; i++) p.insertBefore(nodes[i], end);\n return;\n }\n if (nodes.length > 0 && nodes[0].parentNode) {\n const p = nodes[0].parentNode;\n p.insertBefore(start, nodes[0]);\n p.insertBefore(end, nodes[nodes.length - 1].nextSibling);\n // Client-surplus nodes (SSR rendered fewer items than the client data)\n // are freshly claimed and still detached \u2014 move them into the region in\n // client order before `end`, instead of stranding them off-parent.\n for (let i = 0; i < nodes.length; i++) {\n if (nodes[i].parentNode === null) p.insertBefore(nodes[i], end);\n }\n return;\n }\n fallback.appendChild(start);\n fallback.appendChild(end);\n for (let i = 0; i < nodes.length; i++) fallback.insertBefore(nodes[i], end);\n}\n";
54250
+ const reconcileRegionFn = "function __reconcileRegion(parent, id, branch, walker) {\n if (!parent) return;\n let start = null;\n let end = null;\n for (let n = parent.firstChild; n; n = n.nextSibling) {\n if (n.nodeType !== 8) continue;\n const text = n.textContent || '';\n if (text === 'vesk-r:' + id + ':0' || text === 'vesk-r:' + id + ':1') start = n;\n else if (text === 'vesk-r-end:' + id) end = n;\n if (start && end) break;\n }\n if (!start || !end) return;\n const ssrBranch = (start.textContent || '').slice(-2) === ':1' ? 1 : 0;\n if (ssrBranch !== branch) {\n let n = start.nextSibling;\n while (n && n !== end) {\n const next = n.nextSibling;\n n.remove();\n n = next;\n }\n if (walker && walker.retireDetached) walker.retireDetached();\n }\n start.remove();\n end.remove();\n}\n";
53694
54251
  const updateComponentsFn = "function __updateComponents(nodes) {\n for (const n of nodes) {\n if (n._pageName && __components[n._pageName]) n.page = __components[n._pageName];\n if (n._layoutName && __components[n._layoutName]) n.layout = __components[n._layoutName];\n if (n._errorName && __components[n._errorName]) n.error = __components[n._errorName];\n if (n._notFoundName && __components[n._notFoundName]) n.notFound = __components[n._notFoundName];\n if (n._offlineName && __components[n._offlineName]) n.offline = __components[n._offlineName];\n if (n._networkName && __components[n._networkName]) n.network = __components[n._networkName];\n if (n.children) __updateComponents(n.children);\n }\n}\n";
53695
54252
  const routeTreeJson = JSON.stringify(routeTree);
53696
54253
  if (codeSplit) {
53697
54254
  const resolveNamesFn = "function __resolveNames(nodes) {\n for (const n of nodes) {\n if (n.chunk) n._chunk = n.chunk;\n if (n.chunkError) n._chunkError = n.chunkError;\n if (typeof n.page === 'string') n._pageName = n.page;\n if (typeof n.layout === 'string') n._layoutName = n.layout;\n if (typeof n.error === 'string') n._errorName = n.error;\n if (typeof n.notFound === 'string') n._notFoundName = n.notFound;\n if (typeof n.offline === 'string') n._offlineName = n.offline;\n if (typeof n.network === 'string') n._networkName = n.network;\n if (n.children) __resolveNames(n.children);\n }\n}\n";
53698
54255
  const pendCode = "const __pendChunks = [];\nconst __currentPath = typeof window !== 'undefined' ? window.location.pathname : '/';\nif (typeof matchRoute === 'function') {\n const __currentMatch = matchRoute(__routeTree, __currentPath);\n if (__currentMatch) {\n for (const n of __currentMatch.matchChain) {\n if (n._chunk && !__pendChunks.includes(n._chunk)) __pendChunks.push(n._chunk);\n }\n }\n}\n";
53699
- const routerOpts2 = buildRouterOpts({ routeDataCache });
54256
+ const routerOpts2 = buildRouterOpts({ routeDataCache }, hasServerMiddleware(routeTree));
53700
54257
  const startRouterCode = `const __startRouter = function() {
53701
54258
  __updateComponents(__routeTree);
53702
54259
  const __router = createFileRouter(__routeTree${routerOpts2});
@@ -53735,14 +54292,14 @@ if (__pendChunks.length > 0 && typeof ensureChunk === 'function') {
53735
54292
  ];
53736
54293
  const importedSet = new Set(allRuntimeImports);
53737
54294
  const runtimeGlobals2 = globalNames.filter((n) => importedSet.has(n)).map((n) => `globalThis.${n} = ${n};
53738
- `).join("") + "globalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\n\n";
54295
+ `).join("") + "globalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\nglobalThis.__reconcileRegion = __reconcileRegion;\n\n";
53739
54296
  const extraGlobals = [...runtimeImportNames || []].filter((n) => n && n !== "default").map((n) => `globalThis.${n} = ${n};
53740
54297
  `).join("");
53741
54298
  const code2 = preamble + "const __components = globalThis.__components || (globalThis.__components = {});\nconst __hydrators = globalThis.__hydrators || (globalThis.__hydrators = {});\nconst __runtime_comps = __components;\n\n" + runtimeGlobals2 + extraGlobals + // Shared app modules run HERE: after the runtime bindings are published,
53742
54299
  // before anything can request a route chunk. Earlier (at the top of the
53743
54300
  // bundle) `globalThis.track` was still undefined, so every module-scope
53744
54301
  // cell in a store was created against a missing runtime.
53745
- (sharedModuleBundle ? sharedModuleBundle + "\n" : "") + cleanupFn + placeFn + "globalThis.__components = __components;\n" + resolveNamesFn + updateComponentsFn + "const __routeTree = " + routeTreeJson + ";\n__resolveNames(__routeTree);\n" + pendCode + startRouterCode;
54302
+ (sharedModuleBundle ? sharedModuleBundle + "\n" : "") + cleanupFn + placeFn + reconcileRegionFn + "globalThis.__components = __components;\n" + resolveNamesFn + updateComponentsFn + "const __routeTree = " + routeTreeJson + ";\n__resolveNames(__routeTree);\n" + pendCode + startRouterCode;
53746
54303
  return hmr ? appendHmrGlobals(code2) : code2;
53747
54304
  }
53748
54305
  const componentLines = mono?.componentLines || [];
@@ -53751,8 +54308,8 @@ if (__pendChunks.length > 0 && typeof ensureChunk === 'function') {
53751
54308
  const hydratorAliasLines = mono?.hydratorAliasLines || [];
53752
54309
  const aliasCode = aliasLines.length > 0 ? aliasLines.join("\n") + "\n" : "";
53753
54310
  const hydratorAliasCode = hydratorAliasLines.length > 0 ? hydratorAliasLines.join("\n") + "\n" : "";
53754
- const routerOpts = buildRouterOpts({ routeDataCache });
53755
- const code = preamble + "const __components = {};\nconst __hydrators = {};\nconst __runtime_comps = __components;\n\n" + componentLines.join("\n\n") + "\n" + aliasCode + hydratorLines.join("\n\n") + "\n" + hydratorAliasCode + cleanupFn + placeFn + "globalThis.__components = __components;\nglobalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\n" + allRuntimeImports.map((n) => `globalThis.${n} = ${n};
54311
+ const routerOpts = buildRouterOpts({ routeDataCache }, hasServerMiddleware(routeTree));
54312
+ const code = preamble + "const __components = {};\nconst __hydrators = {};\nconst __runtime_comps = __components;\n\n" + componentLines.join("\n\n") + "\n" + aliasCode + hydratorLines.join("\n\n") + "\n" + hydratorAliasCode + cleanupFn + placeFn + reconcileRegionFn + "globalThis.__components = __components;\nglobalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\nglobalThis.__reconcileRegion = __reconcileRegion;\n" + allRuntimeImports.map((n) => `globalThis.${n} = ${n};
53756
54313
  `).join("") + "function __resolveNames(nodes) {\n for (const n of nodes) {\n if (typeof n.page === 'string') {\n n._pageName = n.page;\n n.page = __components[n.page];\n }\n if (typeof n.layout === 'string') {\n n._layoutName = n.layout;\n n.layout = __components[n.layout];\n }\n if (typeof n.error === 'string') n.error = __components[n.error];\n if (typeof n.notFound === 'string') n.notFound = __components[n.notFound];\n if (typeof n.offline === 'string') n.offline = __components[n.offline];\n if (typeof n.network === 'string') n.network = __components[n.network];\n if (n.children) __resolveNames(n.children);\n }\n}\n" + updateComponentsFn + "const __routeTree = " + routeTreeJson + `;
53757
54314
  __resolveNames(__routeTree);
53758
54315
  const __router = createFileRouter(__routeTree${routerOpts});
@@ -53832,6 +54389,9 @@ function generateManifest(routes, ssrRoutes, apiRoutes, staticRoutes, middleware
53832
54389
  };
53833
54390
  }
53834
54391
 
54392
+ // ../adapter/dist/index.js
54393
+ init_server_only();
54394
+
53835
54395
  // ../adapter/src/static.ts
53836
54396
  init_paths();
53837
54397
  import { mkdirSync as mkdirSync4, copyFileSync, readdirSync as readdirSync3, statSync as statSync6, existsSync as existsSync13, writeFileSync as writeFileSync5, readFileSync as readFileSync15 } from "node:fs";
@@ -54721,6 +55281,41 @@ async function startProdServer(outDir, options) {
54721
55281
  }
54722
55282
  }
54723
55283
  }
55284
+ if (url.pathname === "/_vesk/middleware" && middlewareMod) {
55285
+ const targetPath = url.searchParams.get("path") || "/";
55286
+ const targetUrl = new URL(targetPath, url.origin);
55287
+ const middlewareRequest = new Request(targetUrl.href, {
55288
+ method: "GET",
55289
+ headers: req.headers
55290
+ });
55291
+ const mwEndpointCtx = {
55292
+ request: middlewareRequest,
55293
+ params: {},
55294
+ url: targetUrl,
55295
+ locals: Object.assign({}, globalThis.__vesk_server_ctx || {}),
55296
+ cookies: {},
55297
+ set(key, value) {
55298
+ this.locals[key] = value;
55299
+ },
55300
+ get(key) {
55301
+ return this.locals[key];
55302
+ }
55303
+ };
55304
+ const mwResult = await middlewareMod.execute(mwEndpointCtx);
55305
+ res.writeHead(200, {
55306
+ "Content-Type": "application/json; charset=utf-8",
55307
+ "Cache-Control": "no-store"
55308
+ });
55309
+ if (mwResult.response) {
55310
+ const location = mwResult.response.headers.get("location") || mwResult.response.headers.get("Location");
55311
+ if (location) {
55312
+ res.end(JSON.stringify({ redirect: location }));
55313
+ return;
55314
+ }
55315
+ }
55316
+ res.end(JSON.stringify(mwResult.rewriteUrl ? { rewrite: mwResult.rewriteUrl } : { allow: true }));
55317
+ return;
55318
+ }
54724
55319
  let mwCtx;
54725
55320
  const serverStore = globalThis.__vesk_server_ctx;
54726
55321
  if (middlewareMod) {
@@ -54770,186 +55365,191 @@ async function startProdServer(outDir, options) {
54770
55365
  url.pathname = mwResult.rewriteUrl;
54771
55366
  }
54772
55367
  }
55368
+ const __outerRequest = globalThis.__vesk_request;
54773
55369
  globalThis.__vesk_request = mwCtx;
54774
- if (url.pathname.startsWith("/_vesk/action/")) {
54775
- const actionId = url.pathname.replace("/_vesk/action/", "");
54776
- const actionEntry = buildConfig.actions && buildConfig.actions.find((a) => a.id === actionId);
54777
- if (!actionEntry) {
54778
- res.writeHead(404, { "Content-Type": "application/json" });
54779
- res.end(JSON.stringify({ ok: false, error: "Action not found" }));
54780
- return;
54781
- }
54782
- const mod = await loadFunction(actionEntry.function);
54783
- if (!mod || !mod.handleAction) {
54784
- res.writeHead(404, { "Content-Type": "application/json" });
54785
- res.end(JSON.stringify({ ok: false, error: "Action not found" }));
55370
+ try {
55371
+ if (url.pathname.startsWith("/_vesk/action/")) {
55372
+ const actionId = url.pathname.replace("/_vesk/action/", "");
55373
+ const actionEntry = buildConfig.actions && buildConfig.actions.find((a) => a.id === actionId);
55374
+ if (!actionEntry) {
55375
+ res.writeHead(404, { "Content-Type": "application/json" });
55376
+ res.end(JSON.stringify({ ok: false, error: "Action not found" }));
55377
+ return;
55378
+ }
55379
+ const mod = await loadFunction(actionEntry.function);
55380
+ if (!mod || !mod.handleAction) {
55381
+ res.writeHead(404, { "Content-Type": "application/json" });
55382
+ res.end(JSON.stringify({ ok: false, error: "Action not found" }));
55383
+ return;
55384
+ }
55385
+ try {
55386
+ const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
55387
+ const handleAction = mod.handleAction.bind(mod);
55388
+ const response = await withSecurityScope(() => handleAction(webRequest, actionId));
55389
+ await deliverResponse(res, response);
55390
+ } catch (e) {
55391
+ const status = errorStatus(e, 500);
55392
+ const message = status === 500 && process.env.NODE_ENV === "production" ? "Internal Server Error" : e instanceof Error ? e.message : String(e);
55393
+ res.writeHead(status, { "Content-Type": "application/json" });
55394
+ res.end(JSON.stringify({ ok: false, error: message }));
55395
+ }
54786
55396
  return;
54787
55397
  }
54788
- try {
54789
- const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
54790
- const handleAction = mod.handleAction.bind(mod);
54791
- const response = await withSecurityScope(() => handleAction(webRequest, actionId));
54792
- await deliverResponse(res, response);
54793
- } catch (e) {
54794
- const status = errorStatus(e, 500);
54795
- const message = status === 500 && process.env.NODE_ENV === "production" ? "Internal Server Error" : e instanceof Error ? e.message : String(e);
54796
- res.writeHead(status, { "Content-Type": "application/json" });
54797
- res.end(JSON.stringify({ ok: false, error: message }));
54798
- }
54799
- return;
54800
- }
54801
- if (url.pathname.startsWith("/api")) {
54802
- for (const route of buildConfig.routes) {
54803
- if (route.type === "api") {
54804
- const params = matchPath(route.path, url.pathname);
54805
- if (params) {
54806
- const mod = await loadFunction(route.function);
54807
- if (!mod) {
54808
- if (functionFailure(route.function)) {
54809
- res.writeHead(500, { "Content-Type": "application/json" });
54810
- res.end(JSON.stringify({ error: "Internal Server Error" }));
55398
+ if (url.pathname.startsWith("/api")) {
55399
+ for (const route of buildConfig.routes) {
55400
+ if (route.type === "api") {
55401
+ const params = matchPath(route.path, url.pathname);
55402
+ if (params) {
55403
+ const mod = await loadFunction(route.function);
55404
+ if (!mod) {
55405
+ if (functionFailure(route.function)) {
55406
+ res.writeHead(500, { "Content-Type": "application/json" });
55407
+ res.end(JSON.stringify({ error: "Internal Server Error" }));
55408
+ return;
55409
+ }
55410
+ continue;
55411
+ }
55412
+ try {
55413
+ const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
55414
+ const response = await withSecurityScope(() => mod.handle(webRequest));
55415
+ await deliverResponse(res, response);
55416
+ return;
55417
+ } catch (e) {
55418
+ const status = errorStatus(e, 500);
55419
+ res.writeHead(status, { "Content-Type": "application/json" });
55420
+ res.end(JSON.stringify({ error: status === 500 ? "Internal Server Error" : e instanceof Error ? e.message : String(e) }));
54811
55421
  return;
54812
55422
  }
54813
- continue;
54814
- }
54815
- try {
54816
- const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
54817
- const response = await withSecurityScope(() => mod.handle(webRequest));
54818
- await deliverResponse(res, response);
54819
- return;
54820
- } catch (e) {
54821
- const status = errorStatus(e, 500);
54822
- res.writeHead(status, { "Content-Type": "application/json" });
54823
- res.end(JSON.stringify({ error: status === 500 ? "Internal Server Error" : e instanceof Error ? e.message : String(e) }));
54824
- return;
54825
55423
  }
54826
55424
  }
54827
55425
  }
54828
55426
  }
54829
- }
54830
- const appDir = resolve14(projectDir, "app");
54831
- const pageCssUrls = resolveCssUrls({
54832
- enabled: hasBuiltGlobalCss(outDir)
54833
- });
54834
- const boundaryCache = /* @__PURE__ */ new Map();
54835
- async function renderBoundaryFile(file, pathname, props) {
54836
- const boundaryPath = resolveBoundaryFileForUrl(pathname, appDir, file);
54837
- if (!boundaryPath) return null;
54838
- const key = `${file}:${boundaryPath}`;
54839
- let html = boundaryCache.has(key) ? boundaryCache.get(key) : null;
54840
- if (html === null) {
54841
- try {
54842
- const runtimePath = resolve14(outDir, "server", "runtime.js");
54843
- const { renderFullPage: renderFullPage2, storeDataScriptGlobal } = await import(runtimePath);
54844
- const src2 = readFileSync18(boundaryPath, "utf-8");
54845
- const compName = resolveComponentName(src2) || (file === "error.vsk" ? "Error" : "NotFound");
54846
- html = await renderFullPage2(src2, compName, props, /* @__PURE__ */ new Map(), { hydrate: true, cssUrls: pageCssUrls, clientScriptUrl: buildConfig?.assets?.client?.url || "/_vesk/static/client.js", clientScriptIntegrity: buildConfig?.assets?.client?.integrity, security: securityConfig?.security || {}, externalDataScript: storeDataScriptGlobal, sourcePath: boundaryPath, headExtra: bakedHeadExtra });
54847
- } catch {
54848
- return null;
55427
+ const appDir = resolve14(projectDir, "app");
55428
+ const pageCssUrls = resolveCssUrls({
55429
+ enabled: hasBuiltGlobalCss(outDir)
55430
+ });
55431
+ const boundaryCache = /* @__PURE__ */ new Map();
55432
+ async function renderBoundaryFile(file, pathname, props) {
55433
+ const boundaryPath = resolveBoundaryFileForUrl(pathname, appDir, file);
55434
+ if (!boundaryPath) return null;
55435
+ const key = `${file}:${boundaryPath}`;
55436
+ let html = boundaryCache.has(key) ? boundaryCache.get(key) : null;
55437
+ if (html === null) {
55438
+ try {
55439
+ const runtimePath = resolve14(outDir, "server", "runtime.js");
55440
+ const { renderFullPage: renderFullPage2, storeDataScriptGlobal } = await import(runtimePath);
55441
+ const src2 = readFileSync18(boundaryPath, "utf-8");
55442
+ const compName = resolveComponentName(src2) || (file === "error.vsk" ? "Error" : "NotFound");
55443
+ html = await renderFullPage2(src2, compName, props, /* @__PURE__ */ new Map(), { hydrate: true, cssUrls: pageCssUrls, clientScriptUrl: buildConfig?.assets?.client?.url || "/_vesk/static/client.js", clientScriptIntegrity: buildConfig?.assets?.client?.integrity, security: securityConfig?.security || {}, externalDataScript: storeDataScriptGlobal, sourcePath: boundaryPath, headExtra: bakedHeadExtra });
55444
+ } catch {
55445
+ return null;
55446
+ }
54849
55447
  }
55448
+ return html;
54850
55449
  }
54851
- return html;
54852
- }
54853
- let notFoundHtml = null;
54854
- {
54855
- const rendered = await renderBoundaryFile("not-found.vsk", url.pathname, { params: {}, url: url.pathname });
54856
- notFoundHtml = rendered;
54857
- }
54858
- for (const route of buildConfig.routes) {
54859
- if (route.type === "ssr") {
54860
- const params = matchPath(route.path, url.pathname);
54861
- if (params) {
54862
- const mod = await loadFunction(route.function);
54863
- if (mod) {
54864
- const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
54865
- const origin = new URL(url.href).origin;
54866
- const origFetch = globalThis.fetch;
54867
- globalThis.fetch = async (input, init) => {
54868
- if (typeof input === "string" && input.startsWith("/")) {
54869
- input = origin + input;
54870
- }
54871
- return origFetch(input, init);
54872
- };
54873
- try {
54874
- let cachedResult = null;
54875
- if (route.revalidate && route.revalidate > 0) {
54876
- const { pageIsr: pageIsr2 } = await Promise.resolve().then(() => (init_index_server(), index_server_exports));
54877
- cachedResult = await pageIsr2(url.pathname, async () => {
54878
- const response2 = await withSecurityScope(() => mod.handle(webRequest));
54879
- return { html: await response2.text(), headers: Object.fromEntries(response2.headers) };
54880
- }, { revalidate: route.revalidate, tags: route.tags || [] });
54881
- }
54882
- if (cachedResult) {
54883
- res.writeHead(200, cachedResult.headers || { "Content-Type": "text/html" });
54884
- res.end(cachedResult.html);
54885
- return;
54886
- }
54887
- const response = await withSecurityScope(() => mod.handle(webRequest));
54888
- const headers2 = Object.fromEntries(response.headers);
54889
- if (!headers2["content-type"] && !headers2["Content-Type"]) headers2["Content-Type"] = "text/html";
54890
- if (response.body && typeof response.body.getReader === "function") {
54891
- res.writeHead(response.status, headers2);
54892
- const reader = response.body.getReader();
54893
- const pump = () => {
54894
- reader.read().then(({ done, value }) => {
54895
- if (done) {
54896
- res.end();
54897
- return;
54898
- }
54899
- res.write(value);
54900
- pump();
54901
- }).catch(() => res.end());
54902
- };
54903
- pump();
54904
- } else {
54905
- const body = await response.text();
54906
- res.writeHead(response.status, headers2);
54907
- res.end(body);
54908
- }
54909
- return;
54910
- } catch (e) {
54911
- const err = e instanceof Error ? e : new Error(String(e));
54912
- if (err.name === "Redirect") {
54913
- const redirect2 = err;
54914
- res.writeHead(Number(redirect2.status) || 302, { Location: typeof redirect2.url === "string" ? redirect2.url : "/" });
54915
- res.end();
55450
+ let notFoundHtml = null;
55451
+ {
55452
+ const rendered = await renderBoundaryFile("not-found.vsk", url.pathname, { params: {}, url: url.pathname });
55453
+ notFoundHtml = rendered;
55454
+ }
55455
+ for (const route of buildConfig.routes) {
55456
+ if (route.type === "ssr") {
55457
+ const params = matchPath(route.path, url.pathname);
55458
+ if (params) {
55459
+ const mod = await loadFunction(route.function);
55460
+ if (mod) {
55461
+ const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
55462
+ const origin = new URL(url.href).origin;
55463
+ const origFetch = globalThis.fetch;
55464
+ globalThis.fetch = async (input, init) => {
55465
+ if (typeof input === "string" && input.startsWith("/")) {
55466
+ input = origin + input;
55467
+ }
55468
+ return origFetch(input, init);
55469
+ };
55470
+ try {
55471
+ let cachedResult = null;
55472
+ if (route.revalidate && route.revalidate > 0) {
55473
+ const { pageIsr: pageIsr2 } = await Promise.resolve().then(() => (init_index_server(), index_server_exports));
55474
+ cachedResult = await pageIsr2(url.pathname, async () => {
55475
+ const response2 = await withSecurityScope(() => mod.handle(webRequest));
55476
+ return { html: await response2.text(), headers: Object.fromEntries(response2.headers) };
55477
+ }, { revalidate: route.revalidate, tags: route.tags || [] });
55478
+ }
55479
+ if (cachedResult) {
55480
+ res.writeHead(200, cachedResult.headers || { "Content-Type": "text/html" });
55481
+ res.end(cachedResult.html);
55482
+ return;
55483
+ }
55484
+ const response = await withSecurityScope(() => mod.handle(webRequest));
55485
+ const headers2 = Object.fromEntries(response.headers);
55486
+ if (!headers2["content-type"] && !headers2["Content-Type"]) headers2["Content-Type"] = "text/html";
55487
+ if (response.body && typeof response.body.getReader === "function") {
55488
+ res.writeHead(response.status, headers2);
55489
+ const reader = response.body.getReader();
55490
+ const pump = () => {
55491
+ reader.read().then(({ done, value }) => {
55492
+ if (done) {
55493
+ res.end();
55494
+ return;
55495
+ }
55496
+ res.write(value);
55497
+ pump();
55498
+ }).catch(() => res.end());
55499
+ };
55500
+ pump();
55501
+ } else {
55502
+ const body = await response.text();
55503
+ res.writeHead(response.status, headers2);
55504
+ res.end(body);
55505
+ }
54916
55506
  return;
54917
- }
54918
- if (err.name === "NotFoundError") {
54919
- res.writeHead(404, { "Content-Type": "text/html" });
54920
- res.end(notFoundHtml || renderDefaultNotFoundPage({ url: url.pathname, headExtra: bakedHeadExtra }));
55507
+ } catch (e) {
55508
+ const err = e instanceof Error ? e : new Error(String(e));
55509
+ if (err.name === "Redirect") {
55510
+ const redirect2 = err;
55511
+ res.writeHead(Number(redirect2.status) || 302, { Location: typeof redirect2.url === "string" ? redirect2.url : "/" });
55512
+ res.end();
55513
+ return;
55514
+ }
55515
+ if (err.name === "NotFoundError") {
55516
+ res.writeHead(404, { "Content-Type": "text/html" });
55517
+ res.end(notFoundHtml || renderDefaultNotFoundPage({ url: url.pathname, headExtra: bakedHeadExtra }));
55518
+ return;
55519
+ }
55520
+ console.error("vesk ssr error:", err.message);
55521
+ await reportServerError(err, {
55522
+ url: url.pathname + url.search,
55523
+ routePath: route.path,
55524
+ target: "node",
55525
+ status: 500,
55526
+ buildConfig
55527
+ });
55528
+ if (eventsMod) {
55529
+ await executeError(err, { url: url.href, routePath: route.path, target: "node", status: 500 }, eventsMod);
55530
+ }
55531
+ const expose = process.env.NODE_ENV !== "production";
55532
+ const errorHtml = await renderBoundaryFile("error.vsk", url.pathname, {
55533
+ error: expose ? err.message : "Internal Server Error",
55534
+ stack: expose ? err.stack : "",
55535
+ statusCode: 500,
55536
+ url: url.pathname
55537
+ });
55538
+ res.writeHead(500, { "Content-Type": "text/html" });
55539
+ res.end(errorHtml || renderDefaultErrorPage({ message: process.env.NODE_ENV !== "production" ? err.message : void 0, url: url.pathname, headExtra: bakedHeadExtra }));
54921
55540
  return;
55541
+ } finally {
55542
+ globalThis.fetch = origFetch;
54922
55543
  }
54923
- console.error("vesk ssr error:", err.message);
54924
- await reportServerError(err, {
54925
- url: url.pathname + url.search,
54926
- routePath: route.path,
54927
- target: "node",
54928
- status: 500,
54929
- buildConfig
54930
- });
54931
- if (eventsMod) {
54932
- await executeError(err, { url: url.href, routePath: route.path, target: "node", status: 500 }, eventsMod);
54933
- }
54934
- const expose = process.env.NODE_ENV !== "production";
54935
- const errorHtml = await renderBoundaryFile("error.vsk", url.pathname, {
54936
- error: expose ? err.message : "Internal Server Error",
54937
- stack: expose ? err.stack : "",
54938
- statusCode: 500,
54939
- url: url.pathname
54940
- });
54941
- res.writeHead(500, { "Content-Type": "text/html" });
54942
- res.end(errorHtml || renderDefaultErrorPage({ message: process.env.NODE_ENV !== "production" ? err.message : void 0, url: url.pathname, headExtra: bakedHeadExtra }));
54943
- return;
54944
- } finally {
54945
- globalThis.fetch = origFetch;
54946
55544
  }
54947
55545
  }
54948
55546
  }
54949
55547
  }
55548
+ res.writeHead(404, { "Content-Type": "text/html" });
55549
+ res.end(notFoundHtml || renderDefaultNotFoundPage({ url: url.pathname, headExtra: bakedHeadExtra }));
55550
+ } finally {
55551
+ globalThis.__vesk_request = __outerRequest;
54950
55552
  }
54951
- res.writeHead(404, { "Content-Type": "text/html" });
54952
- res.end(notFoundHtml || renderDefaultNotFoundPage({ url: url.pathname, headExtra: bakedHeadExtra }));
54953
55553
  });
54954
55554
  try {
54955
55555
  await eventsMod?.executeStart?.({ server, port, host });
@@ -55003,9 +55603,9 @@ function PACKAGES_DIR_SELF() {
55003
55603
  var __dirname6 = dirname17(fileURLToPath5(import.meta.url));
55004
55604
  async function resolveCompilerApi(name) {
55005
55605
  const monorepoSrc = resolve21(__dirname6, "..", "..", "compiler", "src");
55006
- if (existsSync22(monorepoSrc)) {
55606
+ if (existsSync23(monorepoSrc)) {
55007
55607
  const tsFile = resolve21(monorepoSrc, name.replace(/\.js$/, ".ts"));
55008
- if (existsSync22(tsFile)) {
55608
+ if (existsSync23(tsFile)) {
55009
55609
  return import(tsFile);
55010
55610
  }
55011
55611
  return import(resolve21(monorepoSrc, name));
@@ -55188,7 +55788,7 @@ async function build2(appDir, options) {
55188
55788
  console.error(`vesk build: ${componentMap.size} external components found in ${componentsDir}`);
55189
55789
  }
55190
55790
  const apiDir = resolve21(appDir, "api");
55191
- const apiTree = existsSync22(apiDir) ? scanApiRoutes2(apiDir) : [];
55791
+ const apiTree = existsSync23(apiDir) ? scanApiRoutes2(apiDir) : [];
55192
55792
  console.error(`vesk build: ${routeTree.length} root routes, ${apiTree.length} API routes`);
55193
55793
  markPhase("scan routes");
55194
55794
  console.error("vesk build: bundling client runtime...");
@@ -55243,7 +55843,7 @@ async function build2(appDir, options) {
55243
55843
  const { funcPath, funcCode, name } = generateSsrFunction(node, appDir, outDir, componentMap, { ancestorLayouts: ssrAncestorLayouts, middlewareCode: mwCode, headExtra: pluginHeadExtra, clientScriptUrl: clientUrl, clientScriptIntegrity: clientIntegrity }, registry);
55244
55844
  writeFileSync12(funcPath, funcCode, "utf-8");
55245
55845
  const pagePath = resolve21(appDir, node.sourceDir, "page.vsk");
55246
- if (existsSync22(pagePath)) {
55846
+ if (existsSync23(pagePath)) {
55247
55847
  const src2 = readFileSync24(pagePath, "utf-8");
55248
55848
  const actionIds = collectActionIds(src2);
55249
55849
  if (node.layout) {
@@ -55330,13 +55930,13 @@ async function build2(appDir, options) {
55330
55930
  const publicDirResolved = resolve21(outDir, "static", "public");
55331
55931
  const siteUrl = options?.siteUrl || "http://localhost:3000";
55332
55932
  const sitemapOverride = resolve21(publicDirResolved, "sitemap.xml");
55333
- if (!existsSync22(sitemapOverride)) {
55933
+ if (!existsSync23(sitemapOverride)) {
55334
55934
  const sitemap = generateSitemap2(routeTree, ssrRoutes, prerenderedRoutes, { siteUrl });
55335
55935
  writeFileSync12(sitemapOverride, sitemap, "utf-8");
55336
55936
  console.error(`vesk build: seo \u2192 static/public/sitemap.xml (${sitemap.length} bytes)`);
55337
55937
  }
55338
55938
  const robotsOverride = resolve21(publicDirResolved, "robots.txt");
55339
- if (!existsSync22(robotsOverride)) {
55939
+ if (!existsSync23(robotsOverride)) {
55340
55940
  const robots = generateRobotsTxt2(siteUrl);
55341
55941
  writeFileSync12(robotsOverride, robots, "utf-8");
55342
55942
  console.error(`vesk build: seo \u2192 static/public/robots.txt (${robots.length} bytes)`);
@@ -55400,7 +56000,7 @@ vesk build: done (${outDir})`);
55400
56000
  init_seo_audit();
55401
56001
 
55402
56002
  // src/dev-server.ts
55403
- import { readFileSync as readFileSync42, watch, statSync as statSync22, existsSync as existsSync43, mkdirSync as mkdirSync19, readdirSync as readdirSync14, writeFileSync as writeFileSync21, renameSync as renameSync2 } from "node:fs";
56003
+ import { readFileSync as readFileSync42, watch, statSync as statSync22, existsSync as existsSync44, mkdirSync as mkdirSync19, readdirSync as readdirSync14, writeFileSync as writeFileSync21, renameSync as renameSync2 } from "node:fs";
55404
56004
  import { createHash as createHash3 } from "node:crypto";
55405
56005
  import { resolve as resolve39, extname as extname7, join as join28, dirname as dirname27, relative as relative9 } from "node:path";
55406
56006
  import { createServer as createServer2 } from "node:http";
@@ -56182,6 +56782,10 @@ var Ctx2 = class {
56182
56782
  markerless = true;
56183
56783
  inTryBody = false;
56184
56784
  claimStatic = false;
56785
+ // Markerless only: the next real claim carries a compiler-generated static
56786
+ // class descriptor so a same-tag but structurally different SSR slot is
56787
+ // substituted instead of adopted (e.g. an empty-state <div> vs a list <div>).
56788
+ descriptorClaim = false;
56185
56789
  // While set, the next StaticNode claimed in hydrate mode uses `__root` (the
56186
56790
  // item element already claimed by key) instead of walking for a new element.
56187
56791
  rootClaim = false;
@@ -56319,6 +56923,7 @@ function emitNode2(ctx2, node, tracked2, effectsVar, parentVar, compPrefix = "__
56319
56923
  ctx2.push(` const __slot = createLayoutSlot(${ctx2.walker}, ${parentVar});`);
56320
56924
  ctx2.push(` const __child = props.children(__slot.walker);`);
56321
56925
  ctx2.push(` if (__child && typeof __child.then === 'function') __pendingChild = __slot.track(__child);`);
56926
+ ctx2.push(` else if (__child && __child.nodeType === 11) ${parentVar}.appendChild(__child);`);
56322
56927
  ctx2.push(` } else {`);
56323
56928
  ctx2.push(` ${parentVar}.appendChild(props.children);`);
56324
56929
  ctx2.push(` }`);
@@ -56370,6 +56975,18 @@ var PROPERTY_ATTRS2 = {
56370
56975
  option: /* @__PURE__ */ new Set(["selected"]),
56371
56976
  progress: /* @__PURE__ */ new Set(["value"])
56372
56977
  };
56978
+ function staticClassDescriptor2(node) {
56979
+ const hasDynamicClass = node.children.some((child) => child instanceof DynamicBinding && child.kind === "attribute" && child.target === "class");
56980
+ if (hasDynamicClass)
56981
+ return null;
56982
+ const attr = node.attributes.find((a) => a.name === "class");
56983
+ if (!attr)
56984
+ return null;
56985
+ const value = attr.value.trim();
56986
+ if (!value)
56987
+ return null;
56988
+ return JSON.stringify({ class: value });
56989
+ }
56373
56990
  function emitStatic2(ctx2, node, tracked2, effectsVar, skipK = 0, regionBudget) {
56374
56991
  const el = ctx2.n();
56375
56992
  if (ctx2.hydrate) {
@@ -56381,7 +56998,11 @@ function emitStatic2(ctx2, node, tracked2, effectsVar, skipK = 0, regionBudget)
56381
56998
  ctx2.rootClaim = false;
56382
56999
  const skipExpr = regionBudget && ctx2.markerless ? markerlessSkipExpr2(regionBudget, skipK) : skipK;
56383
57000
  const skipArg = ctx2.markerless ? `, ${skipExpr}` : "";
56384
- const claimedExpr = rootClaim ? `__root || document.createElement(${JSON.stringify(node.tag)})` : `${ctx2.walker}.nextElement(${JSON.stringify(node.tag)}${skipArg})`;
57001
+ const wantsDescriptor = ctx2.markerless && ctx2.descriptorClaim;
57002
+ ctx2.descriptorClaim = false;
57003
+ const descriptor = wantsDescriptor && !rootClaim ? staticClassDescriptor2(node) : null;
57004
+ const descriptorArg = descriptor ? `, ${descriptor}` : "";
57005
+ const claimedExpr = rootClaim ? `__root || document.createElement(${JSON.stringify(node.tag)})` : `${ctx2.walker}.nextElement(${JSON.stringify(node.tag)}${skipArg}${descriptorArg})`;
56385
57006
  ctx2.push(`const ${el} = ${claimedExpr};`);
56386
57007
  if (regionBudget && ctx2.markerless)
56387
57008
  ctx2.push(`${regionBudget} = 0;`);
@@ -56747,6 +57368,45 @@ function emitFragment2(ctx2, nodes, tracked2, effectsVar) {
56747
57368
  ctx2.push(`return $f; })();`);
56748
57369
  return frag;
56749
57370
  }
57371
+ function containsSlot2(nodes) {
57372
+ for (const node of nodes) {
57373
+ if (node instanceof SlotNode)
57374
+ return true;
57375
+ if (node instanceof StaticNode) {
57376
+ if (containsSlot2(node.children))
57377
+ return true;
57378
+ } else if (node instanceof ComponentCall) {
57379
+ if (containsSlot2(node.children))
57380
+ return true;
57381
+ } else if (node instanceof OpaqueDynamicRegion) {
57382
+ if (containsSlot2(node.consequentNodes) || containsSlot2(node.alternateNodes))
57383
+ return true;
57384
+ } else if (node instanceof MapRegion) {
57385
+ if (containsSlot2(node.bodyTemplate) || containsSlot2(node.alternateNodes))
57386
+ return true;
57387
+ } else if (node instanceof WhileLoop) {
57388
+ if (containsSlot2(node.bodyTemplate))
57389
+ return true;
57390
+ } else if (node instanceof ForLoop) {
57391
+ if (containsSlot2(node.bodyTemplate))
57392
+ return true;
57393
+ } else if (node instanceof SwitchBlock) {
57394
+ for (const c of node.cases)
57395
+ if (containsSlot2(c.body))
57396
+ return true;
57397
+ } else if (node instanceof TryCatch) {
57398
+ if (containsSlot2(node.bodyTemplate) || containsSlot2(node.catchBody))
57399
+ return true;
57400
+ } else if (node instanceof ServerBlock || node instanceof ClientBlock || node instanceof HeadBlock) {
57401
+ if (containsSlot2(node.children))
57402
+ return true;
57403
+ } else if (node instanceof PropSlot) {
57404
+ if (containsSlot2(node.body))
57405
+ return true;
57406
+ }
57407
+ }
57408
+ return false;
57409
+ }
56750
57410
  function emitComponentCall2(ctx2, node, tracked2, effectsVar, parentVar, compPrefix = "__components", skipK = 0, regionBudget) {
56751
57411
  const propsEntries = node.props.map((p) => {
56752
57412
  if (typeof p.value === "string")
@@ -56785,6 +57445,7 @@ function emitComponentCall2(ctx2, node, tracked2, effectsVar, parentVar, compPre
56785
57445
  }
56786
57446
  const callArgs = () => plainTarget ? `reactiveProps({ ${propsEntries.join(", ")} })` : `{ ${propsEntries.join(", ")} }`;
56787
57447
  if (ctx2.hydrate) {
57448
+ ctx2.descriptorClaim = false;
56788
57449
  const access = calleeExpr ?? (ctx2.importedNames.has(node.componentName) ? node.componentName : `${ctx2.hydrateRegistry}[${JSON.stringify(node.componentName)}]`);
56789
57450
  if (!calleeExpr && !ctx2.importedNames.has(node.componentName)) {
56790
57451
  ctx2.push(`if (${access} == null) throw new Error(${JSON.stringify(`Component "${node.componentName}" was not found while rendering. Declare it with the \`component\` keyword, import it, or register it in the component registry.`)});`);
@@ -56814,20 +57475,49 @@ function emitComponentCall2(ctx2, node, tracked2, effectsVar, parentVar, compPre
56814
57475
  const savedHydrate = ctx2.hydrate;
56815
57476
  if (wipeMount || ctx2.selfClaimNames.has(node.componentName))
56816
57477
  ctx2.hydrate = false;
56817
- ctx2.push(`const ${frag} = (() => { const $f = document.createDocumentFragment();`);
56818
- const savedEffects = ctx2.effects;
56819
- ctx2.effects = [];
56820
- for (const child of regChildren) {
56821
- const childVar = emitNode2(ctx2, child, tracked2, effectsVar, "$f");
56822
- if (childVar)
56823
- ctx2.push(`$f.appendChild(${childVar});`);
57478
+ const lazySlotChildren = ctx2.hydrate && !plainTarget && !ctx2.selfClaimNames.has(node.componentName) && containsSlot2(regChildren);
57479
+ if (lazySlotChildren) {
57480
+ const fnVar = ctx2.n();
57481
+ const savedLines = ctx2.lines;
57482
+ const savedEffects = ctx2.effects;
57483
+ const savedWalker = ctx2.walker;
57484
+ ctx2.lines = [];
57485
+ ctx2.effects = [];
57486
+ ctx2.walker = "__childWalker";
57487
+ ctx2.push(`const $f = document.createDocumentFragment();`);
57488
+ for (const child of regChildren) {
57489
+ const childVar = emitNode2(ctx2, child, tracked2, effectsVar, "$f");
57490
+ if (childVar)
57491
+ ctx2.push(`$f.appendChild(${childVar});`);
57492
+ }
57493
+ for (const eff of ctx2.effects)
57494
+ ctx2.push(effectsVar ? `${effectsVar}.push(${effectBlockToHandlerExpr2(eff)});` : eff);
57495
+ ctx2.push(`return $f;`);
57496
+ const body = ctx2.lines.join("\n");
57497
+ ctx2.lines = savedLines;
57498
+ ctx2.effects = savedEffects;
57499
+ ctx2.walker = savedWalker;
57500
+ const asyncKw = ctx2.isAsyncScope ? "async " : "";
57501
+ ctx2.push(`const ${fnVar} = ${asyncKw}(__childWalker) => {`);
57502
+ ctx2.push(indent3(body));
57503
+ ctx2.push(`};`);
57504
+ propsEntries.push(`children: ${fnVar}`);
57505
+ } else {
57506
+ ctx2.push(`const ${frag} = (() => { const $f = document.createDocumentFragment();`);
57507
+ const savedEffects = ctx2.effects;
57508
+ ctx2.effects = [];
57509
+ for (const child of regChildren) {
57510
+ const childVar = emitNode2(ctx2, child, tracked2, effectsVar, "$f");
57511
+ if (childVar)
57512
+ ctx2.push(`$f.appendChild(${childVar});`);
57513
+ }
57514
+ for (const eff of ctx2.effects)
57515
+ ctx2.push(effectsVar ? `${effectsVar}.push(${effectBlockToHandlerExpr2(eff)});` : eff);
57516
+ ctx2.effects = savedEffects;
57517
+ ctx2.push(`return $f; })();`);
57518
+ propsEntries.push(`children: ${frag}`);
56824
57519
  }
56825
- for (const eff of ctx2.effects)
56826
- ctx2.push(effectsVar ? `${effectsVar}.push(${effectBlockToHandlerExpr2(eff)});` : eff);
56827
- ctx2.effects = savedEffects;
56828
57520
  ctx2.hydrate = savedHydrate;
56829
- ctx2.push(`return $f; })();`);
56830
- propsEntries.push(`children: ${frag}`);
56831
57521
  }
56832
57522
  if (ctx2.markerless && promptExpr) {
56833
57523
  ctx2.push(`${walkerArg}.injectSkipK(${promptExpr});`);
@@ -56989,7 +57679,7 @@ function emitTryCatch2(ctx2, node, tracked2, effectsVar, parentVar, skipK = 0, r
56989
57679
  ${effArr}.length = 0;
56990
57680
  __cleanup(${anchor}, ${endAnchor});
56991
57681
  try { ${asyncKw}${tryRenderComp}(); } catch(${catchParam}) { ${hasCatch ? `${asyncKw}${catchRenderComp}(${catchParam});` : "throw ${catchParam};"} }
56992
- });
57682
+ }, true);
56993
57683
  }`);
56994
57684
  return null;
56995
57685
  }
@@ -56997,13 +57687,14 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
56997
57687
  const hyd = ctx2.hydrate;
56998
57688
  const parent = parentVar || "$root";
56999
57689
  const budget = hyd ? regionBudgetVar2(ctx2, skipK, regionBudget) : null;
57690
+ const rid = regionMarkerId(node);
57000
57691
  const isOpaque = (n) => !!n && typeof n.condition !== "undefined";
57001
57692
  if (hyd && node.alternateNodes.length === 1 && isOpaque(node.alternateNodes[0])) {
57002
57693
  const chain = [];
57003
57694
  let cur = node;
57004
57695
  let finalElse = null;
57005
57696
  while (cur) {
57006
- chain.push({ cond: transformTracked2(cur.condition, tracked2), nodes: cur.consequentNodes });
57697
+ chain.push({ cond: transformTracked2(cur.condition, tracked2), nodes: cur.consequentNodes, id: regionMarkerId(cur) });
57007
57698
  if (cur.alternateNodes.length === 1 && isOpaque(cur.alternateNodes[0])) {
57008
57699
  cur = cur.alternateNodes[0];
57009
57700
  } else {
@@ -57027,6 +57718,9 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57027
57718
  ctx2.push(`const ${rn} = ${fnOpen2}`);
57028
57719
  const cl = ctx2.n();
57029
57720
  ctx2.push(indent3(`const ${cl} = [];`));
57721
+ const savedDescriptor = ctx2.descriptorClaim;
57722
+ if (hyd && ctx2.markerless)
57723
+ ctx2.descriptorClaim = true;
57030
57724
  for (const n of chain[i].nodes) {
57031
57725
  const savedClaim = ctx2.claimStatic;
57032
57726
  if (hyd)
@@ -57036,6 +57730,7 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57036
57730
  if (v)
57037
57731
  ctx2.push(indent3(`${cl}.push(${v});`));
57038
57732
  }
57733
+ ctx2.descriptorClaim = savedDescriptor;
57039
57734
  ctx2.push(indent3(`__place(${anchor2}, ${endAnchor2}, ${cl}, ${parent});`));
57040
57735
  ctx2.push(`};`);
57041
57736
  }
@@ -57045,6 +57740,9 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57045
57740
  ctx2.push(`const ${finalRender} = ${fnOpen2}`);
57046
57741
  const cl2 = ctx2.n();
57047
57742
  ctx2.push(indent3(`const ${cl2} = [];`));
57743
+ const savedDescriptor = ctx2.descriptorClaim;
57744
+ if (hyd && ctx2.markerless)
57745
+ ctx2.descriptorClaim = true;
57048
57746
  for (const n of finalElse) {
57049
57747
  const savedClaim = ctx2.claimStatic;
57050
57748
  if (hyd)
@@ -57054,27 +57752,39 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57054
57752
  if (v)
57055
57753
  ctx2.push(indent3(`${cl2}.push(${v});`));
57056
57754
  }
57755
+ ctx2.descriptorClaim = savedDescriptor;
57057
57756
  ctx2.push(indent3(`__place(${anchor2}, ${endAnchor2}, ${cl2}, ${parent});`));
57058
57757
  ctx2.push(`};`);
57059
57758
  }
57060
- let init = `if (${chain[0].cond}) { ${asyncKw2}${renderNames[0]}(); }`;
57061
- for (let i = 1; i < chain.length; i++)
57062
- init += ` else if (${chain[i].cond}) { ${asyncKw2}${renderNames[i]}(); }`;
57063
- if (finalRender)
57064
- init += ` else { ${asyncKw2}${finalRender}(); }`;
57065
- ctx2.push(init);
57066
57759
  let branchInitFallback = finalRender ? `${chain.length}` : "-1";
57067
57760
  for (let i = chain.length - 1; i >= 0; i--) {
57068
57761
  branchInitFallback = `(${chain[i].cond} ? ${i} : ${branchInitFallback})`;
57069
57762
  }
57070
57763
  const branchInit = `(${branchInitFallback})`;
57764
+ const branchSnapshot = ctx2.n();
57765
+ ctx2.push(`const ${branchSnapshot} = ${branchInit};`);
57766
+ if (!ctx2.markerless) {
57767
+ for (let i = 0; i < chain.length; i++) {
57768
+ ctx2.push(`if (__hydrate) __reconcileRegion(${parent}, '${chain[i].id}', ${branchSnapshot} === ${i} ? 0 : 1, ${ctx2.walker});`);
57769
+ }
57770
+ } else {
57771
+ const chainBranches = chain.map((c) => c.nodes);
57772
+ if (finalElse)
57773
+ chainBranches.push(finalElse);
57774
+ emitStructuralRegionDiscard2(ctx2, chainBranches, branchSnapshot, budget);
57775
+ }
57776
+ let init = `if (${branchSnapshot} === 0) { ${asyncKw2}${renderNames[0]}(); }`;
57777
+ for (let i = 1; i < chain.length; i++)
57778
+ init += ` else if (${branchSnapshot} === ${i}) { ${asyncKw2}${renderNames[i]}(); }`;
57779
+ if (finalRender)
57780
+ init += ` else { ${asyncKw2}${finalRender}(); }`;
57781
+ ctx2.push(init);
57071
57782
  let effInner = `if (__new === 0) { ${asyncKw2}${renderNames[0]}(); }`;
57072
57783
  for (let i = 1; i < chain.length; i++)
57073
57784
  effInner += ` else if (__new === ${i}) { ${asyncKw2}${renderNames[i]}(); }`;
57074
57785
  if (finalRender)
57075
57786
  effInner += ` else { ${asyncKw2}${finalRender}(); }`;
57076
57787
  const effBody = `effect(${ctx2.isAsyncScope ? "async () => {" : "() => {"}
57077
- if (__first) { __first = false; __iv = ${branchInit}; return; }
57078
57788
  const __new = ${branchInit};
57079
57789
  if (__new !== __iv) {
57080
57790
  for (const e of ${effectsVar2}) destroy_block(e);
@@ -57083,17 +57793,15 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57083
57793
  ${effInner}
57084
57794
  __iv = __new;
57085
57795
  }
57086
- });`;
57796
+ }, true);`;
57087
57797
  if (effTarget) {
57088
57798
  ctx2.push(`${effTarget}.push((() => {
57089
- let __iv = ${branchInit};
57090
- let __first = true;
57799
+ let __iv = ${branchSnapshot};
57091
57800
  return ${effBody}
57092
57801
  })());`);
57093
57802
  } else {
57094
57803
  ctx2.effects.push(`{
57095
- let __iv = ${branchInit};
57096
- let __first = true;
57804
+ let __iv = ${branchSnapshot};
57097
57805
  ${effBody}
57098
57806
  }`);
57099
57807
  }
@@ -57121,6 +57829,9 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57121
57829
  ctx2.push(indent3(`const ${conFrag} = document.createDocumentFragment();`));
57122
57830
  if (hyd)
57123
57831
  ctx2.push(indent3(`const __cl = [];`));
57832
+ const savedConDescriptor = ctx2.descriptorClaim;
57833
+ if (hyd && ctx2.markerless)
57834
+ ctx2.descriptorClaim = true;
57124
57835
  for (const n of node.consequentNodes) {
57125
57836
  const savedClaim = ctx2.claimStatic;
57126
57837
  if (hyd)
@@ -57134,6 +57845,7 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57134
57845
  ctx2.push(indent3(`${conFrag}.appendChild(${v});`));
57135
57846
  }
57136
57847
  }
57848
+ ctx2.descriptorClaim = savedConDescriptor;
57137
57849
  if (hyd)
57138
57850
  ctx2.push(indent3(`__place(${anchor}, ${endAnchor}, __cl, ${parent});`));
57139
57851
  else
@@ -57150,6 +57862,9 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57150
57862
  ctx2.push(indent3(`const ${altFrag} = document.createDocumentFragment();`));
57151
57863
  if (hyd)
57152
57864
  ctx2.push(indent3(`const __cl = [];`));
57865
+ const savedAltDescriptor = ctx2.descriptorClaim;
57866
+ if (hyd && ctx2.markerless)
57867
+ ctx2.descriptorClaim = true;
57153
57868
  for (const n of node.alternateNodes) {
57154
57869
  const savedAltClaim = ctx2.claimStatic;
57155
57870
  if (hyd)
@@ -57163,6 +57878,7 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57163
57878
  ctx2.push(indent3(`${altFrag}.appendChild(${v});`));
57164
57879
  }
57165
57880
  }
57881
+ ctx2.descriptorClaim = savedAltDescriptor;
57166
57882
  if (hyd)
57167
57883
  ctx2.push(indent3(`__place(${anchor}, ${endAnchor}, __cl, ${parent});`));
57168
57884
  else
@@ -57171,10 +57887,15 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57171
57887
  }
57172
57888
  if (!hyd)
57173
57889
  ctx2.push(`${parent}.appendChild(${endAnchor});`);
57174
- ctx2.push(`if (${condExpr}) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : ""));
57890
+ const condSnapshot = ctx2.n();
57891
+ ctx2.push(`const ${condSnapshot} = ${condExpr};`);
57892
+ if (hyd && !ctx2.markerless)
57893
+ ctx2.push(`if (__hydrate) __reconcileRegion(${parent}, '${rid}', ${condSnapshot} ? 0 : 1, ${ctx2.walker});`);
57894
+ if (hyd && ctx2.markerless)
57895
+ emitStructuralRegionDiscard2(ctx2, [node.consequentNodes, node.alternateNodes], hasElse ? `(${condSnapshot} ? 0 : 1)` : `(${condSnapshot} ? 0 : -1)`, budget);
57896
+ ctx2.push(`if (${condSnapshot}) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : ""));
57175
57897
  const renderBranch = `if (__nv) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : "");
57176
57898
  const effectBody = `effect(${ctx2.isAsyncScope ? "async () => {" : "() => {"}
57177
- if (__first) { __first = false; __iv = ${condExpr}; return; }
57178
57899
  const __nv = ${condExpr};
57179
57900
  if (__nv !== __iv) {
57180
57901
  for (const e of ${effectsVar}) destroy_block(e);
@@ -57183,19 +57904,17 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57183
57904
  ${renderBranch}
57184
57905
  __iv = __nv;
57185
57906
  }
57186
- });`;
57907
+ }, true);`;
57187
57908
  if (!isReactiveExpression2(node.condition, tracked2))
57188
57909
  return null;
57189
57910
  if (effTarget) {
57190
57911
  ctx2.push(`${effTarget}.push((() => {
57191
- let __iv = ${condExpr};
57192
- let __first = true;
57912
+ let __iv = ${condSnapshot};
57193
57913
  return ${effectBody}
57194
57914
  })());`);
57195
57915
  } else {
57196
57916
  ctx2.effects.push(`{
57197
- let __iv = ${condExpr};
57198
- let __first = true;
57917
+ let __iv = ${condSnapshot};
57199
57918
  ${effectBody}
57200
57919
  }`);
57201
57920
  }
@@ -57284,7 +58003,7 @@ function emitWhileLoop2(ctx2, node, tracked2, parentVar, skipK = 0, regionBudget
57284
58003
  __busy = false;
57285
58004
  __iv = (${condExpr});
57286
58005
  }
57287
- });
58006
+ }, true);
57288
58007
  }`);
57289
58008
  return null;
57290
58009
  }
@@ -57384,7 +58103,7 @@ function emitForLoop2(ctx2, node, tracked2, parentVar, skipK = 0, regionBudget)
57384
58103
  __busy = false;
57385
58104
  __iv = (${srcExpr});
57386
58105
  }
57387
- });
58106
+ }, true);
57388
58107
  }`);
57389
58108
  } else {
57390
58109
  const condReactive = isReactiveExpression2(node.condition, tracked2);
@@ -57449,7 +58168,7 @@ function emitForLoop2(ctx2, node, tracked2, parentVar, skipK = 0, regionBudget)
57449
58168
  __cleanup(${anchor}, ${endAnchor});
57450
58169
  ${ctx2.isAsyncScope ? "await " : ""}${renderLoop}();
57451
58170
  __busy = false;
57452
- });
58171
+ }, true);
57453
58172
  }`);
57454
58173
  }
57455
58174
  }
@@ -57521,7 +58240,7 @@ function emitSwitchBlock2(ctx2, node, tracked2, parentVar, skipK = 0, regionBudg
57521
58240
  __busy = false;
57522
58241
  __iv = (${discExpr});
57523
58242
  }
57524
- });
58243
+ }, true);
57525
58244
  }`);
57526
58245
  return null;
57527
58246
  }
@@ -57630,29 +58349,26 @@ function emitMap2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionB
57630
58349
  let emptyRenderName = null;
57631
58350
  if (node.alternateNodes.length > 0) {
57632
58351
  emptyRenderName = ctx2.n();
57633
- const emptySig = !hyd ? ctx2.isAsyncScope ? "async () => {" : "() => {" : ctx2.isAsyncScope ? "async (__cl) => {" : "(__cl) => {";
58352
+ const emptyClaims = ctx2.hydrate;
58353
+ const emptySig = !emptyClaims ? ctx2.isAsyncScope ? "async () => {" : "() => {" : ctx2.isAsyncScope ? "async (__cl) => {" : "(__cl) => {";
57634
58354
  ctx2.push(`const ${emptyRenderName} = ${emptySig}`);
57635
58355
  ctx2.push(indent3(`const __p = ${anchor}.parentNode;`));
57636
58356
  const frag = ctx2.n();
57637
- if (!hyd)
58357
+ if (!emptyClaims)
57638
58358
  ctx2.push(indent3(`const ${frag} = document.createDocumentFragment();`));
57639
58359
  const savedClaim = ctx2.claimStatic;
57640
- const savedHydrate = ctx2.hydrate;
57641
- if (hydKeyed)
57642
- ctx2.hydrate = false;
57643
58360
  for (const n of node.alternateNodes) {
57644
58361
  ctx2.claimStatic = true;
57645
- const v = emitNode2(ctx2, n, tracked2, effectsVar, hyd ? void 0 : frag, "__components", 0, budget || void 0);
58362
+ const v = emitNode2(ctx2, n, tracked2, effectsVar, emptyClaims ? void 0 : frag, "__components", 0, budget || void 0);
57646
58363
  if (v) {
57647
- if (hyd)
58364
+ if (emptyClaims)
57648
58365
  ctx2.push(indent3(`if (__cl) __cl.push(${v}); else __p.insertBefore(${v}, ${endAnchor});`));
57649
58366
  else
57650
58367
  ctx2.push(indent3(`${frag}.appendChild(${v});`));
57651
58368
  }
57652
58369
  }
57653
58370
  ctx2.claimStatic = savedClaim;
57654
- ctx2.hydrate = savedHydrate;
57655
- if (!hyd)
58371
+ if (!emptyClaims)
57656
58372
  ctx2.push(indent3(`if (${frag}.childNodes.length > 0) __p.insertBefore(${frag}, ${endAnchor});`));
57657
58373
  ctx2.push(`};`);
57658
58374
  }
@@ -57674,8 +58390,13 @@ function emitMap2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionB
57674
58390
  }
57675
58391
  if (emptyRenderName) {
57676
58392
  const isEmptyVar = ctx2.n();
58393
+ const collectVar = hydKeyed ? ctx2.n() : null;
57677
58394
  ctx2.push(`let ${isEmptyVar} = !${hasItems}();`);
57678
- ctx2.push(`if (!${isEmptyVar}) { ${initList}(); } else { ${aw}${emptyRenderName}(); }`);
58395
+ if (collectVar)
58396
+ ctx2.push(`const ${collectVar} = [];`);
58397
+ ctx2.push(`if (!${isEmptyVar}) { ${initList}(); } else { ${aw}${emptyRenderName}(${collectVar || ""}); }`);
58398
+ if (collectVar)
58399
+ ctx2.push(`__place(${anchor}, ${endAnchor}, ${collectVar}, ${parent});`);
57679
58400
  if (!reactiveSource)
57680
58401
  return null;
57681
58402
  pushEffect(`let __first = true;`, `effect(${effOpen}
@@ -57690,7 +58411,7 @@ function emitMap2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionB
57690
58411
  ${effectsVar}.length = 0;
57691
58412
  __cleanup(${anchor}, ${endAnchor});
57692
58413
  if (__new) { ${initList}(); } else { ${aw}${emptyRenderName}(); }
57693
- })`);
58414
+ }, true)`);
57694
58415
  } else {
57695
58416
  ctx2.push(`${initList}();`);
57696
58417
  if (!reactiveSource)
@@ -57699,7 +58420,7 @@ function emitMap2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionB
57699
58420
  const __nv = ${arrExpr};
57700
58421
  if (__first) { __first = false; __nv; ${breakReset}${reconciler}(${arrExpr}); return; }
57701
58422
  ${breakVar ? `if (${breakVar}) ${breakVar} = false;` : ""}${reconciler}(${arrExpr});
57702
- })`);
58423
+ }, true)`);
57703
58424
  }
57704
58425
  } else {
57705
58426
  const renderAllItems = (ind, collect) => {
@@ -57754,8 +58475,8 @@ ${renderAllItems(" ", null)}
57754
58475
  __cleanup(${anchor}, ${endAnchor});
57755
58476
  if (__new) {
57756
58477
  ${renderAllItems(" ", null)}
57757
- } else { ${aw}${emptyRenderName}(${collectVar ? collectVar : ""}); }
57758
- })`);
58478
+ } else { ${aw}${emptyRenderName}(); }
58479
+ }, true)`);
57759
58480
  } else {
57760
58481
  const collectVar = hyd ? ctx2.n() : null;
57761
58482
  if (collectVar)
@@ -57772,7 +58493,7 @@ ${renderAllItems(" ", null)}
57772
58493
  ${effectsVar}.length = 0;
57773
58494
  __cleanup(${anchor}, ${endAnchor});
57774
58495
  ${renderAllItems(" ", null)}
57775
- })`);
58496
+ }, true)`);
57776
58497
  }
57777
58498
  }
57778
58499
  return null;
@@ -57847,6 +58568,8 @@ function generateComponent2(comp, importedNames = /* @__PURE__ */ new Set(), hyd
57847
58568
  }
57848
58569
  }
57849
58570
  }
58571
+ if (ctx2.hydrate && ctx2.markerless)
58572
+ ctx2.descriptorClaim = true;
57850
58573
  for (const node of comp.body) {
57851
58574
  if (node instanceof TrackDecl) {
57852
58575
  if (deferredTrackDecls.has(node))
@@ -57937,6 +58660,33 @@ function buildComponentMap3(irRoot, hydrate = false, alloc, markerless = true) {
57937
58660
  const code = generateComponent2(comp, directNames, hydrate, asyncComps, linkNames, selfClaimNames, alloc, markerless);
57938
58661
  mapLines.push(`${registry}[${JSON.stringify(comp.name)}] = ${code};`);
57939
58662
  }
58663
+ if (hydrate && !markerless) {
58664
+ mapLines.push(`function __reconcileRegion(parent, id, branch, walker) {`);
58665
+ mapLines.push(` if (!parent) return;`);
58666
+ mapLines.push(` let start = null;`);
58667
+ mapLines.push(` let end = null;`);
58668
+ mapLines.push(` for (let n = parent.firstChild; n; n = n.nextSibling) {`);
58669
+ mapLines.push(` if (n.nodeType !== 8) continue;`);
58670
+ mapLines.push(` const text = n.textContent || '';`);
58671
+ mapLines.push(` if (text === 'vesk-r:' + id + ':0' || text === 'vesk-r:' + id + ':1') start = n;`);
58672
+ mapLines.push(` else if (text === 'vesk-r-end:' + id) end = n;`);
58673
+ mapLines.push(` if (start && end) break;`);
58674
+ mapLines.push(` }`);
58675
+ mapLines.push(` if (!start || !end) return;`);
58676
+ mapLines.push(` const ssrBranch = (start.textContent || '').slice(-2) === ':1' ? 1 : 0;`);
58677
+ mapLines.push(` if (ssrBranch !== branch) {`);
58678
+ mapLines.push(` let n = start.nextSibling;`);
58679
+ mapLines.push(` while (n && n !== end) {`);
58680
+ mapLines.push(` const next = n.nextSibling;`);
58681
+ mapLines.push(` n.remove();`);
58682
+ mapLines.push(` n = next;`);
58683
+ mapLines.push(` }`);
58684
+ mapLines.push(` if (walker && walker.retireDetached) walker.retireDetached();`);
58685
+ mapLines.push(` }`);
58686
+ mapLines.push(` start.remove();`);
58687
+ mapLines.push(` end.remove();`);
58688
+ mapLines.push(`}`);
58689
+ }
57940
58690
  mapLines.push(`function __cleanup(start, end) {`);
57941
58691
  mapLines.push(` let n = start.nextSibling;`);
57942
58692
  mapLines.push(` while (n && n !== end) {`);
@@ -58001,6 +58751,50 @@ function ssrResidueEstimate2(node) {
58001
58751
  }
58002
58752
  return 0;
58003
58753
  }
58754
+ function firstBranchRoot2(nodes) {
58755
+ for (const n of nodes) {
58756
+ if (n instanceof StaticNode)
58757
+ return { tag: n.tag, descriptor: staticClassDescriptor2(n) };
58758
+ if (n instanceof ComponentCall || n instanceof ComponentRef)
58759
+ return null;
58760
+ if (n instanceof OpaqueDynamicRegion)
58761
+ return null;
58762
+ if (n instanceof MapRegion || n instanceof ForLoop || n instanceof WhileLoop) {
58763
+ const child = firstBranchRoot2(n.bodyTemplate);
58764
+ if (child)
58765
+ return child;
58766
+ }
58767
+ if (n instanceof SwitchBlock) {
58768
+ for (const c of n.cases) {
58769
+ const child = firstBranchRoot2(c.body);
58770
+ if (child)
58771
+ return child;
58772
+ }
58773
+ }
58774
+ if (n instanceof TryCatch) {
58775
+ const child = firstBranchRoot2(n.bodyTemplate) || firstBranchRoot2(n.catchBody);
58776
+ if (child)
58777
+ return child;
58778
+ }
58779
+ }
58780
+ return null;
58781
+ }
58782
+ function structuralRegionMetadata2(branches) {
58783
+ const parts = branches.map((nodes) => {
58784
+ const first = firstBranchRoot2(nodes);
58785
+ const tag = first ? JSON.stringify(first.tag) : "undefined";
58786
+ const descriptor = first && first.descriptor ? first.descriptor : "null";
58787
+ return `{ tag: ${tag}, descriptor: ${descriptor}, count: ${ssrResidueEstimate2(nodes)} }`;
58788
+ });
58789
+ return `[${parts.join(", ")}]`;
58790
+ }
58791
+ function emitStructuralRegionDiscard2(ctx2, branches, selectedExpr, budget) {
58792
+ if (!ctx2.hydrate || !ctx2.markerless)
58793
+ return;
58794
+ const offset2 = budget ? `, ${budget}` : "";
58795
+ const consume = budget ? ` ${budget} = 0;` : "";
58796
+ ctx2.push(`if (${ctx2.walker} && typeof ${ctx2.walker}.discardStructuralRegion === 'function' && ${ctx2.walker}.discardStructuralRegion(${structuralRegionMetadata2(branches)}, ${selectedExpr}${offset2})) {${consume}}`);
58797
+ }
58004
58798
  function isStaticIR2(body) {
58005
58799
  for (const node of body) {
58006
58800
  if (node instanceof StaticNode) {
@@ -58325,7 +59119,7 @@ init_parser();
58325
59119
  init_tokens();
58326
59120
  init_scan();
58327
59121
  init_strip_ts();
58328
- import { readdirSync as readdirSync8, statSync as statSync13, existsSync as existsSync23, readFileSync as readFileSync25 } from "fs";
59122
+ import { readdirSync as readdirSync8, statSync as statSync13, existsSync as existsSync24, readFileSync as readFileSync25 } from "fs";
58329
59123
  import { join as join17, relative as relative5, basename as basename4 } from "path";
58330
59124
  function collapseSlashes2(p) {
58331
59125
  let out = "";
@@ -58344,7 +59138,7 @@ function collapseSlashes2(p) {
58344
59138
  }
58345
59139
  function isStandaloneLayoutFile(layoutPath) {
58346
59140
  try {
58347
- if (!existsSync23(layoutPath))
59141
+ if (!existsSync24(layoutPath))
58348
59142
  return false;
58349
59143
  const src2 = readFileSync25(layoutPath, "utf-8");
58350
59144
  if (!src2.includes("standalone"))
@@ -58409,7 +59203,7 @@ function isStandaloneLayoutFile(layoutPath) {
58409
59203
  }
58410
59204
  }
58411
59205
  function scanRoutes(appDir, options = {}) {
58412
- if (!existsSync23(appDir)) {
59206
+ if (!existsSync24(appDir)) {
58413
59207
  return [];
58414
59208
  }
58415
59209
  return scanDirectory(appDir, appDir, "/", options);
@@ -58419,7 +59213,7 @@ function capitalize(s) {
58419
59213
  }
58420
59214
  function scanComponents(componentsDir) {
58421
59215
  const map = /* @__PURE__ */ new Map();
58422
- if (!existsSync23(componentsDir))
59216
+ if (!existsSync24(componentsDir))
58423
59217
  return map;
58424
59218
  function walk9(dir, prefix) {
58425
59219
  let entries;
@@ -58735,7 +59529,7 @@ function matchUrl(tree, pathname) {
58735
59529
  }
58736
59530
 
58737
59531
  // ../compiler/dist/api-routes.js
58738
- import { readdirSync as readdirSync9, statSync as statSync14, existsSync as existsSync24 } from "fs";
59532
+ import { readdirSync as readdirSync9, statSync as statSync14, existsSync as existsSync25 } from "fs";
58739
59533
  import { join as join18 } from "path";
58740
59534
  init_server_utils();
58741
59535
  function basename5(p) {
@@ -58743,7 +59537,7 @@ function basename5(p) {
58743
59537
  return idx === -1 ? p : p.slice(idx + 1);
58744
59538
  }
58745
59539
  function scanApiRoutes(apiDir) {
58746
- if (!existsSync24(apiDir))
59540
+ if (!existsSync25(apiDir))
58747
59541
  return [];
58748
59542
  return scanApiDir(apiDir, apiDir, "/");
58749
59543
  }
@@ -59138,7 +59932,7 @@ async function executeRewrite(url, originalRequest) {
59138
59932
  }
59139
59933
 
59140
59934
  // ../compiler/dist/middleware.js
59141
- import { existsSync as existsSync25 } from "fs";
59935
+ import { existsSync as existsSync26 } from "fs";
59142
59936
  import { resolve as resolve22 } from "path";
59143
59937
 
59144
59938
  // ../compiler/src/api-routes.ts
@@ -59199,7 +59993,7 @@ function collectMiddlewareChain(routeTree, url, appDir) {
59199
59993
  function collectForNode(node) {
59200
59994
  if (node.hasMiddleware) {
59201
59995
  const mwPath = resolve22(appDir, node.sourceDir, "middleware.ts");
59202
- if (existsSync25(mwPath)) {
59996
+ if (existsSync26(mwPath)) {
59203
59997
  chain.push({ sourcePath: mwPath, node });
59204
59998
  }
59205
59999
  }
@@ -59370,13 +60164,13 @@ async function executeMiddlewareChain(chain, request, params, options = {}) {
59370
60164
  }
59371
60165
 
59372
60166
  // ../compiler/dist/events.js
59373
- import { existsSync as existsSync26 } from "fs";
60167
+ import { existsSync as existsSync27 } from "fs";
59374
60168
  import { join as join19 } from "path";
59375
60169
  var EVENTS_FILE_NAMES2 = ["_events.ts", "_events.js"];
59376
60170
  function collectEventsFile2(appDir) {
59377
60171
  for (const name of EVENTS_FILE_NAMES2) {
59378
60172
  const candidate = join19(appDir, name);
59379
- if (existsSync26(candidate))
60173
+ if (existsSync27(candidate))
59380
60174
  return candidate;
59381
60175
  }
59382
60176
  return null;
@@ -59406,7 +60200,7 @@ async function runEventHandlers(handlers, name, ctx2) {
59406
60200
  }
59407
60201
 
59408
60202
  // ../compiler/dist/md-inline.js
59409
- import { readFileSync as readFileSync26, existsSync as existsSync27 } from "node:fs";
60203
+ import { readFileSync as readFileSync26, existsSync as existsSync28 } from "node:fs";
59410
60204
  import { dirname as dirname18, join as join20, resolve as resolve23 } from "node:path";
59411
60205
  var MD_EXT_MARKER2 = ".md";
59412
60206
  function looksLikeMarkdownPath2(value) {
@@ -59480,15 +60274,15 @@ function resolveMdPath2(specifier, importerDir, roots) {
59480
60274
  if (!importerDir)
59481
60275
  return null;
59482
60276
  const abs = resolve23(importerDir, spec);
59483
- return existsSync27(abs) ? abs : null;
60277
+ return existsSync28(abs) ? abs : null;
59484
60278
  }
59485
60279
  if (spec.startsWith("/")) {
59486
60280
  for (const root3 of roots) {
59487
60281
  const pub = join20(root3, "public", spec);
59488
- if (existsSync27(pub))
60282
+ if (existsSync28(pub))
59489
60283
  return pub;
59490
60284
  const direct = join20(root3, spec);
59491
- if (existsSync27(direct))
60285
+ if (existsSync28(direct))
59492
60286
  return direct;
59493
60287
  }
59494
60288
  }
@@ -59501,7 +60295,7 @@ function guessProjectRoots2(dir) {
59501
60295
  let cur = dir;
59502
60296
  for (let i = 0; i < 6; i++) {
59503
60297
  roots.push(cur);
59504
- if (existsSync27(join20(cur, "package.json")))
60298
+ if (existsSync28(join20(cur, "package.json")))
59505
60299
  break;
59506
60300
  const parent = dirname18(cur);
59507
60301
  if (parent === cur)
@@ -59512,7 +60306,7 @@ function guessProjectRoots2(dir) {
59512
60306
  }
59513
60307
 
59514
60308
  // ../adapter/dist/client-bundle.js
59515
- import { readFileSync as readFileSync27, existsSync as existsSync28, writeFileSync as writeFileSync13, unlinkSync as unlinkSync4, statSync as statSync15, rmSync as rmSync4, mkdtempSync as mkdtempSync2, mkdirSync as mkdirSync12 } from "node:fs";
60309
+ import { readFileSync as readFileSync27, existsSync as existsSync29, writeFileSync as writeFileSync13, unlinkSync as unlinkSync4, statSync as statSync15, rmSync as rmSync4, mkdtempSync as mkdtempSync2, mkdirSync as mkdirSync12 } from "node:fs";
59516
60310
  import { resolve as resolve24, join as join21, dirname as dirname19, relative as relative6, sep as sep3 } from "node:path";
59517
60311
  import { fileURLToPath as fileURLToPath6 } from "node:url";
59518
60312
  import { tmpdir as tmpdir3 } from "node:os";
@@ -59613,12 +60407,24 @@ function fileUnchanged2(filePath, cached) {
59613
60407
  return false;
59614
60408
  }
59615
60409
  }
59616
- function buildRouterOpts2(options) {
60410
+ function hasServerMiddleware2(nodes) {
60411
+ for (const node of nodes) {
60412
+ if (node.hasMiddleware)
60413
+ return true;
60414
+ if (node.children?.length && hasServerMiddleware2(node.children))
60415
+ return true;
60416
+ }
60417
+ return false;
60418
+ }
60419
+ function buildRouterOpts2(options, serverMiddleware) {
59617
60420
  const ttl = options?.routeDataCache;
60421
+ const opts = [];
60422
+ if (serverMiddleware)
60423
+ opts.push("serverMiddleware: true");
59618
60424
  if (typeof ttl === "number" && ttl > 0) {
59619
- return `, { routeDataCache: ${ttl} }`;
60425
+ opts.push(`routeDataCache: ${ttl}`);
59620
60426
  }
59621
- return "";
60427
+ return opts.length ? `, { ${opts.join(", ")} }` : "";
59622
60428
  }
59623
60429
  function findRuntimeSrc3(appDir) {
59624
60430
  const monorepoRoot = resolve24(__dirname7, "..", "..", "..");
@@ -59629,7 +60435,7 @@ function findRuntimeSrc3(appDir) {
59629
60435
  ];
59630
60436
  for (const base of candidates) {
59631
60437
  for (const dir of [base, join21(base, "dist")]) {
59632
- if (existsSync28(join21(dir, "index-client.js")))
60438
+ if (existsSync29(join21(dir, "index-client.js")))
59633
60439
  return dir;
59634
60440
  }
59635
60441
  }
@@ -59674,7 +60480,7 @@ function isAnyImport2(node) {
59674
60480
  return node.type === "ImportDeclaration";
59675
60481
  }
59676
60482
  function isRuntimePreamble2(node) {
59677
- if (node.type === "FunctionDeclaration" && (node.id?.name === "__cleanup" || node.id?.name === "__place")) {
60483
+ if (node.type === "FunctionDeclaration" && (node.id?.name === "__cleanup" || node.id?.name === "__place" || node.id?.name === "__reconcileRegion")) {
59678
60484
  return true;
59679
60485
  }
59680
60486
  if (node.type === "VariableDeclaration") {
@@ -59800,7 +60606,7 @@ function runtimeImportsOf2(filePath, seen = /* @__PURE__ */ new Set()) {
59800
60606
  ];
59801
60607
  for (const candidate of candidates) {
59802
60608
  try {
59803
- if (!existsSync28(candidate) || !statSync15(candidate).isFile())
60609
+ if (!existsSync29(candidate) || !statSync15(candidate).isFile())
59804
60610
  continue;
59805
60611
  } catch {
59806
60612
  continue;
@@ -60263,31 +61069,31 @@ async function generateClientBundle2(routeTree, appDir, componentMap, options) {
60263
61069
  const chunkCode = [];
60264
61070
  const chunkImports = new ChunkImports2();
60265
61071
  const pagePath = resolve24(appDir, node.sourceDir, "page.vsk");
60266
- if (node.page && existsSync28(pagePath)) {
61072
+ if (node.page && existsSync29(pagePath)) {
60267
61073
  compileFile2(pagePath, node.page, chunkCode, chunkImports);
60268
61074
  }
60269
61075
  const layoutPath = resolve24(appDir, node.sourceDir, "layout.vsk");
60270
- if (node.layout && existsSync28(layoutPath)) {
61076
+ if (node.layout && existsSync29(layoutPath)) {
60271
61077
  compileFile2(layoutPath, node.layout, chunkCode, chunkImports);
60272
61078
  }
60273
61079
  const errorPath = resolve24(appDir, node.sourceDir, "error.vsk");
60274
- if (node.error && existsSync28(errorPath)) {
61080
+ if (node.error && existsSync29(errorPath)) {
60275
61081
  compileFile2(errorPath, node.error, chunkCode, chunkImports);
60276
61082
  }
60277
61083
  const notFoundPath = resolve24(appDir, node.sourceDir, "not-found.vsk");
60278
- if (node.notFound && existsSync28(notFoundPath)) {
61084
+ if (node.notFound && existsSync29(notFoundPath)) {
60279
61085
  compileFile2(notFoundPath, node.notFound, chunkCode, chunkImports);
60280
61086
  }
60281
61087
  const offlinePath = resolve24(appDir, node.sourceDir, "offline.vsk");
60282
- if (node.offline && existsSync28(offlinePath)) {
61088
+ if (node.offline && existsSync29(offlinePath)) {
60283
61089
  compileFile2(offlinePath, node.offline, chunkCode, chunkImports);
60284
61090
  }
60285
61091
  const networkPath = resolve24(appDir, node.sourceDir, "network.vsk");
60286
- if (node.network && existsSync28(networkPath)) {
61092
+ if (node.network && existsSync29(networkPath)) {
60287
61093
  compileFile2(networkPath, node.network, chunkCode, chunkImports);
60288
61094
  }
60289
61095
  const loadingPath = resolve24(appDir, node.sourceDir, "loading.vsk");
60290
- if (node.loading && existsSync28(loadingPath)) {
61096
+ if (node.loading && existsSync29(loadingPath)) {
60291
61097
  compileFile2(loadingPath, node.loading, chunkCode, chunkImports);
60292
61098
  }
60293
61099
  if (chunkCode.length > 0) {
@@ -60359,7 +61165,7 @@ ${body}
60359
61165
  } catch {
60360
61166
  }
60361
61167
  }
60362
- if (file.endsWith(".vsk") || !existsSync28(file))
61168
+ if (file.endsWith(".vsk") || !existsSync29(file))
60363
61169
  continue;
60364
61170
  let needsRuntime = false;
60365
61171
  try {
@@ -60618,25 +61424,25 @@ A module-scope statement runs the moment the browser evaluates the chunk, so a s
60618
61424
  }, walkMono2 = function(nodes) {
60619
61425
  for (const node of nodes) {
60620
61426
  const pagePath = resolve24(appDir, node.sourceDir, "page.vsk");
60621
- if (node.page && existsSync28(pagePath))
61427
+ if (node.page && existsSync29(pagePath))
60622
61428
  compileFileMono2(pagePath, node.page);
60623
61429
  const layoutPath = resolve24(appDir, node.sourceDir, "layout.vsk");
60624
- if (node.layout && existsSync28(layoutPath))
61430
+ if (node.layout && existsSync29(layoutPath))
60625
61431
  compileFileMono2(layoutPath, node.layout);
60626
61432
  const errorPath = resolve24(appDir, node.sourceDir, "error.vsk");
60627
- if (node.error && existsSync28(errorPath))
61433
+ if (node.error && existsSync29(errorPath))
60628
61434
  compileFileMono2(errorPath, node.error);
60629
61435
  const notFoundPath = resolve24(appDir, node.sourceDir, "not-found.vsk");
60630
- if (node.notFound && existsSync28(notFoundPath))
61436
+ if (node.notFound && existsSync29(notFoundPath))
60631
61437
  compileFileMono2(notFoundPath, node.notFound);
60632
61438
  const offlinePath = resolve24(appDir, node.sourceDir, "offline.vsk");
60633
- if (node.offline && existsSync28(offlinePath))
61439
+ if (node.offline && existsSync29(offlinePath))
60634
61440
  compileFileMono2(offlinePath, node.offline);
60635
61441
  const networkPath = resolve24(appDir, node.sourceDir, "network.vsk");
60636
- if (node.network && existsSync28(networkPath))
61442
+ if (node.network && existsSync29(networkPath))
60637
61443
  compileFileMono2(networkPath, node.network);
60638
61444
  const loadingPath = resolve24(appDir, node.sourceDir, "loading.vsk");
60639
- if (node.loading && existsSync28(loadingPath))
61445
+ if (node.loading && existsSync29(loadingPath))
60640
61446
  compileFileMono2(loadingPath, node.loading);
60641
61447
  walkMono2(node.children || []);
60642
61448
  }
@@ -60680,16 +61486,22 @@ A module-scope statement runs the moment the browser evaluates the chunk, so a s
60680
61486
  loader: { ".js": "tsx" },
60681
61487
  legalComments: "none",
60682
61488
  ...appTsconfig ? { tsconfig: appTsconfig } : {},
60683
- // Stub optional CJS deps (qrcode-generator via vesk-qr, canvas,
60684
- // @zxing/*) so esbuild never bundles their CJS source into the client
60685
- // bundle — that would emit a `__require` shim that throws in the
60686
- // browser. vesk-qr now lazy-loads them via dynamic import; stubbing
60687
- // keeps the bundle valid ESM without shipping dead code.
61489
+ // Stub only the OPTIONAL CJS deps (canvas for raster export, @zxing/*
61490
+ // for scan validation). They degrade gracefully and their absence must
61491
+ // not break the bundle.
61492
+ //
61493
+ // `qrcode-generator` must NOT be stubbed: it is the pure-JS encoder
61494
+ // every client-side QR (vesk-qr's dynamic `import("qrcode-generator")`)
61495
+ // runs on. Stubbing it to `export {}` makes `getQrcode()` resolve to an
61496
+ // empty object, so `CofoundrMatrix.generate()` throws
61497
+ // "QREncodingError: generator is not a function" during hydration and
61498
+ // the page falls back to the client error boundary. esbuild bundles it
61499
+ // as CJS fine; only genuinely Node-only/optional deps belong here.
60688
61500
  plugins: [
60689
61501
  {
60690
61502
  name: "stub-browser-packages",
60691
61503
  setup(b) {
60692
- b.onResolve({ filter: /^(qrcode-generator|canvas|@zxing\/(browser|node))(\/|$)/ }, (args2) => ({ path: args2.path, namespace: "browser-stub" }));
61504
+ b.onResolve({ filter: /^(canvas|@zxing\/(browser|node))(\/|$)/ }, (args2) => ({ path: args2.path, namespace: "browser-stub" }));
60693
61505
  b.onLoad({ filter: /.*/, namespace: "browser-stub" }, () => ({
60694
61506
  contents: "export {}\n",
60695
61507
  loader: "js"
@@ -60740,7 +61552,7 @@ function buildRuntimeCode2(runtimeDir) {
60740
61552
  let code = "";
60741
61553
  for (const f of runtimeFiles) {
60742
61554
  const p = join21(runtimeDir, f);
60743
- if (existsSync28(p)) {
61555
+ if (existsSync29(p)) {
60744
61556
  let src2 = readFileSync27(p, "utf-8");
60745
61557
  src2 = stripTypes2(src2);
60746
61558
  src2 = src2.replace(/^import\s+[\s\S]*?from\s+['"](?:\.\/.*?|@vesk\/runtime\/src\/.*?)['"];?\n?/gm, "");
@@ -60902,12 +61714,13 @@ async function buildMainBundle2(routeTree, runtimeDir, codeSplit, mono, hmr, imp
60902
61714
  ` : runtimeCode + "\n";
60903
61715
  const cleanupFn = "function __cleanup(start, end) {\n let n = start.nextSibling;\n while (n && n !== end) {\n const next = n.nextSibling;\n n.remove();\n n = next;\n }\n}\n";
60904
61716
  const placeFn = "function __place(start, end, nodes, fallback) {\n if (start.parentNode !== null) {\n const p = start.parentNode;\n for (let i = 0; i < nodes.length; i++) p.insertBefore(nodes[i], end);\n return;\n }\n if (nodes.length > 0 && nodes[0].parentNode) {\n const p = nodes[0].parentNode;\n p.insertBefore(start, nodes[0]);\n p.insertBefore(end, nodes[nodes.length - 1].nextSibling);\n // Client-surplus nodes (SSR rendered fewer items than the client data)\n // are freshly claimed and still detached \u2014 move them into the region in\n // client order before `end`, instead of stranding them off-parent.\n for (let i = 0; i < nodes.length; i++) {\n if (nodes[i].parentNode === null) p.insertBefore(nodes[i], end);\n }\n return;\n }\n fallback.appendChild(start);\n fallback.appendChild(end);\n for (let i = 0; i < nodes.length; i++) fallback.insertBefore(nodes[i], end);\n}\n";
61717
+ const reconcileRegionFn = "function __reconcileRegion(parent, id, branch, walker) {\n if (!parent) return;\n let start = null;\n let end = null;\n for (let n = parent.firstChild; n; n = n.nextSibling) {\n if (n.nodeType !== 8) continue;\n const text = n.textContent || '';\n if (text === 'vesk-r:' + id + ':0' || text === 'vesk-r:' + id + ':1') start = n;\n else if (text === 'vesk-r-end:' + id) end = n;\n if (start && end) break;\n }\n if (!start || !end) return;\n const ssrBranch = (start.textContent || '').slice(-2) === ':1' ? 1 : 0;\n if (ssrBranch !== branch) {\n let n = start.nextSibling;\n while (n && n !== end) {\n const next = n.nextSibling;\n n.remove();\n n = next;\n }\n if (walker && walker.retireDetached) walker.retireDetached();\n }\n start.remove();\n end.remove();\n}\n";
60905
61718
  const updateComponentsFn = "function __updateComponents(nodes) {\n for (const n of nodes) {\n if (n._pageName && __components[n._pageName]) n.page = __components[n._pageName];\n if (n._layoutName && __components[n._layoutName]) n.layout = __components[n._layoutName];\n if (n._errorName && __components[n._errorName]) n.error = __components[n._errorName];\n if (n._notFoundName && __components[n._notFoundName]) n.notFound = __components[n._notFoundName];\n if (n._offlineName && __components[n._offlineName]) n.offline = __components[n._offlineName];\n if (n._networkName && __components[n._networkName]) n.network = __components[n._networkName];\n if (n.children) __updateComponents(n.children);\n }\n}\n";
60906
61719
  const routeTreeJson = JSON.stringify(routeTree);
60907
61720
  if (codeSplit) {
60908
61721
  const resolveNamesFn = "function __resolveNames(nodes) {\n for (const n of nodes) {\n if (n.chunk) n._chunk = n.chunk;\n if (n.chunkError) n._chunkError = n.chunkError;\n if (typeof n.page === 'string') n._pageName = n.page;\n if (typeof n.layout === 'string') n._layoutName = n.layout;\n if (typeof n.error === 'string') n._errorName = n.error;\n if (typeof n.notFound === 'string') n._notFoundName = n.notFound;\n if (typeof n.offline === 'string') n._offlineName = n.offline;\n if (typeof n.network === 'string') n._networkName = n.network;\n if (n.children) __resolveNames(n.children);\n }\n}\n";
60909
61722
  const pendCode = "const __pendChunks = [];\nconst __currentPath = typeof window !== 'undefined' ? window.location.pathname : '/';\nif (typeof matchRoute === 'function') {\n const __currentMatch = matchRoute(__routeTree, __currentPath);\n if (__currentMatch) {\n for (const n of __currentMatch.matchChain) {\n if (n._chunk && !__pendChunks.includes(n._chunk)) __pendChunks.push(n._chunk);\n }\n }\n}\n";
60910
- const routerOpts2 = buildRouterOpts2({ routeDataCache });
61723
+ const routerOpts2 = buildRouterOpts2({ routeDataCache }, hasServerMiddleware2(routeTree));
60911
61724
  const startRouterCode = `const __startRouter = function() {
60912
61725
  __updateComponents(__routeTree);
60913
61726
  const __router = createFileRouter(__routeTree${routerOpts2});
@@ -60946,14 +61759,14 @@ if (__pendChunks.length > 0 && typeof ensureChunk === 'function') {
60946
61759
  ];
60947
61760
  const importedSet = new Set(allRuntimeImports);
60948
61761
  const runtimeGlobals2 = globalNames.filter((n) => importedSet.has(n)).map((n) => `globalThis.${n} = ${n};
60949
- `).join("") + "globalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\n\n";
61762
+ `).join("") + "globalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\nglobalThis.__reconcileRegion = __reconcileRegion;\n\n";
60950
61763
  const extraGlobals = [...runtimeImportNames || []].filter((n) => n && n !== "default").map((n) => `globalThis.${n} = ${n};
60951
61764
  `).join("");
60952
61765
  const code2 = preamble + "const __components = globalThis.__components || (globalThis.__components = {});\nconst __hydrators = globalThis.__hydrators || (globalThis.__hydrators = {});\nconst __runtime_comps = __components;\n\n" + runtimeGlobals2 + extraGlobals + // Shared app modules run HERE: after the runtime bindings are published,
60953
61766
  // before anything can request a route chunk. Earlier (at the top of the
60954
61767
  // bundle) `globalThis.track` was still undefined, so every module-scope
60955
61768
  // cell in a store was created against a missing runtime.
60956
- (sharedModuleBundle ? sharedModuleBundle + "\n" : "") + cleanupFn + placeFn + "globalThis.__components = __components;\n" + resolveNamesFn + updateComponentsFn + "const __routeTree = " + routeTreeJson + ";\n__resolveNames(__routeTree);\n" + pendCode + startRouterCode;
61769
+ (sharedModuleBundle ? sharedModuleBundle + "\n" : "") + cleanupFn + placeFn + reconcileRegionFn + "globalThis.__components = __components;\n" + resolveNamesFn + updateComponentsFn + "const __routeTree = " + routeTreeJson + ";\n__resolveNames(__routeTree);\n" + pendCode + startRouterCode;
60957
61770
  return hmr ? appendHmrGlobals2(code2) : code2;
60958
61771
  }
60959
61772
  const componentLines = mono?.componentLines || [];
@@ -60962,8 +61775,8 @@ if (__pendChunks.length > 0 && typeof ensureChunk === 'function') {
60962
61775
  const hydratorAliasLines = mono?.hydratorAliasLines || [];
60963
61776
  const aliasCode = aliasLines.length > 0 ? aliasLines.join("\n") + "\n" : "";
60964
61777
  const hydratorAliasCode = hydratorAliasLines.length > 0 ? hydratorAliasLines.join("\n") + "\n" : "";
60965
- const routerOpts = buildRouterOpts2({ routeDataCache });
60966
- const code = preamble + "const __components = {};\nconst __hydrators = {};\nconst __runtime_comps = __components;\n\n" + componentLines.join("\n\n") + "\n" + aliasCode + hydratorLines.join("\n\n") + "\n" + hydratorAliasCode + cleanupFn + placeFn + "globalThis.__components = __components;\nglobalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\n" + allRuntimeImports.map((n) => `globalThis.${n} = ${n};
61778
+ const routerOpts = buildRouterOpts2({ routeDataCache }, hasServerMiddleware2(routeTree));
61779
+ const code = preamble + "const __components = {};\nconst __hydrators = {};\nconst __runtime_comps = __components;\n\n" + componentLines.join("\n\n") + "\n" + aliasCode + hydratorLines.join("\n\n") + "\n" + hydratorAliasCode + cleanupFn + placeFn + reconcileRegionFn + "globalThis.__components = __components;\nglobalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\nglobalThis.__reconcileRegion = __reconcileRegion;\n" + allRuntimeImports.map((n) => `globalThis.${n} = ${n};
60967
61780
  `).join("") + "function __resolveNames(nodes) {\n for (const n of nodes) {\n if (typeof n.page === 'string') {\n n._pageName = n.page;\n n.page = __components[n.page];\n }\n if (typeof n.layout === 'string') {\n n._layoutName = n.layout;\n n.layout = __components[n.layout];\n }\n if (typeof n.error === 'string') n.error = __components[n.error];\n if (typeof n.notFound === 'string') n.notFound = __components[n.notFound];\n if (typeof n.offline === 'string') n.offline = __components[n.offline];\n if (typeof n.network === 'string') n.network = __components[n.network];\n if (n.children) __resolveNames(n.children);\n }\n}\n" + updateComponentsFn + "const __routeTree = " + routeTreeJson + `;
60968
61781
  __resolveNames(__routeTree);
60969
61782
  const __router = createFileRouter(__routeTree${routerOpts});
@@ -60977,7 +61790,7 @@ if (typeof document !== 'undefined') __router.start();
60977
61790
 
60978
61791
  // ../adapter/dist/paths.js
60979
61792
  import { resolve as resolve25, sep as sep4 } from "node:path";
60980
- import { existsSync as existsSync29, statSync as statSync16, readFileSync as readFileSync28 } from "node:fs";
61793
+ import { existsSync as existsSync30, statSync as statSync16, readFileSync as readFileSync28 } from "node:fs";
60981
61794
  function resolveWithin2(baseDir, relPath) {
60982
61795
  const base = resolve25(baseDir);
60983
61796
  const target = resolve25(baseDir, relPath);
@@ -61000,7 +61813,7 @@ function installMdReadHook2(publicDirs) {
61000
61813
  const lower2 = abs.toLowerCase();
61001
61814
  if (!lower2.endsWith(".md") && !lower2.endsWith(".markdown"))
61002
61815
  continue;
61003
- if (existsSync29(abs) && statSync16(abs).isFile())
61816
+ if (existsSync30(abs) && statSync16(abs).isFile())
61004
61817
  return readFileSync28(abs, "utf8");
61005
61818
  } catch {
61006
61819
  }
@@ -61068,12 +61881,12 @@ function urlAuthority3(url) {
61068
61881
  }
61069
61882
 
61070
61883
  // ../adapter/dist/dev-api.js
61071
- import { readFileSync as readFileSync31, statSync as statSync18, existsSync as existsSync32, readdirSync as readdirSync10 } from "node:fs";
61884
+ import { readFileSync as readFileSync31, statSync as statSync18, existsSync as existsSync33, readdirSync as readdirSync10 } from "node:fs";
61072
61885
  import { resolve as resolve28 } from "node:path";
61073
61886
 
61074
61887
  // ../adapter/dist/plugins.js
61075
61888
  init_paths();
61076
- import { readFileSync as readFileSync29, writeFileSync as writeFileSync14, existsSync as existsSync30, mkdirSync as mkdirSync13, statSync as statSync17 } from "node:fs";
61889
+ import { readFileSync as readFileSync29, writeFileSync as writeFileSync14, existsSync as existsSync31, mkdirSync as mkdirSync13, statSync as statSync17 } from "node:fs";
61077
61890
  import { resolve as resolve26, dirname as dirname20, join as join22, extname as extname6, basename as basename6 } from "node:path";
61078
61891
  import { createRequire as createRequire6 } from "node:module";
61079
61892
  import { spawn as spawn2 } from "node:child_process";
@@ -61093,7 +61906,7 @@ function stateFilePath2(veskDir) {
61093
61906
  }
61094
61907
  function readPluginState2(veskDir) {
61095
61908
  const file = stateFilePath2(veskDir);
61096
- if (!existsSync30(file))
61909
+ if (!existsSync31(file))
61097
61910
  return defaultState2();
61098
61911
  let raw2;
61099
61912
  try {
@@ -61116,7 +61929,7 @@ function readPluginState2(veskDir) {
61116
61929
  function writePluginState2(veskDir, state) {
61117
61930
  const file = stateFilePath2(veskDir);
61118
61931
  const dir = dirname20(file);
61119
- if (!existsSync30(dir))
61932
+ if (!existsSync31(dir))
61120
61933
  mkdirSync13(dir, { recursive: true });
61121
61934
  writeFileSync14(file, JSON.stringify(state, null, 2) + "\n", "utf-8");
61122
61935
  }
@@ -61135,7 +61948,7 @@ function resolvePackage2(appDir, pkg) {
61135
61948
  while (cur && cur !== dirname20(cur) && !seen.has(cur)) {
61136
61949
  seen.add(cur);
61137
61950
  const candidate = join22(cur, "package.json");
61138
- if (existsSync30(candidate)) {
61951
+ if (existsSync31(candidate)) {
61139
61952
  pkgJsonPath = candidate;
61140
61953
  break;
61141
61954
  }
@@ -61147,7 +61960,7 @@ function resolvePackage2(appDir, pkg) {
61147
61960
  } catch {
61148
61961
  }
61149
61962
  }
61150
- if (pkgJsonPath && existsSync30(pkgJsonPath)) {
61963
+ if (pkgJsonPath && existsSync31(pkgJsonPath)) {
61151
61964
  pkgJson = readJsonFile2(pkgJsonPath);
61152
61965
  const main = pkgJson?.main || pkgJson?.module || "index.js";
61153
61966
  entryPath = resolve26(dirname20(pkgJsonPath), main);
@@ -61165,30 +61978,30 @@ function resolvePackage2(appDir, pkg) {
61165
61978
  if (localPath) {
61166
61979
  const localJson = join22(localPath, "package.json");
61167
61980
  let json = null;
61168
- if (existsSync30(localJson)) {
61981
+ if (existsSync31(localJson)) {
61169
61982
  json = readJsonFile2(localJson);
61170
61983
  }
61171
61984
  return { installed: true, path: localPath, dir: localPath, packageJson: json ?? pkgJson };
61172
61985
  }
61173
- const installed2 = !!pkgJsonPath && existsSync30(pkgJsonPath);
61986
+ const installed2 = !!pkgJsonPath && existsSync31(pkgJsonPath);
61174
61987
  return { installed: installed2, path: entryPath, dir: installed2 ? dirname20(pkgJsonPath) : null, packageJson: pkgJson };
61175
61988
  }
61176
61989
  function localDir2(base, pkg) {
61177
61990
  if (pkg.startsWith("@")) {
61178
61991
  const parts = pkg.split("/");
61179
61992
  const p2 = resolve26(base, parts[0], parts[1] ?? "");
61180
- if (existsSync30(p2))
61993
+ if (existsSync31(p2))
61181
61994
  return p2;
61182
61995
  return null;
61183
61996
  }
61184
61997
  const p = resolve26(base, pkg);
61185
- if (existsSync30(p))
61998
+ if (existsSync31(p))
61186
61999
  return p;
61187
62000
  return null;
61188
62001
  }
61189
62002
  function readJsonFile2(file) {
61190
62003
  try {
61191
- if (existsSync30(file))
62004
+ if (existsSync31(file))
61192
62005
  return JSON.parse(readFileSync29(file, "utf-8"));
61193
62006
  } catch {
61194
62007
  }
@@ -61472,12 +62285,12 @@ function findIconFile2(dir, meta) {
61472
62285
  const explicit = str2(meta?.icon);
61473
62286
  if (explicit) {
61474
62287
  const p = resolveWithin(dir, explicit);
61475
- if (p && existsSync30(p) && statSync17(p).isFile())
62288
+ if (p && existsSync31(p) && statSync17(p).isFile())
61476
62289
  return p;
61477
62290
  }
61478
62291
  for (const name of ["icon.png", "icon.ico"]) {
61479
62292
  const p = resolve26(dir, name);
61480
- if (existsSync30(p) && statSync17(p).isFile())
62293
+ if (existsSync31(p) && statSync17(p).isFile())
61481
62294
  return p;
61482
62295
  }
61483
62296
  return null;
@@ -61562,7 +62375,7 @@ function resolveDtsPath2(probe, pkgJson) {
61562
62375
  if (!rel)
61563
62376
  continue;
61564
62377
  const abs = resolveWithin(dir, rel);
61565
- if (abs && existsSync30(abs) && statSync17(abs).isFile())
62378
+ if (abs && existsSync31(abs) && statSync17(abs).isFile())
61566
62379
  return abs;
61567
62380
  }
61568
62381
  return null;
@@ -62049,16 +62862,16 @@ var __internals2 = {
62049
62862
  };
62050
62863
 
62051
62864
  // ../adapter/dist/dev-config.js
62052
- import { existsSync as existsSync31, readFileSync as readFileSync30, writeFileSync as writeFileSync15, mkdirSync as mkdirSync14, mkdtempSync as mkdtempSync3, rmSync as rmSync5 } from "node:fs";
62865
+ import { existsSync as existsSync32, readFileSync as readFileSync30, writeFileSync as writeFileSync15, mkdirSync as mkdirSync14, mkdtempSync as mkdtempSync3, rmSync as rmSync5 } from "node:fs";
62053
62866
  import { tmpdir as tmpdir4 } from "node:os";
62054
62867
  import { resolve as resolve27, dirname as dirname21, join as join23 } from "node:path";
62055
62868
  init_parser();
62056
62869
  function findConfigFile2(projectDir) {
62057
62870
  const ts9 = resolve27(projectDir, "vesk.config.ts");
62058
- if (existsSync31(ts9))
62871
+ if (existsSync32(ts9))
62059
62872
  return { path: ts9, isTs: true };
62060
62873
  const js = resolve27(projectDir, "vesk.config.js");
62061
- if (existsSync31(js))
62874
+ if (existsSync32(js))
62062
62875
  return { path: js, isTs: false };
62063
62876
  return { path: null, isTs: false };
62064
62877
  }
@@ -63190,7 +64003,7 @@ function createDevApiRouter2(opts) {
63190
64003
  const resolved = resolveWithin2(projectDir, target);
63191
64004
  if (!resolved)
63192
64005
  return jsonStatus(403, { error: "path escapes project root" });
63193
- if (!existsSync32(resolved))
64006
+ if (!existsSync33(resolved))
63194
64007
  return jsonStatus(404, { error: "not found" });
63195
64008
  if (statSync18(resolved).isDirectory()) {
63196
64009
  const entries = readdirSync10(resolved, { withFileTypes: true }).map((e) => e.name);
@@ -63390,7 +64203,7 @@ function produceDiagnostics(input) {
63390
64203
  }
63391
64204
 
63392
64205
  // ../agentic/dist/checkpoints.js
63393
- import { existsSync as existsSync33, mkdirSync as mkdirSync15, readFileSync as readFileSync32, writeFileSync as writeFileSync16, statSync as statSync19, unlinkSync as unlinkSync5, rmSync as rmSync6, renameSync } from "node:fs";
64206
+ import { existsSync as existsSync34, mkdirSync as mkdirSync15, readFileSync as readFileSync32, writeFileSync as writeFileSync16, statSync as statSync19, unlinkSync as unlinkSync5, rmSync as rmSync6, renameSync } from "node:fs";
63394
64207
  import { join as join24, resolve as resolve29, dirname as dirname22, sep as sep5 } from "node:path";
63395
64208
  import { randomUUID as nodeRandomUUID } from "node:crypto";
63396
64209
  function generateId() {
@@ -63540,7 +64353,7 @@ function ensureDir(dir) {
63540
64353
  }
63541
64354
  function readJson(filePath, fallback) {
63542
64355
  try {
63543
- if (!existsSync33(filePath))
64356
+ if (!existsSync34(filePath))
63544
64357
  return fallback;
63545
64358
  const raw2 = readFileSync32(filePath, "utf-8");
63546
64359
  if (raw2.trim() === "")
@@ -63641,7 +64454,7 @@ function rollback(projectDir, id) {
63641
64454
  const abs = resolve29(projectRoot, f.path);
63642
64455
  if (f.before === null) {
63643
64456
  try {
63644
- if (existsSync33(abs)) {
64457
+ if (existsSync34(abs)) {
63645
64458
  const s = statSync19(abs);
63646
64459
  if (s.isDirectory())
63647
64460
  rmSync6(abs, { recursive: true, force: true });
@@ -63662,7 +64475,7 @@ function rollback(projectDir, id) {
63662
64475
  }
63663
64476
 
63664
64477
  // ../agentic/dist/config.js
63665
- import { readFileSync as readFileSync33, writeFileSync as writeFileSync17, existsSync as existsSync34, mkdirSync as mkdirSync16, chmodSync } from "node:fs";
64478
+ import { readFileSync as readFileSync33, writeFileSync as writeFileSync17, existsSync as existsSync35, mkdirSync as mkdirSync16, chmodSync } from "node:fs";
63666
64479
  import { resolve as resolve30, dirname as dirname23 } from "node:path";
63667
64480
  var DEFAULT_CONFIG = {
63668
64481
  provider: "openai",
@@ -63709,7 +64522,7 @@ function dotenvPath(projectDir) {
63709
64522
  function readDotenvValue(projectDir, key, def = null) {
63710
64523
  try {
63711
64524
  const p = dotenvPath(projectDir);
63712
- if (!existsSync34(p))
64525
+ if (!existsSync35(p))
63713
64526
  return def;
63714
64527
  const content = readFileSync33(p, "utf-8");
63715
64528
  for (const rawLine of content.split("\n")) {
@@ -63738,7 +64551,7 @@ function writeDotenvValue(projectDir, key, value) {
63738
64551
  try {
63739
64552
  let out = "";
63740
64553
  let replaced = false;
63741
- if (existsSync34(p)) {
64554
+ if (existsSync35(p)) {
63742
64555
  const lines = readFileSync33(p, "utf-8").split("\n");
63743
64556
  for (const rawLine of lines) {
63744
64557
  const trimmed = rawLine.trim();
@@ -63768,7 +64581,7 @@ function loadAgenticConfig(projectDir) {
63768
64581
  const p = configPath(projectDir);
63769
64582
  let cfg = { ...DEFAULT_CONFIG };
63770
64583
  try {
63771
- if (existsSync34(p))
64584
+ if (existsSync35(p))
63772
64585
  cfg = { ...cfg, ...JSON.parse(readFileSync33(p, "utf-8")) };
63773
64586
  } catch {
63774
64587
  }
@@ -63811,7 +64624,7 @@ function getProviderSpecificKey(projectDir, provider) {
63811
64624
  return dotenvFile.trim();
63812
64625
  try {
63813
64626
  const pp2 = providerKeyPath(projectDir, prov);
63814
- if (existsSync34(pp2)) {
64627
+ if (existsSync35(pp2)) {
63815
64628
  const v = readFileSync33(pp2, "utf-8").trim();
63816
64629
  if (v)
63817
64630
  return v;
@@ -63859,7 +64672,7 @@ function getApiKey(projectDir, provider) {
63859
64672
  }
63860
64673
  try {
63861
64674
  const pp2 = providerKeyPath(projectDir, prov);
63862
- if (existsSync34(pp2)) {
64675
+ if (existsSync35(pp2)) {
63863
64676
  const v = readFileSync33(pp2, "utf-8").trim();
63864
64677
  if (v)
63865
64678
  return v;
@@ -63883,7 +64696,7 @@ function getApiKey(projectDir, provider) {
63883
64696
  }
63884
64697
 
63885
64698
  // ../agentic/dist/dev-api.js
63886
- import { existsSync as existsSync35, readFileSync as readFileSync34 } from "node:fs";
64699
+ import { existsSync as existsSync36, readFileSync as readFileSync34 } from "node:fs";
63887
64700
  import { resolve as resolve31 } from "node:path";
63888
64701
 
63889
64702
  // ../agentic/dist/providers/openai.js
@@ -64255,7 +65068,7 @@ function getPerProviderKeyRaw(projectDir, provider) {
64255
65068
  }
64256
65069
  try {
64257
65070
  const p = resolve31(projectDir, ".vesk", "agentic", "keys", `${sanitizeProviderName(prov)}.key`);
64258
- if (existsSync35(p)) {
65071
+ if (existsSync36(p)) {
64259
65072
  const v = readFileSync34(p, "utf-8").trim();
64260
65073
  if (v)
64261
65074
  return v;
@@ -65117,7 +65930,7 @@ var Agent = class {
65117
65930
  };
65118
65931
 
65119
65932
  // ../agentic/dist/tools/vesk.js
65120
- import { existsSync as existsSync36, readFileSync as readFileSync35, writeFileSync as writeFileSync18, mkdirSync as mkdirSync17, readdirSync as readdirSync11, statSync as statSync20 } from "node:fs";
65933
+ import { existsSync as existsSync37, readFileSync as readFileSync35, writeFileSync as writeFileSync18, mkdirSync as mkdirSync17, readdirSync as readdirSync11, statSync as statSync20 } from "node:fs";
65121
65934
  import { resolve as resolve32, join as join25, dirname as dirname24, sep as sep6 } from "node:path";
65122
65935
  function resolveWithin3(baseDir, relPath) {
65123
65936
  const base = resolve32(baseDir);
@@ -65133,7 +65946,7 @@ function stateFilePath3(veskDir) {
65133
65946
  }
65134
65947
  function readPluginState3(veskDir) {
65135
65948
  const file = stateFilePath3(veskDir);
65136
- if (!existsSync36(file))
65949
+ if (!existsSync37(file))
65137
65950
  return { version: 1, plugins: [] };
65138
65951
  try {
65139
65952
  const raw2 = JSON.parse(readFileSync35(file, "utf-8"));
@@ -65172,10 +65985,10 @@ function validatePackageSpec3(pkg) {
65172
65985
  }
65173
65986
  function findConfigFile3(projectDir) {
65174
65987
  const ts9 = resolve32(projectDir, "vesk.config.ts");
65175
- if (existsSync36(ts9))
65988
+ if (existsSync37(ts9))
65176
65989
  return { path: ts9, isTs: true };
65177
65990
  const js = resolve32(projectDir, "vesk.config.js");
65178
- if (existsSync36(js))
65991
+ if (existsSync37(js))
65179
65992
  return { path: js, isTs: false };
65180
65993
  return { path: null, isTs: false };
65181
65994
  }
@@ -65324,16 +66137,16 @@ function createVeskTools(deps) {
65324
66137
  },
65325
66138
  async execute(_args) {
65326
66139
  try {
65327
- const projExists = existsSync36(projectDir);
66140
+ const projExists = existsSync37(projectDir);
65328
66141
  const projEntries = projExists ? readdirSync11(projectDir, { withFileTypes: true }).map((e) => e.isDirectory() ? e.name + "/" : e.name) : [];
65329
- const appExists = existsSync36(appDir);
66142
+ const appExists = existsSync37(appDir);
65330
66143
  const appEntries = appExists ? readdirSync11(appDir, { withFileTypes: true }).map((e) => e.isDirectory() ? e.name + "/" : e.name) : [];
65331
- const veskExists = existsSync36(veskDir);
66144
+ const veskExists = existsSync37(veskDir);
65332
66145
  const veskEntries = veskExists ? readdirSync11(veskDir, { withFileTypes: true }).map((e) => e.isDirectory() ? e.name + "/" : e.name) : [];
65333
66146
  const cfgInfo = findConfigFile3(projectDir);
65334
66147
  let configSource = null;
65335
66148
  let configExists = false;
65336
- if (cfgInfo.path && existsSync36(cfgInfo.path)) {
66149
+ if (cfgInfo.path && existsSync37(cfgInfo.path)) {
65337
66150
  configExists = true;
65338
66151
  try {
65339
66152
  configSource = readFileSync35(cfgInfo.path, "utf-8").slice(0, 8e3);
@@ -65343,7 +66156,7 @@ function createVeskTools(deps) {
65343
66156
  }
65344
66157
  let packageJson = null;
65345
66158
  const pkgPath = resolve32(projectDir, "package.json");
65346
- if (existsSync36(pkgPath)) {
66159
+ if (existsSync37(pkgPath)) {
65347
66160
  try {
65348
66161
  packageJson = JSON.parse(readFileSync35(pkgPath, "utf-8"));
65349
66162
  } catch {
@@ -65425,7 +66238,7 @@ function createVeskTools(deps) {
65425
66238
  resolved = resolveWithin3(appDir, rel);
65426
66239
  if (!resolved)
65427
66240
  return jsonError("path escapes project root", { path: rel });
65428
- if (!existsSync36(resolved))
66241
+ if (!existsSync37(resolved))
65429
66242
  return jsonError("not found", { path: rel });
65430
66243
  const st = statSync20(resolved);
65431
66244
  if (st.isDirectory()) {
@@ -65466,7 +66279,7 @@ function createVeskTools(deps) {
65466
66279
  }
65467
66280
  }
65468
66281
  const info = findConfigFile3(projectDir);
65469
- if (!info.path || !existsSync36(info.path)) {
66282
+ if (!info.path || !existsSync37(info.path)) {
65470
66283
  return jsonOk({ ok: true, path: null, exists: false, source: "", config: {} });
65471
66284
  }
65472
66285
  const source = readFileSync35(info.path, "utf-8");
@@ -65848,7 +66661,7 @@ function createVeskTools(deps) {
65848
66661
  const contained = resolveWithin3(dir, `${checkpointId}.json`);
65849
66662
  if (!contained)
65850
66663
  return jsonError("path escapes project root");
65851
- if (!existsSync36(file))
66664
+ if (!existsSync37(file))
65852
66665
  return jsonError(`checkpoint not found: ${checkpointId}`, { checkpointId });
65853
66666
  const raw2 = readFileSync35(file, "utf-8");
65854
66667
  let data2;
@@ -65933,7 +66746,7 @@ function renderDefaultNotFoundPage2(opts = {}) {
65933
66746
  }
65934
66747
 
65935
66748
  // ../adapter/dist/ssr-function.js
65936
- import { readFileSync as readFileSync36, existsSync as existsSync37 } from "node:fs";
66749
+ import { readFileSync as readFileSync36, existsSync as existsSync38 } from "node:fs";
65937
66750
  import { resolve as resolve33, relative as relative7, join as join26 } from "node:path";
65938
66751
  init_default_pages();
65939
66752
  init_module_imports();
@@ -65942,25 +66755,25 @@ function resolveBoundaryFileForUrl2(pathname, appDir, file) {
65942
66755
  for (let depth = segments.length; depth >= 0; depth--) {
65943
66756
  const dir = join26(appDir, ...segments.slice(0, depth));
65944
66757
  const p = join26(dir, file);
65945
- if (existsSync37(p))
66758
+ if (existsSync38(p))
65946
66759
  return p;
65947
66760
  }
65948
66761
  return null;
65949
66762
  }
65950
66763
 
65951
66764
  // ../adapter/dist/css.js
65952
- import { readFileSync as readFileSync37, existsSync as existsSync38 } from "node:fs";
66765
+ import { readFileSync as readFileSync37, existsSync as existsSync39 } from "node:fs";
65953
66766
  import { resolve as resolve34 } from "node:path";
65954
66767
  var GLOBAL_CSS_URL2 = "/_vesk/static/global.css";
65955
66768
  function resolveUserCssPath2(appDir) {
65956
66769
  const appCssSrc = resolve34(appDir, "global.css");
65957
- if (existsSync38(appCssSrc))
66770
+ if (existsSync39(appCssSrc))
65958
66771
  return appCssSrc;
65959
66772
  const cssSrc = resolve34(appDir, "..", "src", "global.css");
65960
- if (existsSync38(cssSrc))
66773
+ if (existsSync39(cssSrc))
65961
66774
  return cssSrc;
65962
66775
  const altCssSrc = resolve34(appDir, "..", "src", "app.css");
65963
- if (existsSync38(altCssSrc))
66776
+ if (existsSync39(altCssSrc))
65964
66777
  return altCssSrc;
65965
66778
  return null;
65966
66779
  }
@@ -65976,7 +66789,7 @@ function resolveCssUrls2(opts) {
65976
66789
  // ../adapter/dist/hmr.js
65977
66790
  init_client_codegen();
65978
66791
  import { WebSocketServer } from "ws";
65979
- import { readFileSync as readFileSync38, existsSync as existsSync39, writeFileSync as writeFileSync19 } from "node:fs";
66792
+ import { readFileSync as readFileSync38, existsSync as existsSync40, writeFileSync as writeFileSync19 } from "node:fs";
65980
66793
  import { resolve as resolve35, dirname as dirname25 } from "node:path";
65981
66794
  import { fileURLToPath as fileURLToPath7 } from "node:url";
65982
66795
  init_default_pages();
@@ -66219,7 +67032,7 @@ function buildErrorPayload(error, filename, opts = {}) {
66219
67032
  }
66220
67033
  for (const absPath of candidates) {
66221
67034
  try {
66222
- if (existsSync39(absPath)) {
67035
+ if (existsSync40(absPath)) {
66223
67036
  src2 = readFileSync38(absPath, "utf-8");
66224
67037
  resolvedAbsPath = absPath;
66225
67038
  break;
@@ -66268,7 +67081,7 @@ function buildErrorPayload(error, filename, opts = {}) {
66268
67081
  }
66269
67082
 
66270
67083
  // ../adapter/dist/ssr-error.js
66271
- import { existsSync as existsSync40, readFileSync as readFileSync39 } from "node:fs";
67084
+ import { existsSync as existsSync41, readFileSync as readFileSync39 } from "node:fs";
66272
67085
  import { relative as relative8, resolve as resolve36 } from "node:path";
66273
67086
 
66274
67087
  // ../adapter/dist/error-codeframe.js
@@ -66453,7 +67266,7 @@ function firstSourceFileFrame(stack, projectRoot) {
66453
67266
  if (!isInsideRoot(p, projectRoot))
66454
67267
  continue;
66455
67268
  try {
66456
- if (!existsSync40(p))
67269
+ if (!existsSync41(p))
66457
67270
  continue;
66458
67271
  } catch {
66459
67272
  continue;
@@ -66497,7 +67310,7 @@ function displayPath(absPath, ctx2) {
66497
67310
  }
66498
67311
  function readIfFile(absPath) {
66499
67312
  try {
66500
- if (!existsSync40(absPath))
67313
+ if (!existsSync41(absPath))
66501
67314
  return null;
66502
67315
  return readFileSync39(absPath, "utf-8");
66503
67316
  } catch {
@@ -66647,7 +67460,7 @@ function renderDevErrorPage(payload, opts) {
66647
67460
 
66648
67461
  // src/build-packages.ts
66649
67462
  import { spawnSync as spawnSync2 } from "node:child_process";
66650
- import { cpSync as cpSync2, existsSync as existsSync41, mkdirSync as mkdirSync18, readFileSync as readFileSync40, readdirSync as readdirSync12, statSync as statSync21, writeFileSync as writeFileSync20 } from "node:fs";
67463
+ import { cpSync as cpSync2, existsSync as existsSync42, mkdirSync as mkdirSync18, readFileSync as readFileSync40, readdirSync as readdirSync12, statSync as statSync21, writeFileSync as writeFileSync20 } from "node:fs";
66651
67464
  import { createRequire as createRequire7 } from "node:module";
66652
67465
  import { dirname as dirname26, join as join27, resolve as resolve37 } from "node:path";
66653
67466
  import { fileURLToPath as fileURLToPath8 } from "node:url";
@@ -66696,9 +67509,9 @@ function newestSourceMtime(srcDir) {
66696
67509
  }
66697
67510
  function distStale(pkgDir, entry) {
66698
67511
  const distIndex = join27(pkgDir, "dist", `${entry}.js`);
66699
- if (!existsSync41(distIndex)) return true;
67512
+ if (!existsSync42(distIndex)) return true;
66700
67513
  const distPkg = join27(pkgDir, "dist", "package.json");
66701
- const distStamp = Math.max(statSync21(distIndex).mtimeMs, existsSync41(distPkg) ? statSync21(distPkg).mtimeMs : 0);
67514
+ const distStamp = Math.max(statSync21(distIndex).mtimeMs, existsSync42(distPkg) ? statSync21(distPkg).mtimeMs : 0);
66702
67515
  return newestSourceMtime(join27(pkgDir, "src")) > distStamp;
66703
67516
  }
66704
67517
  function distPackageJson(pkgName, entry, serverEntry, version2) {
@@ -66723,7 +67536,7 @@ function distPackageJson(pkgName, entry, serverEntry, version2) {
66723
67536
  function buildPackages(force = false) {
66724
67537
  for (const [pkg, cfg] of Object.entries(PACKAGES)) {
66725
67538
  const pkgDir = resolve37(root2, "packages", pkg);
66726
- if (!existsSync41(join27(pkgDir, "src"))) continue;
67539
+ if (!existsSync42(join27(pkgDir, "src"))) continue;
66727
67540
  if (!force && !distStale(pkgDir, cfg.entry)) continue;
66728
67541
  console.log(`[build] ${cfg.name} -> tsc`);
66729
67542
  const tscBin = require2.resolve("typescript/bin/tsc");
@@ -66772,7 +67585,7 @@ if (process.argv[1] && resolve37(process.argv[1]) === fileURLToPath8(import.meta
66772
67585
  }
66773
67586
 
66774
67587
  // src/action-handler.ts
66775
- import { existsSync as existsSync42, readFileSync as readFileSync41, readdirSync as readdirSync13 } from "node:fs";
67588
+ import { existsSync as existsSync43, readFileSync as readFileSync41, readdirSync as readdirSync13 } from "node:fs";
66776
67589
  import { resolve as resolve38 } from "node:path";
66777
67590
 
66778
67591
  // ../compiler/dist/server-cookies.js
@@ -66865,7 +67678,7 @@ function pageSourcesFor(appDirPath, routeTree) {
66865
67678
  return out;
66866
67679
  }
66867
67680
  function walkVskFiles(dir, out, seen) {
66868
- if (!existsSync42(dir)) return;
67681
+ if (!existsSync43(dir)) return;
66869
67682
  let entries;
66870
67683
  try {
66871
67684
  entries = readdirSync13(dir, { withFileTypes: true });
@@ -66900,7 +67713,7 @@ function candidateSources(appDirPath, routeTree) {
66900
67713
  return out;
66901
67714
  }
66902
67715
  function registerSource(sourcePath2) {
66903
- if (!existsSync42(sourcePath2)) return;
67716
+ if (!existsSync43(sourcePath2)) return;
66904
67717
  try {
66905
67718
  compileFile(readFileSync41(sourcePath2, "utf-8"), { sourcePath: sourcePath2 });
66906
67719
  } catch {
@@ -66940,14 +67753,14 @@ async function renderPageHtml(pagePathname, params, ctx2) {
66940
67753
  const node = chain[i];
66941
67754
  const pageFilePath = resolve38(ctx2.appDirPath, node.sourceDir, "page.vsk");
66942
67755
  const layoutFilePath = resolve38(ctx2.appDirPath, node.sourceDir, "layout.vsk");
66943
- if (i === chain.length - 1 && node.page && existsSync42(pageFilePath)) {
67756
+ if (i === chain.length - 1 && node.page && existsSync43(pageFilePath)) {
66944
67757
  const src3 = readFileSync41(pageFilePath, "utf-8");
66945
67758
  const compName2 = resolveComponentName(src3) || node.page;
66946
67759
  const result = await renderPage(src3, compName2, { params }, /* @__PURE__ */ new Map(), { hydrate: true, sourcePath: pageFilePath });
66947
67760
  body = result.body;
66948
67761
  head = result.head || "";
66949
67762
  }
66950
- if (node.layout && existsSync42(layoutFilePath)) {
67763
+ if (node.layout && existsSync43(layoutFilePath)) {
66951
67764
  const src3 = readFileSync41(layoutFilePath, "utf-8");
66952
67765
  const compName2 = resolveComponentName(src3) || node.layout;
66953
67766
  const result = await renderPage(src3, compName2, { children: body }, /* @__PURE__ */ new Map(), { hydrate: true, sourcePath: layoutFilePath });
@@ -66955,7 +67768,7 @@ async function renderPageHtml(pagePathname, params, ctx2) {
66955
67768
  head = (result.head || "") + head;
66956
67769
  }
66957
67770
  }
66958
- const hasLayout = chain.some((n) => n.layout && existsSync42(resolve38(ctx2.appDirPath, n.sourceDir, "layout.vsk")));
67771
+ const hasLayout = chain.some((n) => n.layout && existsSync43(resolve38(ctx2.appDirPath, n.sourceDir, "layout.vsk")));
66959
67772
  if (hasLayout) {
66960
67773
  const secMeta = securityMeta(ctx2.security);
66961
67774
  const headBlock = await applyHeadInjects(
@@ -67210,7 +68023,7 @@ function devErrorContextForMatch(match, appDir, projectDir, routeTree) {
67210
68023
  if (!node || typeof node.sourceDir !== "string") continue;
67211
68024
  const p = resolve39(appDir, node.sourceDir, kind);
67212
68025
  try {
67213
- if (existsSync43(p) && !routeFiles.includes(p)) routeFiles.push(p);
68026
+ if (existsSync44(p) && !routeFiles.includes(p)) routeFiles.push(p);
67214
68027
  } catch {
67215
68028
  }
67216
68029
  }
@@ -67242,9 +68055,9 @@ function resolveRuntimeDir(projectDir) {
67242
68055
  resolve39(import.meta.dirname ?? ".", "..", "..", "runtime", "dist")
67243
68056
  ];
67244
68057
  for (const dir of candidates) {
67245
- if (existsSync43(join28(dir, "ripple-runtime.js"))) return dir;
68058
+ if (existsSync44(join28(dir, "ripple-runtime.js"))) return dir;
67246
68059
  const distDir = join28(dir, "dist");
67247
- if (existsSync43(join28(distDir, "ripple-runtime.js"))) return distDir;
68060
+ if (existsSync44(join28(distDir, "ripple-runtime.js"))) return distDir;
67248
68061
  }
67249
68062
  return null;
67250
68063
  }
@@ -67482,7 +68295,7 @@ function collectRoutePaths(nodes, out = []) {
67482
68295
  return out;
67483
68296
  }
67484
68297
  function countFilesNamed(dir, name) {
67485
- if (!existsSync43(dir)) return 0;
68298
+ if (!existsSync44(dir)) return 0;
67486
68299
  let n = 0;
67487
68300
  for (const entry of readdirSync14(dir, { withFileTypes: true })) {
67488
68301
  const p = join28(dir, entry.name);
@@ -67633,13 +68446,13 @@ async function startDevServer(port, projectDir, config, host) {
67633
68446
  const altCssPath = join28(srcDir, "app.css");
67634
68447
  let rawCss = "";
67635
68448
  let devCssSource = "";
67636
- if (existsSync43(appCssPath)) {
68449
+ if (existsSync44(appCssPath)) {
67637
68450
  devCssSource = appCssPath;
67638
68451
  rawCss = readFileSync42(appCssPath, "utf-8");
67639
- } else if (existsSync43(cssPath)) {
68452
+ } else if (existsSync44(cssPath)) {
67640
68453
  devCssSource = cssPath;
67641
68454
  rawCss = readFileSync42(cssPath, "utf-8");
67642
- } else if (existsSync43(altCssPath)) {
68455
+ } else if (existsSync44(altCssPath)) {
67643
68456
  devCssSource = altCssPath;
67644
68457
  rawCss = readFileSync42(altCssPath, "utf-8");
67645
68458
  }
@@ -68127,7 +68940,7 @@ async function startDevServer(port, projectDir, config, host) {
68127
68940
  const kind = classifyHmrWatchPath(filename);
68128
68941
  if (kind === "ignored") return;
68129
68942
  const fullPath = filename.startsWith("/") ? filename : join28(watchDir, filename);
68130
- const fileExists = existsSync43(fullPath);
68943
+ const fileExists = existsSync44(fullPath);
68131
68944
  const bcast = (msg) => {
68132
68945
  const f = globalThis.__vesk_broadcastHmr;
68133
68946
  if (typeof f === "function") f(msg);
@@ -68344,7 +69157,7 @@ Object.defineProperty(__components, ${JSON.stringify(cname)}, { get: () => __com
68344
69157
  };
68345
69158
  const hmrJsPath = join28(runtimeDir, "hmr-client.js");
68346
69159
  const hmrTsPath = join28(runtimeDir, "hmr-client.ts");
68347
- const hmrClientPath = existsSync43(hmrJsPath) ? hmrJsPath : existsSync43(hmrTsPath) ? hmrTsPath : null;
69160
+ const hmrClientPath = existsSync44(hmrJsPath) ? hmrJsPath : existsSync44(hmrTsPath) ? hmrTsPath : null;
68348
69161
  function extractCompName2(src2) {
68349
69162
  return resolveComponentName(src2);
68350
69163
  }
@@ -68505,7 +69318,7 @@ Object.defineProperty(__components, ${JSON.stringify(cname)}, { get: () => __com
68505
69318
  }
68506
69319
  if (url.pathname !== "/") {
68507
69320
  const staticPath = url.pathname.length > 1 ? resolveWithin2(publicDir, url.pathname.slice(1)) : null;
68508
- if (staticPath && existsSync43(staticPath) && statSync22(staticPath).isFile()) {
69321
+ if (staticPath && existsSync44(staticPath) && statSync22(staticPath).isFile()) {
68509
69322
  const ext = extname7(staticPath);
68510
69323
  res.writeHead(200, { "Content-Type": MIME2[ext] || "application/octet-stream" });
68511
69324
  res.end(readFileSync42(staticPath));
@@ -68531,9 +69344,31 @@ Object.defineProperty(__components, ${JSON.stringify(cname)}, { get: () => __com
68531
69344
  if (await handleActionRequest(req, res, { url, appDirPath, routeTree, security, maxBodyBytes, plugins: getActiveDevPlugins() })) {
68532
69345
  return;
68533
69346
  }
69347
+ if (url.pathname === "/_vesk/middleware") {
69348
+ const targetPath = url.searchParams.get("path") || "/";
69349
+ const targetUrl = new URL(targetPath, "http://localhost");
69350
+ const targetChain = collectMiddlewareChain(routeTree, targetUrl.pathname, appDirPath);
69351
+ const rawHeaders = {};
69352
+ for (const [k, v] of Object.entries(req.headers)) {
69353
+ rawHeaders[k] = Array.isArray(v) ? v.join(", ") : v || "";
69354
+ }
69355
+ const mwReq = new Request(targetUrl.href, { headers: rawHeaders, method: "GET" });
69356
+ const mwResult = await executeMiddlewareChain(targetChain, mwReq, {}, {
69357
+ plugins: getActiveDevPlugins(),
69358
+ onLast: async () => null
69359
+ });
69360
+ res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
69361
+ if (mwResult.response) {
69362
+ const location = mwResult.response.headers.get("location") || mwResult.response.headers.get("Location");
69363
+ res.end(JSON.stringify(location ? { redirect: location } : { allow: true }));
69364
+ return;
69365
+ }
69366
+ res.end(JSON.stringify(mwResult.rewriteUrl ? { rewrite: mwResult.rewriteUrl } : { allow: true }));
69367
+ return;
69368
+ }
68534
69369
  const mwChain = collectMiddlewareChain(routeTree, url.pathname, appDirPath);
68535
69370
  const apiDirPath = join28(appDirPath, "api");
68536
- if (url.pathname.startsWith("/api") && existsSync43(apiDirPath)) {
69371
+ if (url.pathname.startsWith("/api") && existsSync44(apiDirPath)) {
68537
69372
  const apiRoutes = await scanApiRoutes(apiDirPath);
68538
69373
  const apiMatch = matchApiUrl(apiRoutes, req.url || url.pathname);
68539
69374
  if (apiMatch) {
@@ -68660,7 +69495,7 @@ Object.defineProperty(__components, ${JSON.stringify(cname)}, { get: () => __com
68660
69495
  const node = chain[i];
68661
69496
  const pageFilePath = resolve39(appDirPath, node.sourceDir, "page.vsk");
68662
69497
  const layoutFilePath = resolve39(appDirPath, node.sourceDir, "layout.vsk");
68663
- if (i === chain.length - 1 && node.page && existsSync43(pageFilePath)) {
69498
+ if (i === chain.length - 1 && node.page && existsSync44(pageFilePath)) {
68664
69499
  const src2 = readFileSync42(pageFilePath, "utf-8");
68665
69500
  const compName = extractCompName2(src2) || node.page;
68666
69501
  const result = await renderPage(src2, compName, { params: matched.params }, /* @__PURE__ */ new Map(), { hydrate: true, sourcePath: pageFilePath, cached: cachedSsrCompile(ssrCompileCache, src2, pageFilePath) });
@@ -68668,7 +69503,7 @@ Object.defineProperty(__components, ${JSON.stringify(cname)}, { get: () => __com
68668
69503
  head = result.head || "";
68669
69504
  props = result.props;
68670
69505
  }
68671
- if (node.layout && existsSync43(layoutFilePath)) {
69506
+ if (node.layout && existsSync44(layoutFilePath)) {
68672
69507
  const src2 = readFileSync42(layoutFilePath, "utf-8");
68673
69508
  const compName = extractCompName2(src2) || node.layout;
68674
69509
  const result = await renderPage(src2, compName, { children: body }, /* @__PURE__ */ new Map(), { hydrate: true, sourcePath: layoutFilePath, cached: cachedSsrCompile(ssrCompileCache, src2, layoutFilePath) });
@@ -68679,7 +69514,7 @@ Object.defineProperty(__components, ${JSON.stringify(cname)}, { get: () => __com
68679
69514
  if (forData) {
68680
69515
  return { html: "", props: props || { params: matched.params }, head };
68681
69516
  }
68682
- const hasLayout = chain.some((n) => n.layout && existsSync43(resolve39(appDirPath, n.sourceDir, "layout.vsk")));
69517
+ const hasLayout = chain.some((n) => n.layout && existsSync44(resolve39(appDirPath, n.sourceDir, "layout.vsk")));
68683
69518
  let html;
68684
69519
  if (hasLayout) {
68685
69520
  const ssrData = currentSsrData();
@@ -68748,7 +69583,7 @@ ${prettifyHtml(body)}
68748
69583
  };
68749
69584
  async function* raw2() {
68750
69585
  const chain = cleanChain;
68751
- const hasLayout = chain.some((n) => n.layout && existsSync43(resolve39(appDirPath, n.sourceDir, "layout.vsk")));
69586
+ const hasLayout = chain.some((n) => n.layout && existsSync44(resolve39(appDirPath, n.sourceDir, "layout.vsk")));
68752
69587
  if (!hasLayout) {
68753
69588
  const leaf2 = chain.find((n) => n.page);
68754
69589
  if (leaf2) {
@@ -68767,7 +69602,7 @@ ${prettifyHtml(body)}
68767
69602
  const node = chain[i];
68768
69603
  const pageFilePath = resolve39(appDirPath, node.sourceDir, "page.vsk");
68769
69604
  const layoutFilePath = resolve39(appDirPath, node.sourceDir, "layout.vsk");
68770
- if (i === chain.length - 1 && node.page && existsSync43(pageFilePath)) {
69605
+ if (i === chain.length - 1 && node.page && existsSync44(pageFilePath)) {
68771
69606
  const src2 = readFileSync42(pageFilePath, "utf-8");
68772
69607
  const compName = extractCompName2(src2) || node.page;
68773
69608
  const result = await renderPage(src2, compName, { params: matched.params }, /* @__PURE__ */ new Map(), { hydrate: true, sourcePath: pageFilePath, cached: cachedSsrCompile(ssrCompileCache, src2, pageFilePath) });
@@ -68775,7 +69610,7 @@ ${prettifyHtml(body)}
68775
69610
  head = result.head || "";
68776
69611
  props = result.props;
68777
69612
  }
68778
- if (node.layout && existsSync43(layoutFilePath)) {
69613
+ if (node.layout && existsSync44(layoutFilePath)) {
68779
69614
  const src2 = readFileSync42(layoutFilePath, "utf-8");
68780
69615
  const compName = extractCompName2(src2) || node.layout;
68781
69616
  const result = await renderPage(src2, compName, { children: body }, /* @__PURE__ */ new Map(), { hydrate: true, sourcePath: layoutFilePath, cached: cachedSsrCompile(ssrCompileCache, src2, layoutFilePath) });
@@ -68919,7 +69754,7 @@ ${prettifyHtml(body)}
68919
69754
  const node = match.nodes[i];
68920
69755
  if (node.notFound) {
68921
69756
  const nfPath = resolve39(appDirPath, node.sourceDir, "not-found.vsk");
68922
- if (existsSync43(nfPath)) {
69757
+ if (existsSync44(nfPath)) {
68923
69758
  try {
68924
69759
  const nfSrc = readFileSync42(nfPath, "utf-8");
68925
69760
  const nfCompName = extractCompName2(nfSrc) || node.notFound;
@@ -68965,7 +69800,7 @@ ${prettifyHtml(body)}
68965
69800
  const node = match.nodes[i];
68966
69801
  if (node.error) {
68967
69802
  const errPath = resolve39(appDirPath, node.sourceDir, "error.vsk");
68968
- if (existsSync43(errPath)) {
69803
+ if (existsSync44(errPath)) {
68969
69804
  try {
68970
69805
  const errSrc = readFileSync42(errPath, "utf-8");
68971
69806
  const errCompName = extractCompName2(errSrc) || node.error;
@@ -69371,7 +70206,7 @@ function loadEnvFiles(projectDir) {
69371
70206
  join32(projectDir, ".env.local")
69372
70207
  ];
69373
70208
  for (const filePath of files) {
69374
- if (!existsSync46(filePath)) continue;
70209
+ if (!existsSync47(filePath)) continue;
69375
70210
  const content = readFileSync46(filePath, "utf-8");
69376
70211
  for (const line of content.split("\n")) {
69377
70212
  const trimmed = line.trim();
@@ -69411,7 +70246,7 @@ function resolveProjectDirs(projectDir, config) {
69411
70246
  };
69412
70247
  }
69413
70248
  async function typecheckBeforeBuild(projectDir) {
69414
- if (!existsSync46(join32(projectDir, "tsconfig.json"))) return;
70249
+ if (!existsSync47(join32(projectDir, "tsconfig.json"))) return;
69415
70250
  let tscPath;
69416
70251
  try {
69417
70252
  tscPath = requireFromCli.resolve("typescript/bin/tsc", { paths: [projectDir] });
@@ -69437,7 +70272,7 @@ if (cmd === "build") {
69437
70272
  const projectDir = process.cwd();
69438
70273
  const rawConfig = await loadConfig(projectDir) || {};
69439
70274
  const { appDir: appDirPath, publicDir, outDir } = resolveProjectDirs(projectDir, rawConfig);
69440
- if (!existsSync46(appDirPath)) {
70275
+ if (!existsSync47(appDirPath)) {
69441
70276
  console.error(`vesk build: no app directory found in ${projectDir} (config appDir: ${rawConfig.appDir ?? "./app"})`);
69442
70277
  process.exit(1);
69443
70278
  }
@@ -69512,7 +70347,7 @@ ${frame}`;
69512
70347
  if (cmd === "seo") {
69513
70348
  const projectDir = process.cwd();
69514
70349
  const { appDir: appDirPath } = resolveProjectDirs(projectDir, await loadConfig(projectDir) || {});
69515
- if (!existsSync46(appDirPath)) {
70350
+ if (!existsSync47(appDirPath)) {
69516
70351
  console.error(`vesk seo: no app directory found in ${projectDir}`);
69517
70352
  process.exit(1);
69518
70353
  }
@@ -69527,7 +70362,7 @@ if (cmd === "seo") {
69527
70362
  if (cmd === "typecheck") {
69528
70363
  const projectDir = process.cwd();
69529
70364
  const { appDir: appDirPath } = resolveProjectDirs(projectDir, await loadConfig(projectDir) || {});
69530
- if (!existsSync46(appDirPath)) {
70365
+ if (!existsSync47(appDirPath)) {
69531
70366
  console.error(`vesk typecheck: no app directory found in ${projectDir}`);
69532
70367
  process.exit(1);
69533
70368
  }
@@ -69554,7 +70389,7 @@ if (cmd === "start") {
69554
70389
  const { outDir } = resolveProjectDirs(projectDir, await loadConfig(projectDir) || {});
69555
70390
  const port = parsePortArg(args);
69556
70391
  const host = parseHostArg(args);
69557
- if (!existsSync46(outDir)) {
70392
+ if (!existsSync47(outDir)) {
69558
70393
  console.error(`vesk start: no build found at ${outDir} \u2014 run "vesk build" first.`);
69559
70394
  process.exit(1);
69560
70395
  }
@@ -69566,7 +70401,7 @@ if (cmd === "init") {
69566
70401
  const projectDir = process.cwd();
69567
70402
  const { appDir: appDirPath } = resolveProjectDirs(projectDir, await loadConfig(projectDir) || {});
69568
70403
  const target = join32(appDirPath, "global.css");
69569
- if (existsSync46(target)) {
70404
+ if (existsSync47(target)) {
69570
70405
  console.error(`vesk init: ${target} already exists \u2014 skipping`);
69571
70406
  process.exit(0);
69572
70407
  }
@@ -69628,7 +70463,7 @@ if (cmd === "dev") {
69628
70463
  const { appDir: appDirPath, publicDir } = resolveProjectDirs(projectDir, await loadConfig(projectDir) || {});
69629
70464
  const port = parsePortArg(args);
69630
70465
  const host = parseHostArg(args);
69631
- if (!existsSync46(appDirPath)) {
70466
+ if (!existsSync47(appDirPath)) {
69632
70467
  console.error(`vesk: no app/ directory found in ${projectDir}`);
69633
70468
  console.error('Run "npx create-vesk@latest <project-name>" first');
69634
70469
  process.exit(1);