dinou 9.0.2 → 9.1.0

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 (41) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +379 -9742
  3. package/dinou/bun/build.js +38 -1
  4. package/{cli.js → dinou/cli.js} +8 -7
  5. package/dinou/cloudflare/build.js +37 -0
  6. package/dinou/core/bailout-proxy.js +2 -2
  7. package/dinou/core/build-static-pages.js +17 -7
  8. package/dinou/core/cache-revalidate.js +977 -152
  9. package/dinou/core/cache-slot.js +848 -103
  10. package/dinou/core/client-webpack.jsx +60 -9
  11. package/dinou/core/client.jsx +60 -9
  12. package/dinou/core/edge-ssr.js +33 -5
  13. package/dinou/core/generate-static.js +109 -47
  14. package/dinou/core/get-jsx.js +35 -27
  15. package/dinou/core/handler.js +786 -54
  16. package/dinou/core/layout-functions.js +102 -1
  17. package/dinou/core/no-dynamic.js +25 -0
  18. package/dinou/core/ppr-context.js +293 -10
  19. package/dinou/core/ppr-runtime.js +373 -37
  20. package/dinou/core/render-jsx-to-client-jsx.js +205 -74
  21. package/dinou/core/slot.js +246 -33
  22. package/dinou/core/storage-adapter.js +117 -11
  23. package/dinou/deno/build.js +38 -1
  24. package/dinou/deno/seed-kv.js +43 -11
  25. package/dinou/esbuild/helpers-esbuild/swc-disk-cache.js +242 -225
  26. package/dinou/esbuild/plugins-esbuild/server-functions-plugin.js +253 -226
  27. package/dinou/esbuild/react-refresh/esm-hmr/client.js +209 -209
  28. package/dinou/index.d.ts +10 -0
  29. package/dinou/index.js +3 -0
  30. package/dinou/node/build.js +2 -2
  31. package/dinou/node/bundle-dual-engine.js +2 -0
  32. package/dinou/node/dev.js +2853 -2704
  33. package/dinou/package.json +4 -1
  34. package/dinou/rollup/react-refresh/esm-hmr/client.js +220 -220
  35. package/dinou/rollup/rollup-plugins/rollup-plugin-server-functions.js +182 -160
  36. package/dinou/server.d.ts +65 -12
  37. package/dinou/server.js +11 -0
  38. package/dinou/webpack/loaders/server-functions-loader.js +101 -94
  39. package/dinou/webpack/webpack.config.js +9 -4
  40. package/eject.js +219 -223
  41. package/package.json +2 -2
@@ -1,9 +1,84 @@
1
+ import React from "react";
1
2
  import {
2
3
  isPprBuildActive,
3
- enterSuspense,
4
- exitSuspense,
4
+ isInsideSuspense,
5
+ isInsideOuterSuspenseOutsideSlot,
6
+ rollbackPprHolesAfter,
7
+ isInsideCachedSlot,
8
+ runInSuspense,
9
+ getPprHoleCounter,
10
+ commitPprSuspenseEffects,
5
11
  registerHole,
12
+ markDynamicAccess,
13
+ isPageRootElement,
14
+ runInPageSegment,
15
+ resetComponentNoDynamicFlag,
16
+ consumeComponentNoDynamicFlag,
17
+ isNoDynamicActive,
18
+ isSlotDiscoveryActive,
6
19
  } from "./ppr-context.js";
