@decocms/blocks 8.1.0-next.0 → 8.1.0-next.1
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/package.json +6 -92
- package/src/index.ts +2 -12
- package/src/protocol/storage/memory.ts +1 -1
- package/src/v8/background.ts +3 -3
- package/src/v8/builtins/legacy.ts +1 -1
- package/src/v8/cli/index.ts +1 -1
- package/src/v8/fetch.ts +8 -27
- package/src/v8/remoteLoader.ts +1 -1
- package/src/v8/telemetry.ts +1 -1
- package/src/cms/applySectionConventions.ts +0 -148
- package/src/cms/blockSource.ts +0 -228
- package/src/cms/client.ts +0 -85
- package/src/cms/deferredTrigger.ts +0 -58
- package/src/cms/draftSource.ts +0 -476
- package/src/cms/index.ts +0 -180
- package/src/cms/loadDecofileDirectory.ts +0 -89
- package/src/cms/loader.ts +0 -563
- package/src/cms/registry.ts +0 -264
- package/src/cms/renderJson.ts +0 -179
- package/src/cms/resolve.ts +0 -2583
- package/src/cms/schema.ts +0 -1219
- package/src/cms/sectionLoaderContext.ts +0 -113
- package/src/cms/sectionLoaders.ts +0 -686
- package/src/cms/sectionMixins.ts +0 -153
- package/src/flags/audience.ts +0 -56
- package/src/flags/everyone.ts +0 -29
- package/src/flags/flag.ts +0 -15
- package/src/flags/multivariate/image.ts +0 -11
- package/src/flags/multivariate/message.ts +0 -11
- package/src/flags/multivariate/page.ts +0 -16
- package/src/flags/multivariate/section.ts +0 -16
- package/src/flags/multivariate.ts +0 -1
- package/src/flags/types.ts +0 -59
- package/src/flags/utils/multivariate.ts +0 -20
- package/src/hooks/Image.tsx +0 -314
- package/src/hooks/JsonLd.tsx +0 -353
- package/src/hooks/LazySection.tsx +0 -121
- package/src/hooks/LiveControls.tsx +0 -144
- package/src/hooks/Picture.tsx +0 -127
- package/src/hooks/RenderSection.tsx +0 -91
- package/src/hooks/SectionErrorFallback.tsx +0 -97
- package/src/hooks/Stats.tsx +0 -134
- package/src/hooks/index.ts +0 -35
- package/src/hooks/useLoadMore.ts +0 -100
- package/src/matchers/builtins.ts +0 -459
- package/src/matchers/countryNames.ts +0 -104
- package/src/matchers/override.ts +0 -136
- package/src/matchers/posthog.ts +0 -154
- package/src/middleware/decoState.ts +0 -55
- package/src/middleware/healthMetrics.ts +0 -133
- package/src/middleware/hydrationContext.ts +0 -79
- package/src/middleware/index.ts +0 -88
- package/src/middleware/liveness.ts +0 -21
- package/src/middleware/observability.ts +0 -800
- package/src/middleware/validateSection.ts +0 -100
- package/src/preview/DraftPreviewBadge.tsx +0 -306
- package/src/preview/decoMark.ts +0 -11
- package/src/preview/index.ts +0 -8
- package/src/sdk/abTesting.ts +0 -556
- package/src/sdk/analytics.ts +0 -147
- package/src/sdk/cacheHeaders.ts +0 -633
- package/src/sdk/cacheStorage.ts +0 -287
- package/src/sdk/cachedLoader.ts +0 -556
- package/src/sdk/clx.ts +0 -5
- package/src/sdk/cn.ts +0 -28
- package/src/sdk/composite.ts +0 -114
- package/src/sdk/cookie.ts +0 -129
- package/src/sdk/crypto.ts +0 -199
- package/src/sdk/csp.ts +0 -59
- package/src/sdk/deepOmit.ts +0 -52
- package/src/sdk/detectDevice.ts +0 -45
- package/src/sdk/djb2.ts +0 -20
- package/src/sdk/encoding.ts +0 -44
- package/src/sdk/env.ts +0 -54
- package/src/sdk/experiments.ts +0 -314
- package/src/sdk/fetchCache.ts +0 -269
- package/src/sdk/fetchTimeout.ts +0 -58
- package/src/sdk/flags.ts +0 -138
- package/src/sdk/http.ts +0 -124
- package/src/sdk/index.ts +0 -97
- package/src/sdk/inflightTimeout.ts +0 -53
- package/src/sdk/instrumentedFetch.ts +0 -362
- package/src/sdk/invoke.ts +0 -298
- package/src/sdk/logger.ts +0 -304
- package/src/sdk/mergeCacheControl.ts +0 -150
- package/src/sdk/nonce.ts +0 -46
- package/src/sdk/normalizeUrls.ts +0 -91
- package/src/sdk/observability.ts +0 -116
- package/src/sdk/otel.ts +0 -1118
- package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
- package/src/sdk/otelAdapters.ts +0 -144
- package/src/sdk/otelHttpLog.ts +0 -419
- package/src/sdk/otelHttpMeter.ts +0 -532
- package/src/sdk/otelHttpTracer.ts +0 -543
- package/src/sdk/redirects.ts +0 -336
- package/src/sdk/requestContext.ts +0 -281
- package/src/sdk/requestContextStorage.browser.ts +0 -43
- package/src/sdk/requestContextStorage.ts +0 -35
- package/src/sdk/responseCache.ts +0 -82
- package/src/sdk/retry.ts +0 -45
- package/src/sdk/serverTimings.ts +0 -68
- package/src/sdk/signal.ts +0 -42
- package/src/sdk/sitemap.ts +0 -160
- package/src/sdk/urlRedaction.ts +0 -82
- package/src/sdk/urlUtils.ts +0 -183
- package/src/sdk/useDevice.ts +0 -89
- package/src/sdk/useDeviceContext.tsx +0 -108
- package/src/sdk/useId.ts +0 -7
- package/src/sdk/useScript.ts +0 -210
- package/src/sdk/useSuggestions.ts +0 -188
- package/src/sdk/wrapCaughtErrors.ts +0 -107
- package/src/setup.ts +0 -120
- package/src/types/index.ts +0 -53
- package/src/types/widgets.ts +0 -14
package/src/sdk/useDevice.ts
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Server-side device detection via RequestContext.
|
|
3
|
-
*
|
|
4
|
-
* @example
|
|
5
|
-
* ```tsx
|
|
6
|
-
* // In a section loader or server function:
|
|
7
|
-
* import { detectDevice } from "@decocms/start/sdk/useDevice";
|
|
8
|
-
*
|
|
9
|
-
* export function loader(props: Props, req: Request) {
|
|
10
|
-
* const device = detectDevice(req.headers.get("user-agent") ?? "");
|
|
11
|
-
* return { ...props, device };
|
|
12
|
-
* }
|
|
13
|
-
*
|
|
14
|
-
* // Or via RequestContext (no request argument needed):
|
|
15
|
-
* import { useDevice } from "@decocms/start/sdk/useDevice";
|
|
16
|
-
*
|
|
17
|
-
* export function loader(props: Props) {
|
|
18
|
-
* const device = useDevice();
|
|
19
|
-
* return { ...props, isMobile: device === "mobile" };
|
|
20
|
-
* }
|
|
21
|
-
* ```
|
|
22
|
-
*/
|
|
23
|
-
|
|
24
|
-
import { detectDevice } from "./detectDevice";
|
|
25
|
-
import { RequestContext } from "./requestContext";
|
|
26
|
-
|
|
27
|
-
// The pure UA-parsing half (`Device`, `MOBILE_RE`, `TABLET_RE`,
|
|
28
|
-
// `isMobileUA`, `detectDevice`) lives in `./detectDevice` — a leaf with no
|
|
29
|
-
// React and no RequestContext — and is re-exported below for backward
|
|
30
|
-
// compatibility. Modules that can land in a Next.js route-handler graph
|
|
31
|
-
// (`cms/sectionMixins.ts`, `sdk/requestContext.ts`) MUST import that leaf
|
|
32
|
-
// directly, not this file: this file also re-exports the `"use client"`
|
|
33
|
-
// context half, which crashes route handlers (see ./detectDevice's doc
|
|
34
|
-
// comment for the vendored-RSC-React mechanics).
|
|
35
|
-
export { type Device, detectDevice, isMobileUA, MOBILE_RE, TABLET_RE } from "./detectDevice";
|
|
36
|
-
|
|
37
|
-
// `DeviceContext`, the `useDevice()` hook, and `DeviceProvider` live in
|
|
38
|
-
// `./useDeviceContext` (a `"use client"` file) and are re-exported below for
|
|
39
|
-
// full backward compatibility with this module's public API — see that
|
|
40
|
-
// file's doc comment for why the split exists.
|
|
41
|
-
export { DeviceContext, useDevice, DeviceProvider } from "./useDeviceContext";
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Resolve the current device from the ambient runtime (RequestContext on the
|
|
45
|
-
* server, `navigator.userAgent` on the client) — no React hooks involved.
|
|
46
|
-
* Used both by the plain `check*()` helpers below and by `useDevice()`/
|
|
47
|
-
* `DeviceProvider` in `./useDeviceContext`.
|
|
48
|
-
*/
|
|
49
|
-
export function resolveDeviceFromRuntime(): ReturnType<typeof detectDevice> {
|
|
50
|
-
// Server: use RequestContext UA header
|
|
51
|
-
if (typeof document === "undefined") {
|
|
52
|
-
const ctx = RequestContext.current;
|
|
53
|
-
if (!ctx) return "desktop";
|
|
54
|
-
const ua = ctx.request.headers.get("user-agent") ?? "";
|
|
55
|
-
return detectDevice(ua);
|
|
56
|
-
}
|
|
57
|
-
// Client: use navigator.userAgent for consistency with server-side UA detection.
|
|
58
|
-
// Using viewport width would produce different results between SSR and
|
|
59
|
-
// hydration (server sees UA, client sees pixels), causing hydration mismatch.
|
|
60
|
-
const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
|
|
61
|
-
return detectDevice(ua);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Check if the current request is from a mobile device.
|
|
66
|
-
*/
|
|
67
|
-
export function checkMobile(): boolean {
|
|
68
|
-
const ctx = RequestContext.current;
|
|
69
|
-
if (!ctx) return false;
|
|
70
|
-
return detectDevice(ctx.request.headers.get("user-agent") ?? "") === "mobile";
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Check if the current request is from a tablet device.
|
|
75
|
-
*/
|
|
76
|
-
export function checkTablet(): boolean {
|
|
77
|
-
const ctx = RequestContext.current;
|
|
78
|
-
if (!ctx) return false;
|
|
79
|
-
return detectDevice(ctx.request.headers.get("user-agent") ?? "") === "tablet";
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Check if the current request is from a desktop device.
|
|
84
|
-
*/
|
|
85
|
-
export function checkDesktop(): boolean {
|
|
86
|
-
const ctx = RequestContext.current;
|
|
87
|
-
if (!ctx) return true;
|
|
88
|
-
return detectDevice(ctx.request.headers.get("user-agent") ?? "") === "desktop";
|
|
89
|
-
}
|
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* The hook/context half of device detection — split out of `useDevice.ts`
|
|
5
|
-
* because it uses `createContext`/`useContext`, which Next.js's App Router
|
|
6
|
-
* (unlike the Vite-based `@decocms/tanstack` binding, and unlike this
|
|
7
|
-
* package's own Vitest/jsdom unit tests) statically rejects unless the
|
|
8
|
-
* *file* that calls them carries a `"use client"` directive — Next's RSC
|
|
9
|
-
* webpack loader errors ("This React Hook only works in a Client
|
|
10
|
-
* Component") on ANY file reachable from a Server Component's module graph
|
|
11
|
-
* that calls a client-only hook, even if the actual call site is never
|
|
12
|
-
* invoked along that particular path.
|
|
13
|
-
*
|
|
14
|
-
* That's exactly what happened here: `packages/blocks/src/cms/sectionMixins.ts`
|
|
15
|
-
* imports only the plain, hook-free `detectDevice()` from `useDevice.ts` for
|
|
16
|
-
* its `withDevice()`/`withMobile()` section-loader mixins — a 100%
|
|
17
|
-
* server-side call path (loaders receive a `Request`, never render). But
|
|
18
|
-
* because `sectionMixins.ts` is pulled in by `cms/index.ts`, which
|
|
19
|
-
* `createSiteSetup()` (runtime/setup.ts) imports, and a site's `setup.ts` is
|
|
20
|
-
* typically imported for its side effects from `app/layout.tsx` (a Server
|
|
21
|
-
* Component under `@decocms/nextjs`), the *whole* `useDevice.ts` file used to
|
|
22
|
-
* ride along into the server compilation graph — including the
|
|
23
|
-
* `createContext`/`useContext` calls now isolated in this file, which had no
|
|
24
|
-
* "use client" directive of their own. `@decocms/nextjs`'s next-smoke fixture
|
|
25
|
-
* (this plan's Task 9) is the first consumer to hit Next's real RSC
|
|
26
|
-
* compiler, so this split was never needed before.
|
|
27
|
-
*
|
|
28
|
-
* `detectDevice`, `isMobileUA`, `checkMobile/Tablet/Desktop`, and the
|
|
29
|
-
* `Device` type stay in `useDevice.ts` (no directive, safe to import from
|
|
30
|
-
* server-only code); `useDevice.ts` re-exports `DeviceContext`/`useDevice`/
|
|
31
|
-
* `DeviceProvider` from here so the public `@decocms/blocks/sdk/useDevice`
|
|
32
|
-
* entry point (and every existing consumer, e.g.
|
|
33
|
-
* `packages/tanstack/src/hooks/DecoPageRenderer.tsx`) is unchanged.
|
|
34
|
-
*/
|
|
35
|
-
import { createContext, createElement, type ReactNode, useContext } from "react";
|
|
36
|
-
import { type Device, resolveDeviceFromRuntime } from "./useDevice";
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* React context for the resolved device. Populated by `<DeviceProvider>` at
|
|
40
|
-
* the top of the framework tree (DecoPageRenderer mounts it for sites that
|
|
41
|
-
* use the standard wiring). Once set, `useDevice()` reads from here in
|
|
42
|
-
* preference to `AsyncLocalStorage`, which is known to be unreliable across
|
|
43
|
-
* streaming SSR Suspense boundaries on Cloudflare Workers.
|
|
44
|
-
*/
|
|
45
|
-
export const DeviceContext = createContext<Device | null>(null);
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Get the current device type. Works everywhere:
|
|
49
|
-
* - Server (loader, middleware, server function): reads User-Agent from RequestContext.
|
|
50
|
-
* - Client (component, event handler): uses `window.innerWidth` breakpoints.
|
|
51
|
-
*
|
|
52
|
-
* @example
|
|
53
|
-
* ```tsx
|
|
54
|
-
* import { useDevice } from "@decocms/start/sdk/useDevice";
|
|
55
|
-
*
|
|
56
|
-
* // In a component:
|
|
57
|
-
* const device = useDevice(); // "mobile" | "tablet" | "desktop"
|
|
58
|
-
* ```
|
|
59
|
-
*/
|
|
60
|
-
export function useDevice(): Device {
|
|
61
|
-
// Prefer the value resolved by <DeviceProvider> at the framework root —
|
|
62
|
-
// safe across streaming-SSR Suspense boundaries where AsyncLocalStorage
|
|
63
|
-
// can lose the request context. The try/catch keeps backward compat with
|
|
64
|
-
// callers outside a React render (loaders, server functions, tests
|
|
65
|
-
// without the framework root), where useContext throws "Invalid hook
|
|
66
|
-
// call" — those callers fall through to the original runtime resolution.
|
|
67
|
-
//
|
|
68
|
-
// Rules-of-hooks note: `useContext` is called *unconditionally* inside the
|
|
69
|
-
// try block — exactly once per `useDevice()` invocation. The catch only
|
|
70
|
-
// fires when there is no React dispatcher at all (outside a render),
|
|
71
|
-
// never *between* hooks in the same render. Hook order within a component
|
|
72
|
-
// therefore remains consistent. Callers that conditionally call
|
|
73
|
-
// `useDevice()` itself were already violating rules of hooks; this PR
|
|
74
|
-
// doesn't change that.
|
|
75
|
-
try {
|
|
76
|
-
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
77
|
-
const fromContext = useContext(DeviceContext);
|
|
78
|
-
if (fromContext) return fromContext;
|
|
79
|
-
} catch {
|
|
80
|
-
// Not in a React render — fall through.
|
|
81
|
-
}
|
|
82
|
-
return resolveDeviceFromRuntime();
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Wraps children in a `DeviceContext` populated by resolving the device once
|
|
87
|
-
* here, at a point in the React tree where `AsyncLocalStorage` is reliable.
|
|
88
|
-
* Any descendant calling `useDevice()` reads from this context instead of
|
|
89
|
-
* re-resolving through ALS — preventing the "wrong device value cached at
|
|
90
|
-
* the edge" failure mode that produces React #418 hydration mismatches.
|
|
91
|
-
*
|
|
92
|
-
* Mount this near the top of the React tree. `DecoPageRenderer` already
|
|
93
|
-
* mounts it automatically; sites with custom roots can mount it explicitly:
|
|
94
|
-
*
|
|
95
|
-
* @example
|
|
96
|
-
* ```tsx
|
|
97
|
-
* <DeviceProvider>
|
|
98
|
-
* <App />
|
|
99
|
-
* </DeviceProvider>
|
|
100
|
-
* ```
|
|
101
|
-
*
|
|
102
|
-
* Pass an explicit `value` to override detection (useful for tests or
|
|
103
|
-
* admin preview where the runtime UA isn't meaningful).
|
|
104
|
-
*/
|
|
105
|
-
export function DeviceProvider(props: { children: ReactNode; value?: Device }): ReactNode {
|
|
106
|
-
const device = props.value ?? resolveDeviceFromRuntime();
|
|
107
|
-
return createElement(DeviceContext.Provider, { value: device }, props.children);
|
|
108
|
-
}
|
package/src/sdk/useId.ts
DELETED
package/src/sdk/useScript.ts
DELETED
|
@@ -1,210 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Serializes functions into inline script strings for SSR output.
|
|
3
|
-
*
|
|
4
|
-
* Includes lightweight minification (whitespace + comment removal)
|
|
5
|
-
* with an LRU cache to avoid re-processing the same function bodies.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
// ---------------------------------------------------------------------------
|
|
9
|
-
// LRU cache for minified function bodies
|
|
10
|
-
// ---------------------------------------------------------------------------
|
|
11
|
-
|
|
12
|
-
const MAX_CACHE_SIZE = 200;
|
|
13
|
-
const minifyCache = new Map<string, string>();
|
|
14
|
-
|
|
15
|
-
function cacheGet(key: string): string | undefined {
|
|
16
|
-
const value = minifyCache.get(key);
|
|
17
|
-
if (value !== undefined) {
|
|
18
|
-
// Move to end (most recently used)
|
|
19
|
-
minifyCache.delete(key);
|
|
20
|
-
minifyCache.set(key, value);
|
|
21
|
-
}
|
|
22
|
-
return value;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
function cacheSet(key: string, value: string) {
|
|
26
|
-
if (minifyCache.size >= MAX_CACHE_SIZE) {
|
|
27
|
-
// Delete oldest entry (first key in insertion order)
|
|
28
|
-
const oldest = minifyCache.keys().next().value;
|
|
29
|
-
if (oldest !== undefined) minifyCache.delete(oldest);
|
|
30
|
-
}
|
|
31
|
-
minifyCache.set(key, value);
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// ---------------------------------------------------------------------------
|
|
35
|
-
// Lightweight minification (no external deps)
|
|
36
|
-
// ---------------------------------------------------------------------------
|
|
37
|
-
|
|
38
|
-
function minifyJs(code: string): string {
|
|
39
|
-
return (
|
|
40
|
-
code
|
|
41
|
-
// Remove block comments only — line-comment stripping and operator-spacing
|
|
42
|
-
// collapse are unsafe: they can corrupt string literals containing "//"
|
|
43
|
-
// or operators, and regex literals whose delimiters look like operators.
|
|
44
|
-
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
45
|
-
// Collapse runs of whitespace (spaces, tabs, newlines) to a single space.
|
|
46
|
-
// This is safe because whitespace inside string/template literals is
|
|
47
|
-
// preserved as a single space, which is semantically identical.
|
|
48
|
-
.replace(/\s+/g, " ")
|
|
49
|
-
.trim()
|
|
50
|
-
);
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// ---------------------------------------------------------------------------
|
|
54
|
-
// Public API
|
|
55
|
-
// ---------------------------------------------------------------------------
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Serializes a function and its arguments into a self-executing inline script.
|
|
59
|
-
*
|
|
60
|
-
* @deprecated `fn.toString()` produces different output in SSR vs client Vite
|
|
61
|
-
* builds (React Compiler transforms differ), causing hydration mismatches on
|
|
62
|
-
* `dangerouslySetInnerHTML.__html`. Use {@link inlineScript} with a plain
|
|
63
|
-
* string constant instead.
|
|
64
|
-
*
|
|
65
|
-
* @example
|
|
66
|
-
* ```tsx
|
|
67
|
-
* // BEFORE (causes hydration mismatch):
|
|
68
|
-
* <script dangerouslySetInnerHTML={{ __html: useScript(onLoad, elementId) }} />
|
|
69
|
-
*
|
|
70
|
-
* // AFTER (safe):
|
|
71
|
-
* <script {...inlineScript(`(${MY_SCRIPT_STRING})("${elementId}")`)} />
|
|
72
|
-
* ```
|
|
73
|
-
*/
|
|
74
|
-
export function useScript<T extends (...args: any[]) => void>(
|
|
75
|
-
fn: T,
|
|
76
|
-
...args: Parameters<T>
|
|
77
|
-
): string {
|
|
78
|
-
if (typeof (globalThis as any).__DECO_USE_SCRIPT_WARNED === "undefined") {
|
|
79
|
-
(globalThis as any).__DECO_USE_SCRIPT_WARNED = new Set<string>();
|
|
80
|
-
}
|
|
81
|
-
const warnedSet = (globalThis as any).__DECO_USE_SCRIPT_WARNED as Set<string>;
|
|
82
|
-
const fnName = fn.name || "anonymous";
|
|
83
|
-
if (
|
|
84
|
-
typeof process !== "undefined" &&
|
|
85
|
-
process.env?.NODE_ENV !== "production" &&
|
|
86
|
-
!warnedSet.has(fnName)
|
|
87
|
-
) {
|
|
88
|
-
warnedSet.add(fnName);
|
|
89
|
-
console.warn(
|
|
90
|
-
`[useScript] Using fn.toString() for "${fnName}". ` +
|
|
91
|
-
`This may produce different output in SSR vs client builds, causing hydration mismatch. ` +
|
|
92
|
-
`Consider using inlineScript() with a plain string constant instead.`,
|
|
93
|
-
);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
const fnStr = fn.toString();
|
|
97
|
-
let minified = cacheGet(fnStr);
|
|
98
|
-
if (minified === undefined) {
|
|
99
|
-
minified = minifyJs(fnStr);
|
|
100
|
-
cacheSet(fnStr, minified);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
const serializedArgs = args.map((a) => JSON.stringify(a)).join(",");
|
|
104
|
-
return `(${minified})(${serializedArgs})`;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* Like useScript, but returns a data: URI suitable for `<script src="...">`.
|
|
109
|
-
*
|
|
110
|
-
* @deprecated Same hydration issues as {@link useScript}. Use {@link inlineScript} instead.
|
|
111
|
-
*/
|
|
112
|
-
export function useScriptAsDataURI<T extends (...args: any[]) => void>(
|
|
113
|
-
fn: T,
|
|
114
|
-
...args: Parameters<T>
|
|
115
|
-
): string {
|
|
116
|
-
const code = useScript(fn, ...args);
|
|
117
|
-
return `data:text/javascript;charset=utf-8,${encodeURIComponent(code)}`;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* Returns props for a `<script>` element with safe inline JavaScript.
|
|
122
|
-
* Unlike {@link useScript}, this accepts a plain string — no `fn.toString()`
|
|
123
|
-
* means no SSR/client divergence and no hydration mismatch.
|
|
124
|
-
*
|
|
125
|
-
* @example
|
|
126
|
-
* ```tsx
|
|
127
|
-
* const SCROLL_SCRIPT = `document.getElementById("btn").addEventListener("click", () => { ... })`;
|
|
128
|
-
* <script {...inlineScript(SCROLL_SCRIPT)} />
|
|
129
|
-
*
|
|
130
|
-
* // With arguments:
|
|
131
|
-
* const INIT_SCRIPT = (id: string) => `document.getElementById("${id}").dataset.ready = "true"`;
|
|
132
|
-
* <script {...inlineScript(INIT_SCRIPT("my-element"))} />
|
|
133
|
-
* ```
|
|
134
|
-
*/
|
|
135
|
-
export function inlineScript(js: string) {
|
|
136
|
-
return { dangerouslySetInnerHTML: { __html: js } } as const;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
/**
|
|
140
|
-
* @deprecated Removed in TanStack Start.
|
|
141
|
-
*
|
|
142
|
-
* The Fresh/Deno HTMX-based partial-section pattern (`useSection` /
|
|
143
|
-
* `usePartialSection` + `sections/Component.tsx`) does not apply on
|
|
144
|
-
* Cloudflare Workers and React. Replace call-sites with one of:
|
|
145
|
-
*
|
|
146
|
-
* 1. Local React state (`useState` + event handlers) for client-side toggles.
|
|
147
|
-
* 2. `createServerFn` + `useMutation` for server actions.
|
|
148
|
-
* 3. Direct `invoke` calls (`~/server/invoke`) for ad-hoc loaders.
|
|
149
|
-
*
|
|
150
|
-
* See: deco-to-tanstack-migration skill, "useComponent / partial sections"
|
|
151
|
-
* section, for the per-pattern recipes.
|
|
152
|
-
*
|
|
153
|
-
* ## SSR-safe stub behavior (since 2.27)
|
|
154
|
-
*
|
|
155
|
-
* Earlier versions threw on call. That broke SSR for the *entire page* if a
|
|
156
|
-
* single section still imported `useSection` — even sections that the user
|
|
157
|
-
* never interacts with (e.g. legacy login form on the homepage). React's
|
|
158
|
-
* error boundary would catch the throw and degrade the whole route to
|
|
159
|
-
* client rendering.
|
|
160
|
-
*
|
|
161
|
-
* The current behavior:
|
|
162
|
-
* - returns a stable placeholder URL (`HTMX_LEGACY_URL`) so it can be
|
|
163
|
-
* embedded in `hx-get` / `hx-post` attributes without crashing the
|
|
164
|
-
* SSR pass,
|
|
165
|
-
* - logs a deduped `console.warn` (in dev only) per call site so the
|
|
166
|
-
* migration signal stays loud,
|
|
167
|
-
* - the `htmx-residue` audit rule still catalogues every call site for
|
|
168
|
-
* systematic rewrite.
|
|
169
|
-
*
|
|
170
|
-
* This is a deliberate trade-off: SSR success > strict-throw enforcement.
|
|
171
|
-
* Audit + skill docs do the enforcement instead.
|
|
172
|
-
*/
|
|
173
|
-
const DEPRECATION_MESSAGE =
|
|
174
|
-
"[@decocms/start] useSection / usePartialSection were removed. " +
|
|
175
|
-
"The Fresh/Deno HTMX partial-section pattern does not apply on " +
|
|
176
|
-
"TanStack Start / Cloudflare Workers. Replace call-sites with " +
|
|
177
|
-
"createServerFn + useMutation, or local React state. See the " +
|
|
178
|
-
"deco-to-tanstack-migration skill for per-pattern recipes. " +
|
|
179
|
-
"Run `deco-post-cleanup` and look for rule [9] htmx-residue to find " +
|
|
180
|
-
"every site call-site that still depends on this.";
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Stable placeholder URL returned by the legacy `useSection` /
|
|
184
|
-
* `usePartialSection` stubs. Hitting this URL surfaces a clear error.
|
|
185
|
-
* Exported so frameworks/tests can match against it.
|
|
186
|
-
*/
|
|
187
|
-
export const HTMX_LEGACY_URL = "/__deco_legacy_htmx_section__";
|
|
188
|
-
|
|
189
|
-
function warnLegacyHtmx(name: string) {
|
|
190
|
-
if (typeof process !== "undefined" && process.env?.NODE_ENV === "production") {
|
|
191
|
-
return;
|
|
192
|
-
}
|
|
193
|
-
if (typeof (globalThis as any).__DECO_LEGACY_HTMX_WARNED === "undefined") {
|
|
194
|
-
(globalThis as any).__DECO_LEGACY_HTMX_WARNED = new Set<string>();
|
|
195
|
-
}
|
|
196
|
-
const set = (globalThis as any).__DECO_LEGACY_HTMX_WARNED as Set<string>;
|
|
197
|
-
if (set.has(name)) return;
|
|
198
|
-
set.add(name);
|
|
199
|
-
console.warn(`[${name}] ${DEPRECATION_MESSAGE}`);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
export function usePartialSection(_props?: Record<string, unknown>): string {
|
|
203
|
-
warnLegacyHtmx("usePartialSection");
|
|
204
|
-
return HTMX_LEGACY_URL;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
export function useSection(_props?: Record<string, unknown>): string {
|
|
208
|
-
warnLegacyHtmx("useSection");
|
|
209
|
-
return HTMX_LEGACY_URL;
|
|
210
|
-
}
|
|
@@ -1,188 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Search-suggestions hook factory.
|
|
3
|
-
*
|
|
4
|
-
* Two production storefronts independently
|
|
5
|
-
* invented the same shape for autocomplete-style suggestions:
|
|
6
|
-
*
|
|
7
|
-
* - module-level signal for the current payload + loading flag
|
|
8
|
-
* - serial in-flight queue so older requests can't race past newer ones
|
|
9
|
-
* - "is this still the latest query?" cancel guard
|
|
10
|
-
* - posts to `/deco/invoke/<__resolveType>` with the loader's
|
|
11
|
-
* extra props + the live `query` string
|
|
12
|
-
*
|
|
13
|
-
* This factory is the canonical version. Sites instantiate it once
|
|
14
|
-
* at module load with their concrete suggestion type and (optionally)
|
|
15
|
-
* an `onError` hook for observability (Sentry / OpenTelemetry / etc.).
|
|
16
|
-
*
|
|
17
|
-
* Why a factory and not a plain hook:
|
|
18
|
-
* - Each call to `createUseSuggestions()` produces an isolated
|
|
19
|
-
* `payload` / `loading` / queue. Keeps the door open for sites
|
|
20
|
-
* with multiple independent suggestion streams (e.g. searchbar
|
|
21
|
-
* *and* a category-jump suggester) without globally-shared state.
|
|
22
|
-
* - Type narrowing happens at the factory boundary, not at hook
|
|
23
|
-
* usage — the returned `useSuggestions` is already specialised
|
|
24
|
-
* on `T` so callers don't need to re-pass generics.
|
|
25
|
-
* - Mirrors the existing `createUseCart` / `createUseUser` /
|
|
26
|
-
* `createUseWishlist` factory pattern from
|
|
27
|
-
* `@decocms/apps/vtex/hooks/*`. See
|
|
28
|
-
* `references/platform-hooks-factories.md`.
|
|
29
|
-
*/
|
|
30
|
-
|
|
31
|
-
import { useCallback } from "react";
|
|
32
|
-
import type { Resolved } from "../types";
|
|
33
|
-
import { signal, type ReactiveSignal } from "./signal";
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Optional dependencies the factory accepts at instantiation time.
|
|
37
|
-
*
|
|
38
|
-
* Most are pure observability hooks — the factory itself runs a
|
|
39
|
-
* `console.error()` after invoking `onError`, so callers don't have
|
|
40
|
-
* to remember to forward the error to the console themselves.
|
|
41
|
-
*/
|
|
42
|
-
export interface UseSuggestionsOptions {
|
|
43
|
-
/**
|
|
44
|
-
* Called once per failed fetch with the original error and the
|
|
45
|
-
* query that triggered it. Use for Sentry / OTEL captures.
|
|
46
|
-
*
|
|
47
|
-
* The factory still calls `console.error` after this returns so
|
|
48
|
-
* sites that don't wire `onError` keep the same console output.
|
|
49
|
-
*/
|
|
50
|
-
onError?: (error: unknown, query: string) => void;
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Override the fetch implementation. Tests pass a stub here; the
|
|
54
|
-
* default is the global `fetch`. Production sites have no reason
|
|
55
|
-
* to set this.
|
|
56
|
-
*/
|
|
57
|
-
fetchImpl?: typeof fetch;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Shape returned by the hook produced by `createUseSuggestions`.
|
|
62
|
-
*
|
|
63
|
-
* `loading` and `payload` are reactive signals — subscribe with
|
|
64
|
-
* `useStore()` from `@tanstack/react-store` (or read `.value`
|
|
65
|
-
* directly inside an `useEffect`).
|
|
66
|
-
*/
|
|
67
|
-
export interface UseSuggestionsReturn<T> {
|
|
68
|
-
loading: ReactiveSignal<boolean>;
|
|
69
|
-
payload: ReactiveSignal<T | null>;
|
|
70
|
-
/**
|
|
71
|
-
* Trigger a suggestion fetch for `query`. Calls coalesce through
|
|
72
|
-
* a serial promise queue, and only the *latest* query's result
|
|
73
|
-
* is allowed to flip `loading` back to `false` — so rapid keystrokes
|
|
74
|
-
* don't leave the UI permanently in a stale loading state.
|
|
75
|
-
*/
|
|
76
|
-
setQuery: (query: string) => void;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Returned by {@link createUseSuggestions}.
|
|
81
|
-
*
|
|
82
|
-
* `useSuggestions` is the React hook bound to this factory's state.
|
|
83
|
-
* The `_internal` field exposes the underlying signals and a non-
|
|
84
|
-
* React `setQuery` for advanced cases (SSR pre-population, unit
|
|
85
|
-
* tests, server-side warmup). Sites almost never need it.
|
|
86
|
-
*/
|
|
87
|
-
export interface CreateUseSuggestionsReturn<T> {
|
|
88
|
-
useSuggestions: (loader: Resolved<T | null>) => UseSuggestionsReturn<T>;
|
|
89
|
-
_internal: {
|
|
90
|
-
readonly payload: ReactiveSignal<T | null>;
|
|
91
|
-
readonly loading: ReactiveSignal<boolean>;
|
|
92
|
-
/**
|
|
93
|
-
* Same semantics as `useSuggestions(...).setQuery`, but pure JS —
|
|
94
|
-
* no React hook context required. Useful in unit tests and for
|
|
95
|
-
* SSR pre-fetch helpers.
|
|
96
|
-
*/
|
|
97
|
-
setQuery: (query: string, loader: Resolved<T | null>) => void;
|
|
98
|
-
/**
|
|
99
|
-
* Promise that resolves once every queued fetch has settled.
|
|
100
|
-
* Tests await this to assert post-cancellation state.
|
|
101
|
-
*/
|
|
102
|
-
readonly drain: () => Promise<unknown>;
|
|
103
|
-
};
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Build a typed `useSuggestions` hook bound to a private
|
|
108
|
-
* `payload` / `loading` / queue tuple. Call once per stream at
|
|
109
|
-
* module load.
|
|
110
|
-
*
|
|
111
|
-
* @example
|
|
112
|
-
* // site/src/sdk/useSuggestions.ts
|
|
113
|
-
* import { createUseSuggestions } from "@decocms/start/sdk/useSuggestions";
|
|
114
|
-
* import * as Sentry from "@sentry/react";
|
|
115
|
-
* import type { Suggestion } from "@decocms/apps/commerce/types";
|
|
116
|
-
*
|
|
117
|
-
* export const { useSuggestions } = createUseSuggestions<Suggestion>({
|
|
118
|
-
* onError: (err) => Sentry.captureException(err),
|
|
119
|
-
* });
|
|
120
|
-
*/
|
|
121
|
-
export function createUseSuggestions<T>(
|
|
122
|
-
options: UseSuggestionsOptions = {},
|
|
123
|
-
): CreateUseSuggestionsReturn<T> {
|
|
124
|
-
const payload = signal<T | null>(null);
|
|
125
|
-
const loading = signal<boolean>(false);
|
|
126
|
-
let queue: Promise<unknown> = Promise.resolve();
|
|
127
|
-
let latestQuery = "";
|
|
128
|
-
|
|
129
|
-
const fetchImpl = options.fetchImpl ?? fetch;
|
|
130
|
-
const onError = options.onError;
|
|
131
|
-
|
|
132
|
-
async function doFetch(
|
|
133
|
-
query: string,
|
|
134
|
-
resolved: Resolved<T | null>,
|
|
135
|
-
): Promise<void> {
|
|
136
|
-
if (latestQuery !== query) return;
|
|
137
|
-
|
|
138
|
-
const { __resolveType, ...extraProps } = resolved as {
|
|
139
|
-
__resolveType: string;
|
|
140
|
-
[k: string]: unknown;
|
|
141
|
-
};
|
|
142
|
-
|
|
143
|
-
try {
|
|
144
|
-
const response = await fetchImpl(`/deco/invoke/${__resolveType}`, {
|
|
145
|
-
method: "POST",
|
|
146
|
-
headers: { "Content-Type": "application/json" },
|
|
147
|
-
body: JSON.stringify({ query, ...extraProps }),
|
|
148
|
-
});
|
|
149
|
-
if (!response.ok) {
|
|
150
|
-
throw new Error(`Suggestions invoke failed: ${response.status}`);
|
|
151
|
-
}
|
|
152
|
-
payload.value = (await response.json()) as T | null;
|
|
153
|
-
} catch (error) {
|
|
154
|
-
onError?.(error, query);
|
|
155
|
-
console.error("[useSuggestions] fetch failed:", error);
|
|
156
|
-
} finally {
|
|
157
|
-
// Only the latest query is allowed to flip the loading flag —
|
|
158
|
-
// otherwise rapid keystrokes can leave the UI in a stale
|
|
159
|
-
// "still loading" state because an older fetch resolved last.
|
|
160
|
-
if (latestQuery === query) loading.value = false;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
function setQueryImpl(query: string, loader: Resolved<T | null>): void {
|
|
165
|
-
loading.value = true;
|
|
166
|
-
latestQuery = query;
|
|
167
|
-
queue = queue.then(() => doFetch(query, loader));
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
function useSuggestions(loader: Resolved<T | null>): UseSuggestionsReturn<T> {
|
|
171
|
-
const setQuery = useCallback(
|
|
172
|
-
(query: string) => setQueryImpl(query, loader),
|
|
173
|
-
[loader],
|
|
174
|
-
);
|
|
175
|
-
|
|
176
|
-
return { loading, payload, setQuery };
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
return {
|
|
180
|
-
useSuggestions,
|
|
181
|
-
_internal: {
|
|
182
|
-
payload,
|
|
183
|
-
loading,
|
|
184
|
-
setQuery: setQueryImpl,
|
|
185
|
-
drain: () => queue,
|
|
186
|
-
},
|
|
187
|
-
};
|
|
188
|
-
}
|