what-core 0.12.3 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/render.js CHANGED
@@ -5,7 +5,7 @@
5
5
  import { effect, untrack, createRoot, _createItemScope, signal, memo, __DEV__ } from './reactive.js';
6
6
  import { __resetIdCounter } from './a11y.js';
7
7
  import { createDOM, disposeTree, getCurrentComponent, getComponentStack, addHydrationDisposer, addHydratedComponent, _setSelectValue, _isUnsafeAttr, _isEventProp, _installLazyChildren, _handleNavigationSignal } from './dom.js';
8
- import { _injectIslandRuntime } from './components.js';
8
+ import { _injectIslandRuntime, reportError } from './components.js';
9
9
  export { effect, untrack };
10
10
  // Re-export memo for compiled output (branch memoization: the compiler emits
11
11
  // _$memo(() => cond) so conditional branches only re-create DOM when the
@@ -1359,6 +1359,22 @@ export function spread(el, props) {
1359
1359
  for (const key in props) {
1360
1360
  const value = props[key];
1361
1361
 
1362
+ // Ref — the element, not a reactive getter.
1363
+ //
1364
+ // This is the one prop whose FUNCTION form is a callback taking the element
1365
+ // rather than an accessor returning a value, which is exactly why the other
1366
+ // two call sites special-case it before the reactive-prop test (setProp
1367
+ // below, and applyProps in dom.js). Spread did not, so a function ref fell
1368
+ // into the reactive branch and was invoked as `value()` with NO ARGUMENT.
1369
+ // Every `{...register('email')}`-shaped API broke in silence on the
1370
+ // compiled path: the ref saw `undefined`, guarded, and returned, so no
1371
+ // element was ever registered and nothing threw to say so.
1372
+ if (key === 'ref') {
1373
+ if (typeof value === 'function') value(el);
1374
+ else if (value && typeof value === 'object') value.current = el;
1375
+ continue;
1376
+ }
1377
+
1362
1378
  if (_isEventProp(key)) {
1363
1379
  // Event handler — direct assignment. Use $$name for delegated events.
1364
1380
  if (typeof value !== 'function') continue;
@@ -1718,6 +1734,36 @@ function trimUnclaimed(parent) {
1718
1734
  }
1719
1735
  }
1720
1736
 
1737
+ /**
1738
+ * Comment markers that belong to the machinery, not to the page.
1739
+ *
1740
+ * '$' / '/$' and '[]' / '/[]' come from the server's hydratable output. The
1741
+ * rest are planted by the hydration walk itself as it goes: 'fn' / '/fn' bound
1742
+ * a reactive region (the function branch of hydrateNode), 'eb:*' and 'sb:*'
1743
+ * bound an <ErrorBoundary> or a <Suspense> (hydrateBoundary), and 'portal' /
1744
+ * 'portal:empty' are a <Portal>'s placeholder.
1745
+ *
1746
+ * In every case the cursor is advanced past the marker at the moment it goes
1747
+ * in, so a later sibling REACHING one means the cursor has desynced. Skipping
1748
+ * is what keeps that desync from turning destructive. No vnode form in this
1749
+ * framework produces a comment node, so the element and text branches treat a
1750
+ * claimed comment as a mismatch and replaceChild() it away: a sibling that
1751
+ * claimed a region's end marker would delete the marker, leave the region
1752
+ * unterminated, and send its next update walking off the end of the parent.
1753
+ * Losing one node's reuse is a scratch; losing a marker is fatal to the region.
1754
+ */
1755
+ const _HYDRATION_MARKERS = new Set([
1756
+ '$', '/$', '[]', '/[]',
1757
+ 'fn', '/fn',
1758
+ 'eb:start', 'eb:end',
1759
+ 'sb:start', 'sb:end',
1760
+ 'portal', 'portal:empty',
1761
+ ]);
1762
+
1763
+ function _isHydrationMarker(node) {
1764
+ return node.nodeType === 8 && _HYDRATION_MARKERS.has(node.textContent);
1765
+ }
1766
+
1721
1767
  /**
1722
1768
  * Claim the next DOM node from the hydration cursor.
1723
1769
  * Returns the existing DOM node or null if none available.
@@ -1726,17 +1772,9 @@ function claimNode(parent) {
1726
1772
  const children = parent.childNodes;
1727
1773
  while (_hydrationCursor.index < children.length) {
1728
1774
  const node = children[_hydrationCursor.index];
1729
- // Skip hydration comment markers. 'fn' / '/fn' are the reactive-region
1730
- // markers hydration itself inserts as it walks (see the function branch of
1731
- // hydrateNode); the cursor is adjusted when they go in, and skipping them
1732
- // here keeps a later sibling from ever claiming one as its node.
1733
- if (node.nodeType === 8) { // Comment node
1734
- const text = node.textContent;
1735
- if (text === '$' || text === '/$' || text === '[]' || text === '/[]'
1736
- || text === 'fn' || text === '/fn') {
1737
- _hydrationCursor.index++;
1738
- continue;
1739
- }
1775
+ if (_isHydrationMarker(node)) {
1776
+ _hydrationCursor.index++;
1777
+ continue;
1740
1778
  }
1741
1779
  _hydrationCursor.index++;
1742
1780
  return node;
@@ -1756,13 +1794,7 @@ function peekNode(parent) {
1756
1794
  const children = parent.childNodes;
1757
1795
  for (let i = _hydrationCursor.index; i < children.length; i++) {
1758
1796
  const node = children[i];
1759
- if (node.nodeType === 8) {
1760
- const text = node.textContent;
1761
- if (text === '$' || text === '/$' || text === '[]' || text === '/[]'
1762
- || text === 'fn' || text === '/fn') {
1763
- continue;
1764
- }
1765
- }
1797
+ if (_isHydrationMarker(node)) continue;
1766
1798
  return node;
1767
1799
  }
1768
1800
  return null;
@@ -2071,9 +2103,29 @@ function hydrateNode(vnode, parent) {
2071
2103
  if (endChildrenPass) endChildrenPass();
2072
2104
  } catch (error) {
2073
2105
  componentStack.pop();
2074
- // Same classification as createComponent: a navigation signal carries
2075
- // its own handler and is not a render failure.
2076
- if (!_handleNavigationSignal(error)) {
2106
+ // Same classification as createComponent, and it has to be the same or
2107
+ // the two paths disagree about what a throw MEANS:
2108
+ //
2109
+ // - a navigation signal carries its own handler and is not a failure.
2110
+ // - a thrown thenable is a SUSPENSION. It is how lazy() says "my
2111
+ // chunk has not landed yet", and during hydration that is not an
2112
+ // edge case but the normal one: on a real first load the dynamic
2113
+ // import is still in flight when hydrate() runs. Logging it and
2114
+ // returning null left `loading` unflipped, so the <Suspense> region
2115
+ // came out EMPTY, the server's fallback markup was left unclaimed
2116
+ // and then trimmed, and the chunk resolving re-rendered nothing.
2117
+ // The boundary sat permanently blank, which is the one outcome
2118
+ // Suspense exists to prevent.
2119
+ // - anything else is a real error and belongs to the nearest
2120
+ // <ErrorBoundary>, exactly as in a client-only render.
2121
+ //
2122
+ // Unlike createComponent this never RE-THROWS when nothing handles it.
2123
+ // An exception escaping here escapes hydrate() itself and the rest of
2124
+ // the page never hydrates at all; whatever this component was, its
2125
+ // siblings are still recoverable.
2126
+ if (!_handleNavigationSignal(error)
2127
+ && !(error && typeof error.then === 'function' && suspendDuringHydration(error, ctx))
2128
+ && !reportError(error, ctx)) {
2077
2129
  console.error('[what] Error in component during hydration:', Component.name || 'Anonymous', error);
2078
2130
  }
2079
2131
  return null;
@@ -2111,6 +2163,10 @@ function hydrateNode(vnode, parent) {
2111
2163
  // A region root falls back to the parent element instead. That disposes
2112
2164
  // later than ideal (when the parent goes, not when the component does),
2113
2165
  // and disposing late is strictly better than disposing while mounted.
2166
+ //
2167
+ // A boundary root needs no case here: hydrateBoundary returns its start
2168
+ // MARKER rather than its contents, and a marker is stable by
2169
+ // construction.
2114
2170
  const rootIsRegion = typeof result === 'function'
2115
2171
  || (Array.isArray(result) && result.some((child) => typeof child === 'function'));
2116
2172
  const first = Array.isArray(node) ? node[0] : node;
@@ -2122,6 +2178,65 @@ function hydrateNode(vnode, parent) {
2122
2178
  }
2123
2179
  }
2124
2180
 
2181
+ // Boundary marker tags — NOT elements, and never rendered as themselves.
2182
+ //
2183
+ // <ErrorBoundary>, <Suspense> and <Portal> each return one of these instead
2184
+ // of a DOM tag, and every other render path routes them to a boundary
2185
+ // handler rather than to createElement (dom.js createDOM, and the same
2186
+ // three tags in the server's renderer). Hydration was the one path with no
2187
+ // branch for them, so a marker tag fell through to the ELEMENT branch below
2188
+ // and went looking for a `<__errorBoundary>` element in the server HTML.
2189
+ // What it found was the first node of the boundary's OWN subtree, which it
2190
+ // warned about and destroyed:
2191
+ //
2192
+ // server: <div id="x"><p>INNER</p></div>
2193
+ // client: <div id="x"><!--eb:start--></div>
2194
+ //
2195
+ // One <ErrorBoundary> anywhere in a server-rendered page blanked everything
2196
+ // under it. The construct whose entire job is to contain a failure was
2197
+ // itself the failure.
2198
+ if (vnode.tag === '__errorBoundary') {
2199
+ const { errorState, fallback, reset, handleError } = vnode.props;
2200
+ return hydrateBoundary(vnode, parent, {
2201
+ startText: 'eb:start',
2202
+ endText: 'eb:end',
2203
+ ctxExtras: { _errorBoundary: handleError },
2204
+ state: errorState,
2205
+ contentFor: (error) => {
2206
+ if (!error) return vnode.children || [];
2207
+ return typeof fallback === 'function' ? fallback({ error, reset }) : fallback;
2208
+ },
2209
+ });
2210
+ }
2211
+
2212
+ if (vnode.tag === '__suspense') {
2213
+ const { boundary, fallback, loading } = vnode.props;
2214
+ return hydrateBoundary(vnode, parent, {
2215
+ startText: 'sb:start',
2216
+ endText: 'sb:end',
2217
+ ctxExtras: { _suspenseBoundary: boundary },
2218
+ state: loading,
2219
+ contentFor: (isLoading) => (isLoading ? fallback : (vnode.children || [])),
2220
+ });
2221
+ }
2222
+
2223
+ // <Portal> renders NOTHING on the server, by the same decision that makes
2224
+ // Portal() return null when there is no document: its content belongs to a
2225
+ // container somewhere else on the page, not to this position. So there is
2226
+ // no server markup here to claim and the portal mounts client-side exactly
2227
+ // as it does in a client-only render.
2228
+ //
2229
+ // The element branch did the opposite. It CLAIMED the next node, which is
2230
+ // the server's next real sibling, warned about a mismatch that never
2231
+ // existed, and replaced that sibling with the portal's placeholder comment.
2232
+ // The claimed node was destroyed and everything after it shifted, so a
2233
+ // portal in the middle of a server-rendered list cost every node behind it:
2234
+ // a modal host declared before the page content rebuilt the entire page.
2235
+ if (vnode.tag === '__portal') {
2236
+ const placeholder = createDOM(vnode, parent);
2237
+ return placeholder ? insertAtCursor(parent, placeholder) : null;
2238
+ }
2239
+
2125
2240
  // Element — claim existing DOM element
2126
2241
  //
2127
2242
  // The comparison is case-INSENSITIVE. `nodeName` is uppercased for HTML
@@ -2198,6 +2313,360 @@ function hydrateNode(vnode, parent) {
2198
2313
  return insertAtCursor(parent, document.createTextNode(String(vnode)));
2199
2314
  }
2200
2315
 
2316
+ /**
2317
+ * Hand a thrown thenable to the nearest <Suspense> above `ctx`.
2318
+ *
2319
+ * The twin of the private `suspend()` in dom.js: the same walk up the same
2320
+ * `_parentCtx` chain to the same `_suspenseBoundary`. It is written out again
2321
+ * rather than shared because dom.js keeps its copy module-private, and the two
2322
+ * halves it depends on (the chain, and the boundary's onSuspend) are fixed
2323
+ * shapes that createSuspenseBoundary and hydrateBoundary both build.
2324
+ *
2325
+ * Returns false when nothing above can take the suspension, which makes the
2326
+ * thenable an ordinary unhandled error again.
2327
+ */
2328
+ function suspendDuringHydration(promise, ctx) {
2329
+ for (let c = ctx; c; c = c._parentCtx) {
2330
+ if (c._suspenseBoundary) {
2331
+ c._suspenseBoundary.onSuspend(promise);
2332
+ return true;
2333
+ }
2334
+ }
2335
+ return false;
2336
+ }
2337
+
2338
+ /**
2339
+ * Evidence that the node the cursor is parked on is NOT the one `vnode` would
2340
+ * have produced on the server.
2341
+ *
2342
+ * A boundary's region has no delimiter in the server's bytes, so "the markup
2343
+ * here belongs to this boundary" can never be PROVEN from the client. It can
2344
+ * sometimes be refuted, and a refutation is all claimServerArm needs: a plain
2345
+ * element or text vnode names exactly the node it wants, so a <p> facing a
2346
+ * <footer> is a boundary reaching past its own region into its next sibling.
2347
+ *
2348
+ * Anything else — a component, a thunk, a nested boundary marker — cannot
2349
+ * answer without being run, and "cannot tell" is deliberately NOT a refutation.
2350
+ * Refusing there would give up the reuse for `fallback={() => <ErrorMessage />}`,
2351
+ * which is the shape most apps actually write.
2352
+ */
2353
+ function contradictsServerNode(vnode, node) {
2354
+ if (typeof vnode === 'string' || typeof vnode === 'number') return node.nodeType !== 3;
2355
+ if (vnode && vnode._vnode && typeof vnode.tag === 'string') {
2356
+ return node.nodeType !== 1 || node.nodeName.toLowerCase() !== vnode.tag.toLowerCase();
2357
+ }
2358
+ return false;
2359
+ }
2360
+
2361
+ /**
2362
+ * Claim the server's markup for a boundary's FALLBACK, when the server rendered
2363
+ * the fallback too.
2364
+ *
2365
+ * A child that throws during SSR is caught by the server's own boundary branch
2366
+ * (packages/server/src/index.js), so the response carries the fallback and NOT
2367
+ * the children. The same child throws again while hydrating, which flips the
2368
+ * boundary's signal — but by then hydrateBoundary has already walked the happy
2369
+ * arm, and the happy arm does not match a byte of what the server sent. The
2370
+ * fallback markup went unclaimed, the boundary's effect built a second copy of
2371
+ * it, and the first copy was trimmed: the server rendered the fallback and the
2372
+ * client threw it away and rebuilt it.
2373
+ *
2374
+ * What makes this recoverable is that a child which throws before producing
2375
+ * anything claims NOTHING, so the cursor is still parked exactly where the
2376
+ * server's markup for this boundary starts and nothing in the region has been
2377
+ * written over. Then the fallback can hydrate against it like ordinary markup.
2378
+ *
2379
+ * The refusals matter as much as the claim, because the region's extent is not
2380
+ * knowable from the client (see contradictsServerNode):
2381
+ *
2382
+ * - the failed arm produced something first, so the cursor has moved and
2383
+ * whatever it moved over has already been claimed or replaced. A child
2384
+ * ahead of the thrower is the ordinary case here: it claims the server's
2385
+ * fallback node, calls it a mismatch, and destroys it before the boundary
2386
+ * ever learns an error happened. Nothing left to reuse.
2387
+ * - the server left nothing at this position at all. The node at the cursor
2388
+ * then belongs to the boundary's next SIBLING, and claiming it would be the
2389
+ * <Portal> failure again: a boundary eating the footer behind it.
2390
+ * - the node that is there openly disagrees with the fallback's root.
2391
+ *
2392
+ * Every refusal falls back to the boundary's effect rebuilding the region,
2393
+ * which is what this whole path did before and is always correct — a lost
2394
+ * reuse, not a lost node.
2395
+ *
2396
+ * `getContent` is a thunk rather than a value so the refusals above cost
2397
+ * nothing: on a refusal the effect is the one that builds the fallback, and
2398
+ * running a user's `fallback={({ error }) => ...}` twice per catch to throw the
2399
+ * first result away is a side effect this has no business causing.
2400
+ *
2401
+ * Returns true when the region now holds the fallback.
2402
+ */
2403
+ function claimServerArm(parent, regionStart, getContent) {
2404
+ // No cursor in this parent means nothing here was being claimed from the
2405
+ // server in the first place.
2406
+ if (regionStart < 0 || !_hydrationCursor || _hydrationCursor.parent !== parent) return false;
2407
+
2408
+ // The failed arm has to have produced NOTHING. Any movement of the cursor is
2409
+ // a node this region has already committed to, claimed or created.
2410
+ if (_hydrationCursor.index !== regionStart) return false;
2411
+
2412
+ // Nothing at this position means there is nothing to reuse. Asked first
2413
+ // because it is the only question answerable without building the fallback.
2414
+ const candidate = peekNode(parent);
2415
+ if (!candidate) return false;
2416
+
2417
+ const content = getContent();
2418
+ const vnodes = Array.isArray(content) ? content : [content];
2419
+ const root = vnodes.find((v) => v != null && typeof v !== 'boolean');
2420
+
2421
+ // A fallback that renders nothing wants an empty region, and an empty region
2422
+ // is what it already has. Claimed, with nothing to claim — and `candidate` is
2423
+ // left for whoever it really belongs to.
2424
+ if (root === undefined) return true;
2425
+
2426
+ if (contradictsServerNode(root, candidate)) return false;
2427
+
2428
+ for (const v of vnodes) hydrateNode(v, parent);
2429
+ return true;
2430
+ }
2431
+
2432
+ /**
2433
+ * Hydrate an <ErrorBoundary> or a <Suspense>.
2434
+ *
2435
+ * The two are the same machine with a different signal: a marked region whose
2436
+ * contents are the children while the signal is falsy and the fallback once it
2437
+ * is not. The client builds both with createErrorBoundary / createSuspenseBoundary
2438
+ * in dom.js, and this is the hydrating twin of those two functions.
2439
+ *
2440
+ * Three things have to be true when this returns, and each was a separate bug:
2441
+ *
2442
+ * - the server's markup is still on screen. The children hydrate against it
2443
+ * in place; nothing is rebuilt.
2444
+ * - the boundary's context is on the component stack while those children
2445
+ * hydrate. reportError and suspend() both find their boundary by walking
2446
+ * `_parentCtx` up from the component that threw, so a boundary missing from
2447
+ * that chain catches nothing: the error escapes to the console and the page
2448
+ * dies exactly as it would with no boundary at all.
2449
+ * - the region is owned by an effect from here on, bounded by real comment
2450
+ * markers. Without the markers there is no insertion point and no stable
2451
+ * node to hang the disposer on, which is the same pair of failures the
2452
+ * reactive-region branch documents above.
2453
+ *
2454
+ * The first effect run is the subtle one. It must NOT rebuild what hydration
2455
+ * just claimed, or hydrating a boundary would be indistinguishable from
2456
+ * client-rendering it. But it cannot skip unconditionally either: a child that
2457
+ * threw or suspended WHILE hydrating flipped the signal before this effect
2458
+ * existed, and in that case the markup between the markers may be the wrong arm
2459
+ * and has to be replaced.
2460
+ *
2461
+ * "May be", not "is", and that is the whole of claimServerArm below. When a
2462
+ * child throws during the SERVER render the server catches it too and puts the
2463
+ * FALLBACK in the HTML, so the two sides agree on the arm and the fallback is
2464
+ * ordinary server markup that hydration should claim like any other. Hydrating
2465
+ * the happy arm first and then rebuilding on the flipped signal threw that
2466
+ * markup away and built a second copy of it, which is exactly the
2467
+ * destroy-and-rebuild these markers exist to stop.
2468
+ */
2469
+ function hydrateBoundary(vnode, parent, { startText, endText, ctxExtras, state, contentFor }) {
2470
+ const children = vnode.children || [];
2471
+ const cursorInParent = !!(_hydrationCursor && _hydrationCursor.parent === parent);
2472
+ const startComment = document.createComment(startText);
2473
+ const endComment = document.createComment(endText);
2474
+
2475
+ // Same shape as the contexts the client boundaries build, for the same
2476
+ // reasons: `_parentCtx` keeps useContext resolving through the boundary, and
2477
+ // the marker references let a teardown find the region from the context.
2478
+ const boundaryCtx = {
2479
+ hooks: [],
2480
+ hookIndex: 0,
2481
+ effects: [],
2482
+ cleanups: [],
2483
+ mounted: false,
2484
+ disposed: false,
2485
+ _parentCtx: captureOwner(),
2486
+ _startComment: startComment,
2487
+ _endComment: endComment,
2488
+ ...ctxExtras,
2489
+ };
2490
+
2491
+ // Open the region at the slot the cursor points at, before anything is
2492
+ // hydrated into it, so everything the children claim lands inside the pair.
2493
+ // (Anchoring the markers afterwards to whatever the children produced is
2494
+ // wrong for a boundary that produced nothing, and interleaves nested regions
2495
+ // instead of nesting them. See the reactive-region branch.)
2496
+ if (cursorInParent) {
2497
+ parent.insertBefore(startComment, parent.childNodes[_hydrationCursor.index] || null);
2498
+ _hydrationCursor.index++;
2499
+ } else {
2500
+ parent.appendChild(startComment);
2501
+ }
2502
+
2503
+ // Where the region's content begins, in cursor terms. The start marker has
2504
+ // already consumed its slot, so this is the index the server's first node for
2505
+ // this boundary sits at. claimServerArm needs it to tell "the failed arm
2506
+ // touched nothing" from "the failed arm got part way in".
2507
+ const regionStart = cursorInParent ? _hydrationCursor.index : -1;
2508
+
2509
+ const stack = getComponentStack();
2510
+ stack.push(boundaryCtx);
2511
+ try {
2512
+ for (const child of children) {
2513
+ hydrateNode(child, parent);
2514
+ }
2515
+ } finally {
2516
+ stack.pop();
2517
+ }
2518
+
2519
+ // Which arm the boundary is on now that its children have run.
2520
+ //
2521
+ // Read UNTRACKED. This is the hydration walk, not the effect below, and a
2522
+ // hydrate() reached from inside somebody else's effect would otherwise hand
2523
+ // that effect a subscription to this boundary's private error/loading signal:
2524
+ // an unrelated region upstream would re-render every time a boundary caught.
2525
+ const armAfterWalk = untrack(state);
2526
+
2527
+ // Whether the markup between the markers is already the arm `armAfterWalk`
2528
+ // names. True by construction when nothing flipped the signal (the walk just
2529
+ // claimed the children the server rendered), and true again when the fallback
2530
+ // below is claimed in place.
2531
+ let regionHoldsArm = !armAfterWalk;
2532
+
2533
+ if (armAfterWalk) {
2534
+ // Same re-push as the rebuild in the effect, for the same reason: a
2535
+ // fallback that renders a component of its own must see the boundary in its
2536
+ // parent chain, and contentFor is what runs that fallback.
2537
+ stack.push(boundaryCtx);
2538
+ try {
2539
+ regionHoldsArm = claimServerArm(parent, regionStart, () => contentFor(armAfterWalk));
2540
+ } finally {
2541
+ stack.pop();
2542
+ }
2543
+ }
2544
+
2545
+ if (cursorInParent) {
2546
+ parent.insertBefore(endComment, parent.childNodes[_hydrationCursor.index] || null);
2547
+ _hydrationCursor.index++;
2548
+ } else {
2549
+ parent.appendChild(endComment);
2550
+ }
2551
+
2552
+ let claimedFromServer = true;
2553
+ // Generation guard, carried over from createSuspenseBoundary in dom.js, where
2554
+ // it exists because a child suspending mid-rebuild flips the state signal from
2555
+ // inside the loop below: if that re-entered the effect, the inner run would
2556
+ // replace the region and the outer run would then append the rest of the arm
2557
+ // it was already committed to, putting both arms on screen at once.
2558
+ //
2559
+ // It is honest to say this is currently UNREACHABLE and kept for parity. An
2560
+ // effect cannot re-enter itself here: reactive.js's notify() only executes
2561
+ // subscribers at notifyDepth 0 and queues them otherwise, so a write made
2562
+ // during an effect's own run is always drained after that run returns. Every
2563
+ // shape tried against it (two- and three-deep lazy waterfalls, and a staged
2564
+ // suspender behind a signal so the effect was auto-promoted to _stable and
2565
+ // therefore running INLINE) came back with a nesting depth of 1.
2566
+ //
2567
+ // Keeping it costs four lines and removes a way for the two boundary
2568
+ // implementations to disagree. The invariant it leans on lives in another
2569
+ // module and is not part of any contract this one can see.
2570
+ let generation = 0;
2571
+ const dispose = effect(() => {
2572
+ const current = state();
2573
+
2574
+ if (claimedFromServer) {
2575
+ claimedFromServer = false;
2576
+ // The region already holds the arm this run would build: either the
2577
+ // children the server rendered and the walk claimed (the normal case), or
2578
+ // the fallback claimed in place by claimServerArm. The markup already
2579
+ // there IS the answer, so leave it alone.
2580
+ if (regionHoldsArm && current === armAfterWalk) return;
2581
+ }
2582
+
2583
+ const host = startComment.parentNode;
2584
+ if (!host) return; // region detached before this run; nothing to update
2585
+
2586
+ const gen = ++generation;
2587
+
2588
+ // Same teardown as the client boundaries: everything between the markers
2589
+ // goes, disposed first so nested effects and component contexts die with
2590
+ // the nodes rather than outliving them.
2591
+ while (startComment.nextSibling && startComment.nextSibling !== endComment) {
2592
+ const old = startComment.nextSibling;
2593
+ disposeTree(old);
2594
+ host.removeChild(old);
2595
+ }
2596
+
2597
+ // Re-push the boundary for the rebuild. This effect re-runs long after the
2598
+ // hydration walk has unwound the stack, and anything built with an empty
2599
+ // stack gets `parentCtx = null`: a fallback that itself contains a
2600
+ // component would sit outside every context it was written inside.
2601
+ stack.push(boundaryCtx);
2602
+ try {
2603
+ const content = contentFor(current);
2604
+ const vnodes = Array.isArray(content) ? content : [content];
2605
+ for (const v of vnodes) {
2606
+ const node = createDOM(v, host);
2607
+ if (gen !== generation) {
2608
+ // A newer run already rebuilt the region. Whatever this node is, it
2609
+ // belongs to a superseded arm: dispose it rather than insert it
2610
+ // alongside the arm that won.
2611
+ if (node) disposeTree(node);
2612
+ break;
2613
+ }
2614
+ // endComment can be gone if that newer run tore the region down.
2615
+ if (!node) continue;
2616
+ if (endComment.parentNode) endComment.parentNode.insertBefore(node, endComment);
2617
+ else disposeTree(node);
2618
+ }
2619
+ } finally {
2620
+ stack.pop();
2621
+ }
2622
+ });
2623
+
2624
+ // Put the cursor back where the END MARKER actually ended up.
2625
+ //
2626
+ // The effect above runs SYNCHRONOUSLY, and when the state was already truthy
2627
+ // it has just removed R nodes from the region and inserted I of its own. The
2628
+ // cursor was fixed at endComment+1 a few lines earlier and knows nothing
2629
+ // about that, so it is off by (R - I) and the rest of the walk pays:
2630
+ //
2631
+ // - drifting forward SKIPS the boundary's next server sibling, which then
2632
+ // warns "got nothing" and is rendered a SECOND time. A page with a
2633
+ // boundary above the footer got two footers.
2634
+ // - drifting backward makes that sibling claim a node it must not, which
2635
+ // before the marker skip list above meant claiming the boundary's own
2636
+ // end marker and replaceChild()ing it away.
2637
+ //
2638
+ // Re-reading the marker's real index is the same re-sync the _mapArray branch
2639
+ // does, and for the same reason: once something has moved nodes behind the
2640
+ // walk's back, the only trustworthy answer to "where is the cursor now" is
2641
+ // where the marker physically is.
2642
+ if (cursorInParent && _hydrationCursor && _hydrationCursor.parent === parent) {
2643
+ const endIndex = Array.prototype.indexOf.call(parent.childNodes, endComment);
2644
+ if (endIndex >= 0) _hydrationCursor.index = endIndex + 1;
2645
+ }
2646
+
2647
+ boundaryCtx.effects.push(dispose);
2648
+ // The client registers a boundary context in dom.js's comment->ctx WeakMap;
2649
+ // the hydration disposer registry is the same idea reached from out here, and
2650
+ // disposeTree walks both. Registered on BOTH markers, matching the
2651
+ // reactive-region branch: whichever one a teardown happens to walk, the
2652
+ // boundary dies. disposeComponent latches on ctx.disposed, so being reached
2653
+ // twice is harmless.
2654
+ addHydratedComponent(startComment, boundaryCtx);
2655
+ addHydratedComponent(endComment, boundaryCtx);
2656
+
2657
+ // The START MARKER is the boundary's node, not its current contents.
2658
+ //
2659
+ // This matches the client exactly: createErrorBoundary returns a fragment
2660
+ // whose first node is that same start comment. It also matters for whoever
2661
+ // hydrated us. A component anchors its context to the first node its output
2662
+ // produced, and the contents of a boundary are the one thing that is
2663
+ // guaranteed to be replaced later, so returning them handed the enclosing
2664
+ // component a self-destructing anchor: the boundary catching an error
2665
+ // disposed the very component that wrapped the boundary. The markers outlive
2666
+ // every value the region holds, which is what an anchor has to do.
2667
+ return startComment;
2668
+ }
2669
+
2201
2670
  /**
2202
2671
  * Apply props to an existing hydrated element.
2203
2672
  * Attaches event handlers and reactive bindings without re-creating the element.
package/src/scheduler.js CHANGED
@@ -56,7 +56,24 @@ export function flushScheduler() {
56
56
  try { fn(); } catch (e) { console.error('[what] Scheduler write error:', e); }
57
57
  }
58
58
 
59
+ // Clear the flag BEFORE checking for leftovers so schedule() can arm a frame.
59
60
  scheduled = false;
61
+
62
+ // A callback may queue work whose phase has already run in this flush. The
63
+ // canonical case is cssTransition(): it asks for a reflow READ from inside a
64
+ // WRITE, and the read queue was drained before the write phase started.
65
+ // schedule() short-circuits while `scheduled` is true, so that request used
66
+ // to land in a drained queue with no frame armed and sat there until some
67
+ // unrelated code happened to poke the scheduler again (cssTransition's
68
+ // promise never settled and the element stayed on its start class).
69
+ //
70
+ // Arm another frame for whatever is left instead of dropping it. We defer by
71
+ // a frame rather than looping here on purpose: a callback that re-schedules
72
+ // itself unconditionally then costs one iteration per frame, the same bound
73
+ // as a plain requestAnimationFrame loop, instead of spinning the main thread
74
+ // forever inside a single flush. One frame is armed no matter how many
75
+ // leftovers there are, because schedule() is idempotent.
76
+ if (readQueue.length > 0 || writeQueue.length > 0) schedule();
60
77
  }
61
78
 
62
79
  // --- Internal scheduling ---