20
+ import { getContext } from "./request-context.js";
21
+
22
+ function isThenable(val) {
23
+ return (
24
+ val !== null &&
25
+ (typeof val === "object" || typeof val === "function") &&
26
+ typeof val.then === "function"
27
+ );
28
+ }
29
+
30
+ function isCacheSlotComponent(fn) {
31
+ if (!fn) return false;
32
+ return Boolean(fn.$$dinouCacheSlot || fn.name === "DinouCacheSlot");
33
+ }
34
+
35
+ async function invokeServerComponentInPpr(fn, callFn) {
36
+ resetComponentNoDynamicFlag();
37
+ const rawResult = callFn();
38
+ const optedOut = consumeComponentNoDynamicFlag();
39
+ if (
40
+ isThenable(rawResult) &&
41
+ !isCacheSlotComponent(fn) &&
42
+ isPprBuildActive() &&
43
+ isInsideOuterSuspenseOutsideSlot() &&
44
+ !isSlotDiscoveryActive() &&
45
+ !optedOut &&
46
+ !isNoDynamicActive()
47
+ ) {
48
+ try {
49
+ rawResult.then(null, () => {});
50
+ } catch (_) {}
51
+ markDynamicAccess("async-suspense");
52
+ }
53
+ return await rawResult;
54
+ }
55
+
56
+ function cloneWithDevProps(jsx, newProps, resolvedKey, overrideType) {
57
+ const cloned = {
58
+ ...jsx,
59
+ $$typeof: Symbol.for("react.transitional.element"),
60
+ type: overrideType !== undefined ? overrideType : jsx.type,
61
+ props: newProps,
62
+ key: resolvedKey,
63
+ };
64
+ if ("_owner" in jsx) cloned._owner = jsx._owner;
65
+ if ("_store" in jsx && jsx._store) {
66
+ cloned._store = {};
67
+ Object.defineProperty(cloned._store, "validated", {
68
+ configurable: false,
69
+ enumerable: false,
70
+ writable: true,
71
+ value: jsx._store.validated || 1,
72
+ });
73
+ }
74
+ for (const devProp of ["ref", "_debugInfo", "_debugStack", "_debugTask"]) {
75
+ const desc = Object.getOwnPropertyDescriptor(jsx, devProp);
76
+ if (desc) {
77
+ Object.defineProperty(cloned, devProp, desc);
78
+ }
79
+ }
80
+ return cloned;
81
+ }
7
82
 
8
83
  // Function to check if a component is a client component
