@decocms/tanstack 8.1.0-next.0 → 8.4.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 (177) hide show
  1. package/README.md +79 -0
  2. package/dist/draft.d.ts +33 -0
  3. package/dist/draft.d.ts.map +1 -0
  4. package/dist/draft.js +41 -0
  5. package/dist/draft.js.map +1 -0
  6. package/dist/index.d.ts +9 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +9 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/react/DecoDocument.d.ts +61 -0
  11. package/dist/react/DecoDocument.d.ts.map +1 -0
  12. package/dist/react/DecoDocument.js +96 -0
  13. package/dist/react/DecoDocument.js.map +1 -0
  14. package/dist/react/Image.d.ts +96 -0
  15. package/dist/react/Image.d.ts.map +1 -0
  16. package/dist/react/Image.js +79 -0
  17. package/dist/react/Image.js.map +1 -0
  18. package/dist/react/index.d.ts +7 -0
  19. package/dist/react/index.d.ts.map +1 -0
  20. package/dist/react/index.js +7 -0
  21. package/dist/react/index.js.map +1 -0
  22. package/dist/react/pageValues.d.ts +10 -0
  23. package/dist/react/pageValues.d.ts.map +1 -0
  24. package/dist/react/pageValues.js +29 -0
  25. package/dist/react/pageValues.js.map +1 -0
  26. package/dist/react/scripts.d.ts +14 -0
  27. package/dist/react/scripts.d.ts.map +1 -0
  28. package/dist/react/scripts.js +96 -0
  29. package/dist/react/scripts.js.map +1 -0
  30. package/dist/router/index.d.ts +38 -0
  31. package/dist/router/index.d.ts.map +1 -0
  32. package/dist/router/index.js +60 -0
  33. package/dist/router/index.js.map +1 -0
  34. package/dist/scope/browser.d.ts +11 -0
  35. package/dist/scope/browser.d.ts.map +1 -0
  36. package/dist/scope/browser.js +8 -0
  37. package/dist/scope/browser.js.map +1 -0
  38. package/dist/scope/server.d.ts +13 -0
  39. package/dist/scope/server.d.ts.map +1 -0
  40. package/dist/scope/server.js +26 -0
  41. package/dist/scope/server.js.map +1 -0
  42. package/dist/server/index.d.ts +27 -0
  43. package/dist/server/index.d.ts.map +1 -0
  44. package/dist/server/index.js +31 -0
  45. package/dist/server/index.js.map +1 -0
  46. package/dist/shared.d.ts +26 -0
  47. package/dist/shared.d.ts.map +1 -0
  48. package/dist/shared.js +26 -0
  49. package/dist/shared.js.map +1 -0
  50. package/dist/start/index.d.ts +9 -0
  51. package/dist/start/index.d.ts.map +1 -0
  52. package/dist/start/index.js +33 -0
  53. package/dist/start/index.js.map +1 -0
  54. package/dist/studio.d.ts +28 -0
  55. package/dist/studio.d.ts.map +1 -0
  56. package/dist/studio.js +53 -0
  57. package/dist/studio.js.map +1 -0
  58. package/dist/vite/index.d.ts +15 -0
  59. package/dist/vite/index.d.ts.map +1 -0
  60. package/dist/vite/index.js +95 -0
  61. package/dist/vite/index.js.map +1 -0
  62. package/dist/worker/cacheProfiles.d.ts +43 -0
  63. package/dist/worker/cacheProfiles.d.ts.map +1 -0
  64. package/dist/worker/cacheProfiles.js +162 -0
  65. package/dist/worker/cacheProfiles.js.map +1 -0
  66. package/dist/worker/cookies.d.ts +20 -0
  67. package/dist/worker/cookies.d.ts.map +1 -0
  68. package/dist/worker/cookies.js +69 -0
  69. package/dist/worker/cookies.js.map +1 -0
  70. package/dist/worker/drafts.d.ts +59 -0
  71. package/dist/worker/drafts.d.ts.map +1 -0
  72. package/dist/worker/drafts.js +140 -0
  73. package/dist/worker/drafts.js.map +1 -0
  74. package/dist/worker/index.d.ts +107 -0
  75. package/dist/worker/index.d.ts.map +1 -0
  76. package/dist/worker/index.js +511 -0
  77. package/dist/worker/index.js.map +1 -0
  78. package/dist/worker/security.d.ts +14 -0
  79. package/dist/worker/security.d.ts.map +1 -0
  80. package/dist/worker/security.js +48 -0
  81. package/dist/worker/security.js.map +1 -0
  82. package/dist/worker/segment.d.ts +21 -0
  83. package/dist/worker/segment.d.ts.map +1 -0
  84. package/dist/worker/segment.js +43 -0
  85. package/dist/worker/segment.js.map +1 -0
  86. package/package.json +85 -37
  87. package/src/draft.ts +43 -0
  88. package/src/index.ts +8 -61
  89. package/src/react/DecoDocument.tsx +234 -0
  90. package/src/react/Image.tsx +213 -0
  91. package/src/react/index.ts +24 -0
  92. package/src/react/pageValues.ts +35 -0
  93. package/src/react/scripts.ts +98 -0
  94. package/src/router/index.ts +80 -0
  95. package/src/scope/browser.ts +18 -0
  96. package/src/scope/server.ts +37 -0
  97. package/src/server/index.ts +43 -0
  98. package/src/shared.ts +29 -0
  99. package/src/start/index.ts +31 -0
  100. package/src/studio.ts +52 -0
  101. package/src/vite/index.ts +105 -0
  102. package/src/worker/cacheProfiles.ts +180 -0
  103. package/src/worker/cookies.ts +65 -0
  104. package/src/worker/drafts.ts +157 -0
  105. package/src/worker/index.ts +648 -0
  106. package/src/worker/security.ts +63 -0
  107. package/src/worker/segment.ts +49 -0
  108. package/src/__conformance__/observability.test.ts +0 -221
  109. package/src/cms/kvBlockSource.test.ts +0 -82
  110. package/src/cms/kvBlockSource.ts +0 -68
  111. package/src/daemon/auth.ts +0 -204
  112. package/src/daemon/fs.ts +0 -238
  113. package/src/daemon/index.ts +0 -8
  114. package/src/daemon/middleware.ts +0 -156
  115. package/src/daemon/tunnel.ts +0 -129
  116. package/src/daemon/volumes.ts +0 -366
  117. package/src/daemon/watch.ts +0 -272
  118. package/src/hooks/CdnSegmentMarker.tsx +0 -38
  119. package/src/hooks/DecoPageRenderer.tsx +0 -750
  120. package/src/hooks/DecoRootLayout.tsx +0 -192
  121. package/src/hooks/DraftPreviewIndicator.test.tsx +0 -60
  122. package/src/hooks/DraftPreviewIndicator.tsx +0 -64
  123. package/src/hooks/NavigationProgress.test.tsx +0 -58
  124. package/src/hooks/NavigationProgress.tsx +0 -63
  125. package/src/hooks/PreviewProviders.test.tsx +0 -42
  126. package/src/hooks/PreviewProviders.tsx +0 -45
  127. package/src/hooks/StableOutlet.tsx +0 -30
  128. package/src/hooks/deferredObserverTiming.test.tsx +0 -91
  129. package/src/hooks/index.ts +0 -10
  130. package/src/routes/adminRoutes.test.ts +0 -99
  131. package/src/routes/adminRoutes.ts +0 -153
  132. package/src/routes/cmsRoute.test.ts +0 -267
  133. package/src/routes/cmsRoute.ts +0 -1053
  134. package/src/routes/components.tsx +0 -57
  135. package/src/routes/index.ts +0 -24
  136. package/src/routes/pageUrl.test.ts +0 -70
  137. package/src/routes/pageUrl.ts +0 -55
  138. package/src/routes/withSiteGlobals.test.ts +0 -243
  139. package/src/routes/withSiteGlobals.ts +0 -243
  140. package/src/sdk/backgroundTasks.test.ts +0 -68
  141. package/src/sdk/backgroundTasks.ts +0 -38
  142. package/src/sdk/cdnSegment.test.ts +0 -67
  143. package/src/sdk/cdnSegment.ts +0 -71
  144. package/src/sdk/cookiePassthrough.ts +0 -58
  145. package/src/sdk/createInvoke.ts +0 -77
  146. package/src/sdk/deferredSectionLoader.test.ts +0 -94
  147. package/src/sdk/deferredSectionLoader.ts +0 -46
  148. package/src/sdk/draft.test.ts +0 -341
  149. package/src/sdk/draft.ts +0 -277
  150. package/src/sdk/draftShared.ts +0 -16
  151. package/src/sdk/kvHydration.test.ts +0 -371
  152. package/src/sdk/kvHydration.ts +0 -263
  153. package/src/sdk/kvRedirects.test.ts +0 -132
  154. package/src/sdk/kvRedirects.ts +0 -125
  155. package/src/sdk/outboundHeaders.test.ts +0 -113
  156. package/src/sdk/outboundHeaders.ts +0 -81
  157. package/src/sdk/router.ts +0 -101
  158. package/src/sdk/serverFnFetch.ts +0 -59
  159. package/src/sdk/speculationRules.test.ts +0 -82
  160. package/src/sdk/speculationRules.ts +0 -136
  161. package/src/sdk/startEntry.ts +0 -31
  162. package/src/sdk/useHydrated.ts +0 -19
  163. package/src/sdk/workerEntry.cacheStorage.test.ts +0 -147
  164. package/src/sdk/workerEntry.test.ts +0 -1033
  165. package/src/sdk/workerEntry.trackingCache.test.ts +0 -328
  166. package/src/sdk/workerEntry.ts +0 -3154
  167. package/src/setupFastDeploy.ts +0 -13
  168. package/src/v8/__conformance__/delivery.test.ts +0 -100
  169. package/src/v8/binding.ts +0 -70
  170. package/src/v8/kvLoader.bundle.test.ts +0 -42
  171. package/src/v8/kvLoader.test.ts +0 -74
  172. package/src/v8/kvLoader.ts +0 -43
  173. package/src/vite/plugin-scaffold-gen.test.js +0 -106
  174. package/src/vite/plugin.js +0 -1022
  175. package/src/vite/plugin.test.js +0 -238
  176. package/src/vite/plugin.test.ts +0 -176
  177. package/tsconfig.json +0 -7