9
84
  function isClientComponent(type) {
@@ -18,6 +93,20 @@ function isClientComponent(type) {
18
93
  }
19
94
 
20
95
  async function asyncRenderJSXToClientJSX(jsx, key = null) {
96
+ if (isPageRootElement(jsx)) {
97
+ return await runInPageSegment(async () => {
98
+ const resolved = await asyncRenderJSXToClientJSXInner(jsx, key);
99
+ const ctx = getContext();
100
+ if (ctx) {
101
+ ctx._resolvedPageClientJsx = resolved;
102
+ }
103
+ return resolved;
104
+ });
105
+ }
106
+ return await asyncRenderJSXToClientJSXInner(jsx, key);
107
+ }
108
+
109
+ async function asyncRenderJSXToClientJSXInner(jsx, key = null) {
21
110
  if (
22
111
  typeof jsx === "string" ||
23
112
  typeof jsx === "number" ||
@@ -28,6 +117,13 @@ async function asyncRenderJSXToClientJSX(jsx, key = null) {
28
117
  ) {
29
118
  return jsx;
30
119
  } else if (Array.isArray(jsx)) {
120
+ if (isPprBuildActive()) {
121
+ const results = [];
122
+ for (const child of jsx) {
123
+ results.push(await asyncRenderJSXToClientJSX(child, child?.key ?? null));
124
+ }
125
+ return results;
126
+ }
31
127
  return await Promise.all(
32
128
  jsx.map((child) =>
33
129
  asyncRenderJSXToClientJSX(
@@ -39,12 +135,7 @@ async function asyncRenderJSXToClientJSX(jsx, key = null) {
39
135
  } else if (typeof jsx === "symbol") {
40
136
  if (jsx === Symbol.for("react.fragment")) {
41
137
  // Handle Fragment as an empty props object
42
- return {
43
- $$typeof: Symbol.for("react.transitional.element"),
44
- type: Symbol.for("react.fragment"),
45
- props: {},
46
- key,
47
- };
138
+ return React.createElement(React.Fragment, key != null ? { key } : null);
48
139
  }
49
140
  console.error("Unsupported symbol:", String(jsx));
50
141
  throw new Error(`Unsupported symbol: ${String(jsx)}`);
@@ -52,71 +143,98 @@ async function asyncRenderJSXToClientJSX(jsx, key = null) {
52
143
  if (jsx.$$typeof === Symbol.for("react.transitional.element")) {
53
144
  if (jsx.type === Symbol.for("react.suspense")) {
54
145
  if (isPprBuildActive()) {
55
- const holeId = enterSuspense();
56
- try {
57
- const renderedChildren = await asyncRenderJSXToClientJSX(jsx.props?.children);
58
- exitSuspense();
59
- return {
60
- ...jsx,
61
- props: {
62
- ...jsx.props,
63
- children: renderedChildren,
64
- fallback: await asyncRenderJSXToClientJSX(jsx.props?.fallback),
65
- },
66
- key: key ?? jsx.key,
67
- };
68
- } catch (err) {
69
- exitSuspense();
70
- if (
71
- (err && err.$$typeof === Symbol.for("dinou.ppr.postpone")) ||
72
- (err && typeof err?.then === "function") ||
73
- (err && err?.$$typeof === Symbol.for("react.postpone"))
74
- ) {
75
- registerHole(holeId, { type: err.pprType || "suspense" });
146
+ return await runInSuspense(async (holeId, suspenseStore) => {
147
+ const countBefore = getPprHoleCounter();
148
+ try {
149
+ const renderedChildren = await asyncRenderJSXToClientJSX(jsx.props?.children);
76
150
  const renderedFallback = await asyncRenderJSXToClientJSX(jsx.props?.fallback);
77
- return {
78
- $$typeof: Symbol.for("react.transitional.element"),
79
- type: "div",
80
- props: {
81
- "data-ppr-hole": holeId,
82
- style: { display: "contents" },
83
- children: renderedFallback,
151
+ const hasNestedSuspense = getPprHoleCounter() > countBefore;
152
+ await commitPprSuspenseEffects(suspenseStore);
153
+ return cloneWithDevProps(
154
+ jsx,
155
+ {
156
+ ...jsx.props,
157
+ ...(hasNestedSuspense ? { "data-ppr-static-parent": holeId } : {}),
158
+ children: hasNestedSuspense
159
+ ? React.createElement(
160
+ "div",
161
+ { "data-ppr-static-parent": holeId, style: { display: "contents" } },
162
+ renderedChildren
163
+ )
164
+ : renderedChildren,
165
+ fallback: renderedFallback,
84
166
  },
85
- key: key ?? jsx.key,
86
- };
167
+ key ?? jsx.key
168
+ );
169
+ } catch (err) {
170
+ if (
171
+ (suspenseStore?.slotDepthAtSuspense || 0) === 0 &&
172
+ ((err && err.$$typeof === Symbol.for("dinou.ppr.postpone")) ||
173
+ (err && typeof err?.then === "function") ||
174
+ (err && err?.$$typeof === Symbol.for("react.postpone")))
175
+ ) {
176
+ rollbackPprHolesAfter(countBefore);
177
+ registerHole(holeId, { type: err.pprType || "suspense" });
178
+ const renderedFallback = await asyncRenderJSXToClientJSX(jsx.props?.fallback);
179
+ return cloneWithDevProps(
180
+ jsx,
181
+ {
182
+ "data-ppr-hole": holeId,
183
+ style: { display: "contents" },
184
+ children: renderedFallback,
185
+ },
186
+ key ?? jsx.key,
187
+ "div"
188
+ );
189
+ }
190
+ throw err;
191
+ } finally {
192
+ if (suspenseStore) {
193
+ suspenseStore.settled = true;
194
+ }
87
195
  }
88
- throw err;
89
- }
196
+ });
90
197
  }
91
- return {
92
- ...jsx,
93
- props: await asyncRenderJSXToClientJSX(jsx.props),
94
- key: key ?? jsx.key,
95
- };
198
+ return await runInSuspense(async () => {
199
+ return cloneWithDevProps(
200
+ jsx,
201
+ await asyncRenderJSXToClientJSX(jsx.props),
202
+ key ?? jsx.key
203
+ );
204
+ });
96
205
  } else if (
97
206
  jsx.type === Symbol.for("react.fragment") ||
98
207
  jsx.type === Symbol.for("react.view_transition") ||
99
208
  typeof jsx.type === "string"
100
209
  ) {
101
- return {
102
- ...jsx,
103
- props: await asyncRenderJSXToClientJSX(jsx.props),
104
- key: key ?? jsx.key,
105
- };
210
+ return cloneWithDevProps(
211
+ jsx,
212
+ await asyncRenderJSXToClientJSX(jsx.props),
213
+ key ?? jsx.key
214
+ );
106
215
  } else if (typeof jsx.type === "function") {
107
216
  const Component = jsx.type;
108
217
  const props = jsx.props;
109
218
  if (isClientComponent(Component)) {
110
- return {
111
- ...jsx,
112
- $$typeof: Symbol.for("react.transitional.element"),
113
- type: Component,
114
- props: await asyncRenderJSXToClientJSX(props),
115
- key: key ?? jsx.key,
116
- };
219
+ if (jsx.__clientJsxAlreadyRendered) {
220
+ return cloneWithDevProps(
221
+ jsx,
222
+ props,
223
+ key ?? jsx.key,
224
+ Component
225
+ );
226
+ }
227
+ return cloneWithDevProps(
228
+ jsx,
229
+ await asyncRenderJSXToClientJSX(props),
230
+ key ?? jsx.key,
231
+ Component
232
+ );
117
233
  } else {
118
234
  // Server component: execute and process
119
- const returnedJsx = await Component(props);
235
+ const returnedJsx = await invokeServerComponentInPpr(Component, () =>
236
+ Component(props)
237
+ );
120
238
  return await asyncRenderJSXToClientJSX(returnedJsx, key ?? jsx.key);
121
239
  }
122
240
  } else if (
@@ -125,15 +243,17 @@ async function asyncRenderJSXToClientJSX(jsx, key = null) {
125
243
  jsx.type.$$typeof === Symbol.for("react.forward_ref")
126
244
  ) {
127
245
  if (isClientComponent(jsx.type)) {
128
- return {
129
- ...jsx,
130
- $$typeof: Symbol.for("react.transitional.element"),
131
- type: jsx.type,
132
- props: await asyncRenderJSXToClientJSX(jsx.props),
133
- key: key ?? jsx.key,
134
- };
246
+ return cloneWithDevProps(
247
+ jsx,
248
+ await asyncRenderJSXToClientJSX(jsx.props),
249
+ key ?? jsx.key,
250
+ jsx.type
251
+ );
135
252
  } else {
136
- const returnedJsx = await jsx.type.render(jsx.props, jsx.ref);
253
+ const returnedJsx = await invokeServerComponentInPpr(
254
+ jsx.type.render,
255
+ () => jsx.type.render(jsx.props, jsx.ref)
256
+ );
137
257
  return await asyncRenderJSXToClientJSX(returnedJsx, key ?? jsx.key);
138
258
  }
139
259
  } else if (
@@ -142,16 +262,20 @@ async function asyncRenderJSXToClientJSX(jsx, key = null) {
142
262
  jsx.type.$$typeof === Symbol.for("react.memo")
143
263
  ) {
144
264
  if (isClientComponent(jsx.type)) {
145
- return {
146
- ...jsx,
147
- $$typeof: Symbol.for("react.transitional.element"),
148
- type: jsx.type,
149
- props: await asyncRenderJSXToClientJSX(jsx.props),
150
- key: key ?? jsx.key,
151
- };
265
+ return cloneWithDevProps(
266
+ jsx,
267
+ await asyncRenderJSXToClientJSX(jsx.props),
268
+ key ?? jsx.key,
269
+ jsx.type
270
+ );
152
271
  } else {
153
272
  const innerComp = jsx.type.type;
154
- const returnedJsx = typeof innerComp === "function" ? await innerComp(jsx.props) : null;
273
+ const returnedJsx =
274
+ typeof innerComp === "function"
275
+ ? await invokeServerComponentInPpr(innerComp, () =>
276
+ innerComp(jsx.props)
277
+ )
278
+ : null;
155
279
  return await asyncRenderJSXToClientJSX(returnedJsx, key ?? jsx.key);
156
280
  }
157
281
  } else {
@@ -162,6 +286,13 @@ async function asyncRenderJSXToClientJSX(jsx, key = null) {
162
286
  return jsx;
163
287
  } else {
164
288
  // Process object props (e.g., { className: "foo" })
289
+ if (isPprBuildActive()) {
290
+ const entries = [];
291
+ for (const [propName, value] of Object.entries(jsx)) {
292
+ entries.push([propName, await asyncRenderJSXToClientJSX(value)]);
293
+ }
294
+ return Object.fromEntries(entries);
295
+ }
165
296
  return Object.fromEntries(
166
297
  await Promise.all(
167
298
  Object.entries(jsx).map(async ([propName, value]) => [
@@ -7,6 +7,7 @@ const useContext = React.useContext;
7
7
  const useMemo = React.useMemo;
8
8
  const useState = React.useState;
9
9
  const useEffect = React.useEffect;
10
+ const useLayoutEffect = React.useLayoutEffect || React.useEffect;
10
11
  const startTransition = React.startTransition;
11
12
  const use = React.use;
12
13
  const createElement = React.createElement;
@@ -217,7 +218,21 @@ class SlotErrorBoundary extends Component {
217
218
  }
218
219
  }
219
220
 
220
- function PageConsumer({ pagePromise }) {
221
+ function PageConsumer({ pagePromise, pageElement }) {
222
+ if (typeof useLayoutEffect === "function" && typeof window !== "undefined") {
223
+ useLayoutEffect(() => {
224
+ if (
225
+ typeof document !== "undefined" &&
226
+ document.body &&
227
+ document.body.getAttribute("data-hydrated") !== "true"
228
+ ) {
229
+ document.body.setAttribute("data-hydrated", "true");
230
+ }
231
+ });
232
+ }
233
+ if (pageElement !== undefined) {
234
+ return pageElement;
235
+ }
221
236
  if (pagePromise && pagePromise.status === "rejected") {
222
237
  throw pagePromise.reason;
223
238
  }
@@ -225,13 +240,19 @@ function PageConsumer({ pagePromise }) {
225
240
  }
226
241
 
227
242
  export function DinouPageSlot() {
228
- if (typeof useContext !== "function" || !DinouPageContext) {
229
- return null;
230
- }
231
- const slotContext = useContext(DinouPageContext);
243
+ const fallbackContext =
244
+ typeof globalThis !== "undefined" ? globalThis.__DINOU_SSR_SLOT_CONTEXT__ : null;
245
+ const slotContext =
246
+ typeof useContext === "function" && DinouPageContext
247
+ ? useContext(DinouPageContext) || fallbackContext
248
+ : fallbackContext;
232
249
  if (!slotContext) {
233
250
  return null;
234
251
  }
252
+ const pageElement =
253
+ slotContext && slotContext.pageElement !== undefined
254
+ ? slotContext.pageElement
255
+ : undefined;
235
256
  const pagePromise =
236
257
  slotContext && slotContext.pagePromise !== undefined
237
258
  ? slotContext.pagePromise
@@ -244,57 +265,249 @@ export function DinouPageSlot() {
244
265
  return createElement(
245
266
  SlotErrorBoundary,
246
267
  { resetKey, pagePromise },
247
- createElement(PageConsumer, { pagePromise })
268
+ createElement(PageConsumer, { pagePromise, pageElement })
248
269
  );
249
270
  }
250
271
 
251
- function SlotConsumer({ slotPromise, fallback }) {
252
- if (slotPromise && slotPromise.status === "rejected") {
253
- throw slotPromise.reason;
254
- }
255
- return use ? use(slotPromise) : (slotPromise || fallback);
272
+ const slotOverrideCache =
273
+ typeof globalThis !== "undefined"
274
+ ? (globalThis.__DINOU_SLOT_OVERRIDE_CACHE__ =
275
+ globalThis.__DINOU_SLOT_OVERRIDE_CACHE__ || new Map())
276
+ : new Map();
277
+
278
+ const knownClientSlots =
279
+ typeof globalThis !== "undefined"
280
+ ? (globalThis.__DINOU_KNOWN_CLIENT_SLOTS__ =
281
+ globalThis.__DINOU_KNOWN_CLIENT_SLOTS__ || new Map())
282
+ : new Map();
283
+
284
+ const mountedClientSlots =
285
+ typeof globalThis !== "undefined"
286
+ ? (globalThis.__DINOU_MOUNTED_CLIENT_SLOTS__ =
287
+ globalThis.__DINOU_MOUNTED_CLIENT_SLOTS__ || new Set())
288
+ : new Set();
289
+
290
+ if (
291
+ typeof window !== "undefined" &&
292
+ !window.__DINOU_UNMOUNTED_SLOT_LISTENER_INSTALLED__
293
+ ) {
294
+ window.__DINOU_UNMOUNTED_SLOT_LISTENER_INSTALLED__ = true;
295
+ window.addEventListener("dinou:refresh-slot", (e) => {
296
+ const targetId = e?.detail?.id;
297
+ const options = e?.detail?.options;
298
+ if (typeof window.__DINOU_FETCH_SLOT__ !== "function") return;
299
+
300
+ for (const [slotId, entry] of knownClientSlots.entries()) {
301
+ if (mountedClientSlots.has(slotId)) continue;
302
+ const matchesTag =
303
+ Array.isArray(entry.tags) && targetId && entry.tags.includes(targetId);
304
+ if (!e || !e.detail || targetId === slotId || targetId === "*" || matchesTag) {
305
+ const fetchOpts = {
306
+ ...(options || {}),
307
+ currentPath: entry.routePath || window.location.pathname,
308
+ };
309
+ const promise = window.__DINOU_FETCH_SLOT__(slotId, fetchOpts);
310
+ if (promise && typeof promise.then === "function") {
311
+ const reqId = (entry.latestReqId || 0) + 1;
312
+ entry.latestReqId = reqId;
313
+ entry.pendingPromise = promise;
314
+ entry.pendingReqId = reqId;
315
+ const baseRef = entry.baseChildren;
316
+ promise.then(
317
+ (resolved) => {
318
+ if (entry.latestReqId !== reqId) {
319
+ return;
320
+ }
321
+ if (entry.pendingPromise === promise) {
322
+ entry.pendingPromise = null;
323
+ }
324
+ slotOverrideCache.set(slotId, {
325
+ baseChildren: baseRef,
326
+ content: resolved,
327
+ });
328
+ if (typeof entry.notifyMounted === "function") {
329
+ entry.notifyMounted(resolved, baseRef);
330
+ }
331
+ },
332
+ () => {
333
+ if (entry.pendingPromise === promise) {
334
+ entry.pendingPromise = null;
335
+ }
336
+ }
337
+ );
338
+ }
339
+ }
340
+ }
341
+ });
256
342
  }
257
343
 
258
- export function DinouCacheSlotBoundary({ id, children }) {
344
+ export function DinouCacheSlotBoundary({ id, tags, children }) {
259
345
  if (typeof useState !== "function") {
260
346
  return children;
261
347
  }
262
- const [slotPromise, setSlotPromise] = useState(null);
348
+ const isBrowser = typeof window !== "undefined";
349
+ const cachedOverride = isBrowser ? slotOverrideCache.get(id) : null;
350
+ const initialContent =
351
+ cachedOverride && cachedOverride.baseChildren === children
352
+ ? cachedOverride.content
353
+ : null;
354
+
355
+ const [override, setOverride] = useState({
356
+ baseChildren: children,
357
+ content: initialContent,
358
+ });
359
+ const childrenRef =
360
+ typeof React.useRef === "function" ? React.useRef(children) : { current: children };
361
+ childrenRef.current = children;
362
+
363
+ if (isBrowser) {
364
+ const existingKnown = knownClientSlots.get(id);
365
+ if (!existingKnown || existingKnown.baseChildren !== children) {
366
+ knownClientSlots.set(id, {
367
+ id,
368
+ tags: Array.isArray(tags) ? tags : [],
369
+ baseChildren: children,
370
+ routePath: window.location.pathname,
371
+ pendingPromise: existingKnown?.pendingPromise || null,
372
+ pendingReqId: existingKnown?.pendingReqId || 0,
373
+ latestReqId: existingKnown?.latestReqId || 0,
374
+ notifyMounted: existingKnown?.notifyMounted || null,
375
+ });
376
+ } else if (Array.isArray(tags)) {
377
+ existingKnown.tags = tags;
378
+ }
379
+ if (cachedOverride && cachedOverride.baseChildren !== children) {
380
+ slotOverrideCache.delete(id);
381
+ }
382
+ }
263
383
 
264
384
  useEffect(() => {
385
+ mountedClientSlots.add(id);
386
+ const applyResolved = (resolved, baseRef = childrenRef.current) => {
387
+ slotOverrideCache.set(id, {
388
+ baseChildren: baseRef,
389
+ content: resolved,
390
+ });
391
+ const applyFn = () => {
392
+ setOverride({
393
+ baseChildren: baseRef,
394
+ content: resolved,
395
+ });
396
+ };
397
+ if (typeof startTransition === "function") {
398
+ startTransition(applyFn);
399
+ } else {
400
+ applyFn();
401
+ }
402
+ };
403
+
404
+ const knownEntry = knownClientSlots.get(id);
405
+ if (knownEntry) {
406
+ knownEntry.routePath = window.location.pathname;
407
+ knownEntry.baseChildren = childrenRef.current;
408
+ knownEntry.notifyMounted = applyResolved;
409
+ if (Array.isArray(tags)) {
410
+ knownEntry.tags = tags;
411
+ }
412
+ if (knownEntry.pendingPromise) {
413
+ const pending = knownEntry.pendingPromise;
414
+ const pendingReqId = knownEntry.pendingReqId;
415
+ pending.then(
416
+ (resolved) => {
417
+ if (knownEntry.latestReqId !== pendingReqId) {
418
+ return;
419
+ }
420
+ if (knownEntry.pendingPromise === pending) {
421
+ knownEntry.pendingPromise = null;
422
+ }
423
+ applyResolved(resolved, childrenRef.current);
424
+ },
425
+ () => {}
426
+ );
427
+ }
428
+ }
429
+
430
+ const latestCached = slotOverrideCache.get(id);
431
+ if (
432
+ latestCached &&
433
+ latestCached.baseChildren === childrenRef.current &&
434
+ latestCached.content !== null
435
+ ) {
436
+ setOverride((prev) =>
437
+ prev.content === latestCached.content && prev.baseChildren === childrenRef.current
438
+ ? prev
439
+ : { baseChildren: childrenRef.current, content: latestCached.content }
440
+ );
441
+ }
442
+
265
443
  const handleRefresh = (e) => {
266
- if (!e || !e.detail || e.detail.id === id || e.detail.id === "*") {
444
+ const targetId = e?.detail?.id;
445
+ const matchesTag = Array.isArray(tags) && targetId && tags.includes(targetId);
446
+ if (!e || !e.detail || targetId === id || targetId === "*" || matchesTag) {
267
447
  if (
268
448
  typeof window !== "undefined" &&
269
449
  typeof window.__DINOU_FETCH_SLOT__ === "function"
270
450
  ) {
451
+ const curEntry = knownClientSlots.get(id);
271
452
  const promise = window.__DINOU_FETCH_SLOT__(id, e.detail?.options);
272
- if (promise) {
273
- if (typeof startTransition === "function") {
274
- startTransition(() => {
275
- setSlotPromise(promise);
276
- });
277
- } else {
278
- setSlotPromise(promise);
453
+ const reqId = curEntry ? (curEntry.latestReqId || 0) + 1 : 0;
454
+ if (curEntry) {
455
+ curEntry.latestReqId = reqId;
456
+ }
457
+ if (promise && typeof promise.then === "function") {
458
+ if (curEntry) {
459
+ curEntry.pendingPromise = promise;
460
+ curEntry.pendingReqId = reqId;
279
461
  }
462
+ promise.then(
463
+ (resolved) => {
464
+ if (curEntry && curEntry.latestReqId !== reqId) {
465
+ return;
466
+ }
467
+ if (curEntry && curEntry.pendingPromise === promise) {
468
+ curEntry.pendingPromise = null;
469
+ }
470
+ applyResolved(resolved, childrenRef.current);
471
+ },
472
+ (err) => {
473
+ if (curEntry && curEntry.pendingPromise === promise) {
474
+ curEntry.pendingPromise = null;
475
+ }
476
+ console.error(`[Dinou] Failed to refresh slot "${id}":`, err);
477
+ }
478
+ );
479
+ } else if (promise) {
480
+ if (curEntry) {
481
+ curEntry.pendingPromise = null;
482
+ }
483
+ applyResolved(promise, childrenRef.current);
280
484
  }
281
485
  }
282
486
  }
283
487
  };
284
488
  window.addEventListener("dinou:refresh-slot", handleRefresh);
285
- return () => window.removeEventListener("dinou:refresh-slot", handleRefresh);
286
- }, [id]);
489
+ return () => {
490
+ mountedClientSlots.delete(id);
491
+ const curKnown = knownClientSlots.get(id);
492
+ if (curKnown && curKnown.notifyMounted === applyResolved) {
493
+ curKnown.notifyMounted = null;
494
+ }
495
+ window.removeEventListener("dinou:refresh-slot", handleRefresh);
496
+ };
497
+ }, [id, tags]);
287
498
 
288
- if (slotPromise) {
289
- return createElement(
290
- SlotErrorBoundary,
291
- { resetKey: slotPromise, pagePromise: slotPromise },
292
- createElement(
293
- Suspense,
294
- { fallback: children },
295
- createElement(SlotConsumer, { slotPromise, fallback: children })
296
- )
297
- );
499
+ if (isBrowser) {
500
+ const latestCached = slotOverrideCache.get(id);
501
+ if (
502
+ latestCached &&
503
+ latestCached.content !== null &&
504
+ latestCached.baseChildren === children
505
+ ) {
506
+ return latestCached.content;
507
+ }
508
+ }
509
+ if (override.content !== null && override.baseChildren === children) {
510
+ return override.content;
298
511
  }
299
512
  return children;
300
513
  }