@@ -0,0 +1,213 @@
1
+ "use client";
2
+ /**
3
+ * `Image`, `Picture` and `Source`: v7's components (`@decocms/blocks` 7.x
4
+ * `hooks/Image.tsx` and `hooks/Picture.tsx`) with the same props and the same
5
+ * markup, so call sites move by changing the import. The URLs come from an
6
+ * `ImageUrl` (`@decocms/blocks/image`) instead of v7's module-wide
7
+ * `registerImageCdnDomain` / `registerImageQuality`: wrap the app in
8
+ * `<ImageUrlProvider value={imageUrl}>` with the site's own `createImageUrl`.
9
+ *
10
+ * This package knows no commerce platform. v7's components resized VTEX
11
+ * catalog and Shopify images on those platforms' hosts; a site that shows
12
+ * them lists the platform's helper first in its own `createImageUrl`
13
+ * (`vtexCatalog()` from `@decocms/apps-vtex/image`, `shopifyCdn()` from
14
+ * `@decocms/apps-shopify/image`), then `decoCdn({ sources: "all" })`, and
15
+ * gets v7's URLs byte for byte. Without a provider every source goes through
16
+ * the Deco image CDN (`assets.decocms.com`, the CDN's default quality):
17
+ * {@link DECO_IMAGE_URL}.
18
+ *
19
+ * Difference from v7, on purpose: no "Missing height" warning on every render.
20
+ */
21
+ import {
22
+ createImageUrl,
23
+ decoCdn,
24
+ type Fit,
25
+ type ImageUrl,
26
+ srcSet as srcSetOf,
27
+ } from "@decocms/blocks/image";
28
+ import {
29
+ type ComponentPropsWithoutRef,
30
+ type Context,
31
+ createContext,
32
+ forwardRef,
33
+ type ImgHTMLAttributes,
34
+ type ReactNode,
35
+ useContext,
36
+ useMemo,
37
+ } from "react";
38
+
39
+ /**
40
+ * The URLs without an `ImageUrlProvider`: every source through the Deco image
41
+ * CDN, as v7 sent every source that wasn't a VTEX catalog or Shopify image.
42
+ */
43
+ export const DECO_IMAGE_URL: ImageUrl = createImageUrl({
44
+ providers: [decoCdn({ sources: "all" })],
45
+ });
46
+
47
+ interface Contexts {
48
+ imageUrl: Context<ImageUrl>;
49
+ preload: Context<{ preload: boolean }>;
50
+ }
51
+
52
+ // One pair of contexts per process even if a bundler duplicates this module,
53
+ // so a provider always reaches its components.
54
+ const KEY = Symbol.for("decocms.tanstack.imageContexts");
55
+ const holder = globalThis as unknown as Record<symbol, Contexts | undefined>;
56
+ const contexts: Contexts = holder[KEY] ?? {
57
+ imageUrl: createContext<ImageUrl>(DECO_IMAGE_URL),
58
+ preload: createContext({ preload: false }),
59
+ };
60
+ holder[KEY] = contexts;
61
+
62
+ /** The site's image URLs for every `Image`, `Picture` and `Source` below it. */
63
+ export function ImageUrlProvider({ value, children }: { value: ImageUrl; children?: ReactNode }) {
64
+ return <contexts.imageUrl.Provider value={value}>{children}</contexts.imageUrl.Provider>;
65
+ }
66
+
67
+ /** The `ImageUrl` the nearest `ImageUrlProvider` gives ({@link DECO_IMAGE_URL} without one). */
68
+ export function useImageUrl(): ImageUrl {
69
+ return useContext(contexts.imageUrl);
70
+ }
71
+
72
+ const DEFAULT_SIZES = "(max-width: 768px) 100vw, 50vw";
73
+
74
+ export interface ImageProps
75
+ extends Omit<ImgHTMLAttributes<HTMLImageElement>, "src" | "width" | "height"> {
76
+ src: string;
77
+ /** @description Improves Web Vitals (CLS/LCP) */
78
+ width: number;
79
+ /** @description Improves Web Vitals (CLS/LCP) */
80
+ height?: number;
81
+ /** @description Object-fit */
82
+ fit?: Fit;
83
+ /**
84
+ * @description Web Vitals (LCP). Injects a `<link rel="preload">` tag
85
+ * alongside the `<img>`, sets `fetchPriority="high"` and `loading="eager"`.
86
+ * Use once per page for the LCP image.
87
+ */
88
+ preload?: boolean;
89
+ /** @description Media query for responsive preloading (e.g. "(min-width: 768px)") */
90
+ media?: string;
91
+ }
92
+
93
+ export const Image = forwardRef<HTMLImageElement, ImageProps>(function Image(
94
+ {
95
+ src,
96
+ width,
97
+ height,
98
+ fit = "cover",
99
+ preload,
100
+ media,
101
+ loading,
102
+ decoding,
103
+ srcSet: srcSetProp,
104
+ sizes,
105
+ fetchPriority,
106
+ ...rest
107
+ },
108
+ ref,
109
+ ) {
110
+ const url = useImageUrl();
111
+ const optimizedSrc = url(src, { width, height, fit });
112
+ const srcSet = srcSetProp ?? srcSetOf(url, src, { width, height, fit });
113
+ const resolvedSizes = srcSet ? (sizes ?? DEFAULT_SIZES) : undefined;
114
+
115
+ return (
116
+ <>
117
+ {preload && (
118
+ <link
119
+ as="image"
120
+ rel="preload"
121
+ href={optimizedSrc}
122
+ imageSrcSet={srcSet}
123
+ imageSizes={resolvedSizes}
124
+ fetchPriority={fetchPriority ?? "high"}
125
+ media={media}
126
+ />
127
+ )}
128
+ {/* biome-ignore lint/a11y/useAltText: alt comes from the caller's props, as in v7 */}
129
+ <img
130
+ {...rest}
131
+ src={optimizedSrc}
132
+ srcSet={srcSet}
133
+ sizes={resolvedSizes}
134
+ width={width}
135
+ height={height}
136
+ loading={loading ?? (preload ? "eager" : "lazy")}
137
+ decoding={decoding ?? "async"}
138
+ fetchPriority={preload ? "high" : fetchPriority}
139
+ ref={ref}
140
+ />
141
+ </>
142
+ );
143
+ });
144
+
145
+ export type SourceProps = Omit<ComponentPropsWithoutRef<"source">, "width" | "height"> & {
146
+ src: string;
147
+ /** @description Improves Web Vitals (CLS|LCP) */
148
+ width: number;
149
+ /** @description Improves Web Vitals (CLS|LCP) */
150
+ height?: number;
151
+ /** @description Improves Web Vitals (LCP). Use high for LCP image. */
152
+ fetchPriority?: "high" | "low" | "auto";
153
+ /** @description Object-fit */
154
+ fit?: Fit;
155
+ };
156
+
157
+ /** A `<source>` with its srcset built for it; inside `<Picture preload>`, it also preloads for its media query. */
158
+ export const Source = forwardRef<HTMLSourceElement, SourceProps>(function Source(
159
+ { src, width, height, fetchPriority, fit = "cover", ...rest },
160
+ ref,
161
+ ) {
162
+ const { preload } = useContext(contexts.preload);
163
+ const url = useImageUrl();
164
+ const optimizedSrc = url(src, { width, height, fit });
165
+ const srcSet = rest.srcSet ?? srcSetOf(url, src, { width, height, fit });
166
+
167
+ return (
168
+ <>
169
+ {preload && (
170
+ <link
171
+ as="image"
172
+ rel="preload"
173
+ href={optimizedSrc}
174
+ imageSrcSet={srcSet}
175
+ fetchPriority={fetchPriority ?? "high"}
176
+ media={rest.media}
177
+ />
178
+ )}
179
+ <source {...rest} srcSet={srcSet ?? optimizedSrc} width={width} height={height} ref={ref} />
180
+ </>
181
+ );
182
+ });
183
+
184
+ export type PictureProps = ComponentPropsWithoutRef<"picture"> & {
185
+ children: ReactNode;
186
+ /** @description When true, child `<Source>` elements inject `<link rel="preload">` tags for their media queries. */
187
+ preload?: boolean;
188
+ };
189
+
190
+ /**
191
+ * Art direction: `<Source>`s per media query and an `<Image>` fallback.
192
+ *
193
+ * ```tsx
194
+ * <Picture preload={isLcp}>
195
+ * <Source media="(max-width: 767px)" src={mobile} width={320} height={280} />
196
+ * <Source media="(min-width: 768px)" src={desktop} width={1280} height={280} />
197
+ * <Image src={desktop} width={1280} height={280} />
198
+ * </Picture>
199
+ * ```
200
+ */
201
+ export const Picture = forwardRef<HTMLPictureElement, PictureProps>(function Picture(
202
+ { children, preload = false, ...props },
203
+ ref,
204
+ ) {
205
+ const value = useMemo(() => ({ preload }), [preload]);
206
+ return (
207
+ <contexts.preload.Provider value={value}>
208
+ <picture {...props} ref={ref}>
209
+ {children}
210
+ </picture>
211
+ </contexts.preload.Provider>
212
+ );
213
+ });
@@ -0,0 +1,24 @@
1
+ /**
2
+ * `@decocms/tanstack/react`: the root document and its pieces, and the image
3
+ * components. Safe in the browser bundle.
4
+ */
5
+ export {
6
+ DecoDocument,
7
+ type DecoDocumentProps,
8
+ DecoPreview,
9
+ type DecoPreviewProps,
10
+ NavigationProgress,
11
+ type NavigationProgressProps,
12
+ StableOutlet,
13
+ } from "./DecoDocument.tsx";
14
+ export {
15
+ DECO_IMAGE_URL,
16
+ Image,
17
+ type ImageProps,
18
+ ImageUrlProvider,
19
+ Picture,
20
+ type PictureProps,
21
+ Source,
22
+ type SourceProps,
23
+ useImageUrl,
24
+ } from "./Image.tsx";
@@ -0,0 +1,35 @@
1
+ /**
2
+ * What the worker handed this request's render (the CDN segment token and the
3
+ * draft), and the inline script that publishes it to the browser.
4
+ */
5
+ import { currentScope } from "@decocms/tanstack/scope";
6
+ import { CSEG_GLOBAL } from "../shared.ts";
7
+
8
+ export const DRAFT_GLOBAL = "__DECO_DRAFT";
9
+
10
+ export interface PageValues {
11
+ cseg?: string;
12
+ draft?: string;
13
+ }
14
+
15
+ /** On the server, the request scope; in the browser, what the server published on `window`. */
16
+ export function pageValues(): PageValues {
17
+ if (typeof window !== "undefined") {
18
+ const w = window as unknown as Record<string, unknown>;
19
+ const pick = (k: string) =>
20
+ typeof w[k] === "string" && w[k] !== "" ? (w[k] as string) : undefined;
21
+ return { cseg: pick(CSEG_GLOBAL), draft: pick(DRAFT_GLOBAL) };
22
+ }
23
+ const scope = currentScope();
24
+ return { cseg: scope?.csegToken, draft: scope?.draft };
25
+ }
26
+
27
+ /** The script that publishes `pageValues()`; the same markup on the server and in the browser. */
28
+ export function publishScript(values: PageValues): string | null {
29
+ const parts: string[] = [];
30
+ // JSON.stringify keeps the values inert; `<` is escaped so they can't close the script.
31
+ const literal = (v: string) => JSON.stringify(v).replace(/</g, "\\u003c");
32
+ if (values.cseg) parts.push(`window.${CSEG_GLOBAL}=${literal(values.cseg)}`);
33
+ if (values.draft) parts.push(`window.${DRAFT_GLOBAL}=${literal(values.draft)}`);
34
+ return parts.length ? parts.join(";") : null;
35
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The inline scripts every Deco page runs, as v7's root layout ran them
3
+ * (`@decocms/tanstack` 7.x `DecoRootLayout`, `@decocms/blocks` 7.x
4
+ * `sdk/analytics.ts`).
5
+ */
6
+
7
+ /** The `DECO.events` bus. Events dispatched before a subscriber exists are replayed to it. */
8
+ export function eventsBootstrap(account: string): string {
9
+ return `
10
+ window.__RUNTIME__ = window.__RUNTIME__ || { account: ${JSON.stringify(account)} };
11
+ window.DECO = window.DECO || {};
12
+ window.DECO.events = window.DECO.events || {
13
+ _q: [],
14
+ _subs: [],
15
+ dispatch: function(e) {
16
+ this._q.push(e);
17
+ for (var i = 0; i < this._subs.length; i++) {
18
+ try { this._subs[i](e); } catch(err) { console.error('[DECO.events]', err); }
19
+ }
20
+ },
21
+ subscribe: function(fn) {
22
+ this._subs.push(fn);
23
+ for (var i = 0; i < this._q.length; i++) {
24
+ try { fn(this._q[i]); } catch(err) {}
25
+ }
26
+ }
27
+ };
28
+ window.dataLayer = window.dataLayer || [];
29
+ `;
30
+ }
31
+
32
+ /**
33
+ * Dispatches the events elements declare with `data-event`, on view or click.
34
+ * It waits for a Speculation Rules prerender to activate before observing.
35
+ */
36
+ export const DATA_EVENT_OBSERVER = `
37
+ (function() {
38
+ function start() {
39
+ function dispatch(event) {
40
+ if (window.dataLayer) {
41
+ window.dataLayer.push({ event: event.name, ...event.params });
42
+ }
43
+ if (window.DECO && window.DECO.events) {
44
+ window.DECO.events.dispatch(event);
45
+ }
46
+ }
47
+
48
+ function getEvent(el) {
49
+ var raw = el.getAttribute("data-event");
50
+ if (!raw) return null;
51
+ try { return JSON.parse(decodeURIComponent(raw)); } catch(e) { return null; }
52
+ }
53
+
54
+ var viewObserver = new IntersectionObserver(function(entries) {
55
+ entries.forEach(function(entry) {
56
+ if (entry.isIntersecting) {
57
+ var event = getEvent(entry.target);
58
+ if (event) dispatch(event);
59
+ viewObserver.unobserve(entry.target);
60
+ }
61
+ });
62
+ }, { threshold: 0.5 });
63
+
64
+ document.addEventListener("click", function(e) {
65
+ var el = e.target.closest("[data-event-trigger='click']");
66
+ if (el) {
67
+ var event = getEvent(el);
68
+ if (event) dispatch(event);
69
+ }
70
+ });
71
+
72
+ function observeAll() {
73
+ document.querySelectorAll("[data-event-trigger='view']").forEach(function(el) {
74
+ viewObserver.observe(el);
75
+ });
76
+ }
77
+
78
+ observeAll();
79
+ var mo = new MutationObserver(observeAll);
80
+ if (typeof requestIdleCallback !== 'undefined') {
81
+ requestIdleCallback(function() { mo.observe(document.body, { childList: true, subtree: true }); });
82
+ } else {
83
+ setTimeout(function() { mo.observe(document.body, { childList: true, subtree: true }); }, 0);
84
+ }
85
+ }
86
+
87
+ if (document.prerendering) {
88
+ document.addEventListener('prerenderingchange', start, { once: true });
89
+ } else {
90
+ start();
91
+ }
92
+ })();
93
+ `;
94
+
95
+ export const PROGRESS_CSS = `
96
+ @keyframes progressSlide { from { transform: translateX(-100%); } to { transform: translateX(100%); } }
97
+ .nav-progress-bar { animation: progressSlide 1s ease-in-out infinite; }
98
+ `;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The router factory every Deco TanStack site uses (isomorphic).
3
+ *
4
+ * Search params use plain `URLSearchParams`, not TanStack's JSON format, so
5
+ * commerce URLs such as `?filter.size=M&filter.size=L` round-trip unchanged.
6
+ */
7
+ import {
8
+ type AnyRoute,
9
+ createRouter,
10
+ type SearchParser,
11
+ type SearchSerializer,
12
+ type TrailingSlashOption,
13
+ } from "@tanstack/react-router";
14
+ import type { JSX } from "react";
15
+
16
+ export { PAGE_STATUS_HEADER } from "../shared.ts";
17
+
18
+ export const decoParseSearch: SearchParser = (searchStr) => {
19
+ const str = searchStr.startsWith("?") ? searchStr.slice(1) : searchStr;
20
+ if (!str) return {};
21
+ const params = new URLSearchParams(str);
22
+ const result: Record<string, string | string[]> = {};
23
+ for (const key of new Set(params.keys())) {
24
+ const values = params.getAll(key);
25
+ result[key] = values.length === 1 ? (values[0] as string) : values;
26
+ }
27
+ return result;
28
+ };
29
+
30
+ /**
31
+ * The inverse of {@link decoParseSearch}, and a fixed point of it: on the
32
+ * server, TanStack Router compares the request's URL with
33
+ * `stringifySearch(parseSearch(...))` and redirects (307) when they differ, so
34
+ * an empty value (`?q=`, `?sort=`) must be kept, as v7 #646 fixed.
35
+ * `undefined` and `null` still remove a param (`navigate({ search: { q: undefined } })`).
36
+ */
37
+ export const decoStringifySearch: SearchSerializer = (search) => {
38
+ const params = new URLSearchParams();
39
+ for (const [key, value] of Object.entries(search)) {
40
+ if (value === undefined || value === null) continue;
41
+ if (Array.isArray(value)) for (const v of value) params.append(key, String(v));
42
+ else params.append(key, String(value));
43
+ }
44
+ const str = params.toString();
45
+ return str ? `?${str}` : "";
46
+ };
47
+
48
+ export interface DecoRouterOptions<TRouteTree extends AnyRoute> {
49
+ routeTree: TRouteTree;
50
+ /** Router context for every route (e.g. `{ queryClient }`). */
51
+ context?: Record<string, unknown>;
52
+ /** A provider around the whole app (non-DOM only, e.g. `QueryClientProvider`). */
53
+ Wrap?: (props: { children: any }) => JSX.Element;
54
+ /** The CSP nonce TanStack stamps on its own scripts, when the site enforces one. */
55
+ nonce?: string;
56
+ /** Default `"intent"`. */
57
+ defaultPreload?: "intent" | "viewport" | "render" | false;
58
+ trailingSlash?: TrailingSlashOption;
59
+ }
60
+
61
+ /**
62
+ * `createRouter` with Deco's defaults: `URLSearchParams` search params that
63
+ * keep empty values, scroll restoration, preload on intent.
64
+ */
65
+ export function createDecoRouter<TRouteTree extends AnyRoute>(
66
+ options: DecoRouterOptions<TRouteTree>,
67
+ ) {
68
+ const { routeTree, context, Wrap, nonce, defaultPreload = "intent", trailingSlash } = options;
69
+ return createRouter({
70
+ routeTree,
71
+ context: context as any,
72
+ Wrap,
73
+ scrollRestoration: true,
74
+ defaultPreload,
75
+ trailingSlash,
76
+ parseSearch: decoParseSearch,
77
+ stringifySearch: decoStringifySearch,
78
+ ...(nonce ? { ssr: { nonce } } : {}),
79
+ });
80
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The browser's copy of `./server.ts`: the same shape, and no request scope
3
+ * (nothing renders inside a worker request there), so no `node:async_hooks`
4
+ * in the client bundle.
5
+ */
6
+ import type { RequestScope } from "./server.ts";
7
+
8
+ export type { RequestScope };
9
+
10
+ export function runInScope<T>(_scope: RequestScope, fn: () => T): T {
11
+ return fn();
12
+ }
13
+
14
+ export function currentScope(): RequestScope | undefined {
15
+ return undefined;
16
+ }
17
+
18
+ export const SCOPE_IMPLEMENTATION = "browser-stub" as "async-local-storage" | "browser-stub";
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Values `createDecoWorker` hands to the render of the request it is serving
3
+ * (the `__cseg` token and the draft `DecoDocument` publishes), through
4
+ * `AsyncLocalStorage`. The browser build resolves `./browser.ts` instead (the
5
+ * package's `./scope` export is conditional: `workerd` and `node` come before
6
+ * `browser`, because a Workers build turns `browser` on too).
7
+ *
8
+ * One storage per process even if a bundler duplicates this module: it lives
9
+ * on `globalThis` under a registered symbol.
10
+ */
11
+ import { AsyncLocalStorage } from "node:async_hooks";
12
+
13
+ export interface RequestScope {
14
+ /** The CDN segment token for this request's page, or undefined when it may not be cached. */
15
+ csegToken?: string;
16
+ /** The draft this request renders (after the worker's host check). */
17
+ draft?: string;
18
+ }
19
+
20
+ const KEY = Symbol.for("decocms.tanstack.requestScope");
21
+ const holder = globalThis as unknown as Record<symbol, AsyncLocalStorage<RequestScope> | undefined>;
22
+ const storage: AsyncLocalStorage<RequestScope> =
23
+ holder[KEY] ?? new AsyncLocalStorage<RequestScope>();
24
+ holder[KEY] = storage;
25
+
26
+ /** Runs `fn` with `scope` as the request's scope. */
27
+ export function runInScope<T>(scope: RequestScope, fn: () => T): T {
28
+ return storage.run(scope, fn);
29
+ }
30
+
31
+ /** The scope of the request being served, or undefined outside one (and in the browser). */
32
+ export function currentScope(): RequestScope | undefined {
33
+ return storage.getStore();
34
+ }
35
+
36
+ /** Which implementation this is: the conditional-export test asserts it. */
37
+ export const SCOPE_IMPLEMENTATION = "async-local-storage" as "async-local-storage" | "browser-stub";
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Server-only helpers for a site's server functions and page loader. Never
3
+ * import this from a component that ships to the browser.
4
+ *
5
+ * The draft a request renders is decided once, by `createDecoWorker` (its host
6
+ * allowlist), and handed to the app in the `x-deco-draft` request header; the
7
+ * worker removes any copy that arrives from outside. These read that header.
8
+ */
9
+ import type { Client, CMS } from "@decocms/blocks";
10
+ import { getRequest, setResponseHeader } from "@tanstack/react-start/server";
11
+ import { DRAFT_HEADER } from "../draft.ts";
12
+
13
+ /** The draft `request` renders (checked by the worker), or `null` for the release. */
14
+ export function requestDraft(request: Request = getRequest()): string | null {
15
+ return request.headers.get(DRAFT_HEADER) || null;
16
+ }
17
+
18
+ /**
19
+ * The content client for a request: its draft's, or the release's. Without
20
+ * `request`, the request being served (`getRequest()`).
21
+ */
22
+ export function contentClient(cms: CMS, request: Request = getRequest()): Client {
23
+ const pointer = requestDraft(request);
24
+ return pointer ? cms.forDraft(pointer) : cms.forRelease();
25
+ }
26
+
27
+ /** True when the browser called a server function over HTTP; false while a document renders. */
28
+ export function isServerFnCall(request: Request = getRequest()): boolean {
29
+ return new URL(request.url).pathname.startsWith("/_serverFn/");
30
+ }
31
+
32
+ /**
33
+ * Marks a server function's response as per-visitor (`Cache-Control: private,
34
+ * no-store`): the worker never stores it and the CDN never keeps it. Only when
35
+ * the browser called the function over HTTP; while a document renders the
36
+ * function is a plain call and the header would land on the page.
37
+ */
38
+ export function markPrivate(): void {
39
+ if (!isServerFnCall()) return;
40
+ setResponseHeader("Cache-Control", "private, no-store");
41
+ }
42
+
43
+ export { DEGRADED_HEADER, PAGE_STATUS_HEADER } from "../shared.ts";
package/src/shared.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Names the worker, the router and the browser code share. No imports, no
3
+ * state: safe in every bundle.
4
+ */
5
+
6
+ /**
7
+ * The query parameter `decoServerFnFetch` adds to a server-function URL: the
8
+ * page's CDN segment token, which the worker checks before it lets the CDN
9
+ * cache the response. `__d` is avoided: v7 used it as a debug flag.
10
+ */
11
+ export const CSEG_PARAM = "__cseg";
12
+
13
+ /** The `window` property the page publishes the token on. */
14
+ export const CSEG_GLOBAL = "__DECO_CSEG";
15
+
16
+ /**
17
+ * The response header a route sets to give the document another status (a CMS
18
+ * page that renders the site's 404 page): the worker turns it into the
19
+ * response's status and removes it. A route's `headers` reach the document
20
+ * response, a status set while rendering does not.
21
+ */
22
+ export const PAGE_STATUS_HEADER = "x-page-status";
23
+
24
+ /**
25
+ * The response header a page sets when a loader it depends on failed: the
26
+ * worker never stores that response, and serves a stale copy instead when it
27
+ * has one.
28
+ */
29
+ export const DEGRADED_HEADER = "x-deco-degraded";
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Safe in the browser bundle: the `serverFns.fetch` hook for `createStart`.
3
+ *
4
+ * ```ts
5
+ * // src/start.ts
6
+ * export const startInstance = createStart(() => ({ serverFns: { fetch: decoServerFnFetch } }));
7
+ * ```
8
+ */
9
+ import { CSEG_GLOBAL, CSEG_PARAM } from "../shared.ts";
10
+
11
+ function publishedToken(): string | null {
12
+ if (typeof window === "undefined") return null;
13
+ const value = (window as unknown as Record<string, unknown>)[CSEG_GLOBAL];
14
+ return typeof value === "string" && value.length > 0 ? value : null;
15
+ }
16
+
17
+ /**
18
+ * `fetch` for server-function calls: adds the CDN segment token the page
19
+ * published (`__cseg`), so the CDN can cache client-side navigation data. The
20
+ * token is a hint: the worker recomputes it from the request and keeps
21
+ * `CDN-Cache-Control: no-store` unless they match. With no token on the page,
22
+ * a plain `fetch`.
23
+ */
24
+ export const decoServerFnFetch: typeof fetch = (input, init) => {
25
+ // TanStack's server-function fetcher passes the URL as a string; anything else goes through as is.
26
+ if (typeof input !== "string") return fetch(input, init);
27
+ const token = publishedToken();
28
+ if (!token) return fetch(input, init);
29
+ const sep = input.includes("?") ? "&" : "?";
30
+ return fetch(`${input}${sep}${CSEG_PARAM}=${encodeURIComponent(token)}`, init);
31
+ };
package/src/studio.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Where Deco Studio runs: the origins its site editor frames a site from and
3
+ * talks to it from (`postMessage`). One list, so the worker's
4
+ * `frame-ancestors` and the Studio bridge `DecoDocument` mounts never drift
5
+ * apart.
6
+ *
7
+ * No module state and no framework code: safe in a browser bundle.
8
+ */
9
+
10
+ /**
11
+ * Studio's origins, in the CSP source form (`https://*.decocms.com` matches
12
+ * any subdomain). Test an origin with {@link isStudioOrigin}: the list holds a
13
+ * wildcard, so `includes()` isn't the check.
14
+ */
15
+ export const STUDIO_ORIGINS: readonly string[] = Object.freeze([
16
+ "https://studio.decocms.com",
17
+ "https://studio-stg.decocms.com",
18
+ "https://decocms.com",
19
+ "https://*.decocms.com",
20
+ ]);
21
+
22
+ /**
23
+ * The `frame-ancestors` sources a site sends so Studio can show it in the
24
+ * site editor: the site itself, {@link STUDIO_ORIGINS}, and v7's
25
+ * `https://*.deco.studio`. A binding adds the loopback origins in local
26
+ * development (`http://localhost:*`), where a Studio runs on the same machine.
27
+ */
28
+ export const STUDIO_FRAME_ANCESTORS: readonly string[] = Object.freeze([
29
+ "'self'",
30
+ ...STUDIO_ORIGINS,
31
+ "https://*.deco.studio",
32
+ ]);
33
+
34
+ /**
35
+ * Whether `origin` (a `MessageEvent.origin`, an `Origin` header) is one of
36
+ * {@link STUDIO_ORIGINS}: `https`, the default port, and `decocms.com` or a
37
+ * name under it.
38
+ */
39
+ export function isStudioOrigin(origin: string | null | undefined): boolean {
40
+ if (typeof origin !== "string" || origin === "") return false;
41
+ let url: URL;
42
+ try {
43
+ url = new URL(origin);
44
+ } catch {
45
+ return false;
46
+ }
47
+ // An origin is the scheme and host alone: `https://decocms.com/x` or one with
48
+ // credentials isn't one.
49
+ if (url.origin !== origin || url.protocol !== "https:" || url.port !== "") return false;
50
+ const host = url.hostname;
51
+ return host === "decocms.com" || host.endsWith(".decocms.com");
52
+ }