@storystick/next 0.2.0-rc.1 → 0.2.0-rc.3

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/PUBLIC-API.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @storystick/next API contract
2
2
 
3
- Install this candidate explicitly with `@storystick/next@0.2.0-rc.1` after registry bootstrap and publication. This repository alone does not make the candidate or beta channel available on npm.
3
+ Install this candidate explicitly with `@storystick/next@0.2.0-rc.3` after registry bootstrap and publication. This repository alone does not make the candidate or beta channel available on npm.
4
4
 
5
- Version 0.2.0-rc.1, cohort `sdk-0.2.0-rc.1`. ESM distribution; no CommonJS or universal Edge compatibility is promised.
5
+ Version 0.2.0-rc.3, cohort `sdk-0.2.0-rc.3`. ESM distribution; no CommonJS or universal Edge compatibility is promised.
6
6
 
7
7
  This package is a product integration facade. Reserved contracts are required between SDK packages and must be upgraded with the same cohort. Their public export paths do not promise independent stability.
8
8
 
@@ -24,7 +24,7 @@ This package is a product integration facade. Reserved contracts are required be
24
24
  | `./testing` | Reserved SDK contract |
25
25
  | `./server` | Supported beta entry |
26
26
 
27
- The qualified toolchain is Node 24.19.0 and pnpm 9.15.9. Next uses App Router 15.5.28, Sharp 0.35.5 and React/React DOM 19.2.8; Astro uses 7.4.4 with the Node adapter 11.1.9. Browser delivery is verified by bundling; hosted Preview activation and cross-browser behavior require the staging manual check. Source/CLI are Node tools, server entries belong on the server, and browser entries must never receive a server API key.
27
+ Supported consumer Node versions: `^22.13.0 || ^24.19.0`. The release build toolchain remains Node 24.19.0 and pnpm 9.15.9. Next uses App Router 15.5.28, Sharp 0.35.5 and React/React DOM 19.2.8; Astro uses 7.4.4 with the Node adapter 11.1.9. Browser delivery is verified by bundling; hosted Preview activation and cross-browser behavior require the staging manual check. Source/CLI are Node tools, server entries belong on the server, and browser entries must never receive a server API key.
28
28
 
29
29
  Use a generated Query V2 definition. A missing document/singleton returns null, an empty collection returns an empty array, and fetch throws on blocked/degraded execution. Execute exposes the complete result envelope. RSC metadata must remain plain JSON data; request authority must not be stored in shared module state.
30
30
 
package/README.md CHANGED
@@ -1,6 +1,21 @@
1
1
  # @storystick/next
2
2
 
3
- Minimal content reads and Preview for the Next.js 15 App Router, with React 19.
3
+ Minimal content reads and Preview for the Next.js 15 and 16 App Router, with React 19.
4
+
5
+ The supported framework ranges are `^15.5.28 || ^16.2.9`. Release preparation
6
+ qualifies both pinned minimum versions with the same SDK archives. The cache
7
+ webhook uses immediate tag expiration on both versions; Next 16's
8
+ stale-while-revalidate `max` profile is not substituted for that contract.
9
+
10
+ To repeat the standalone consumer recipe on Next 16:
11
+
12
+ ```sh
13
+ node scripts/starter-qualification.mjs --release-dir /path/to/candidate --next-version 16.2.9
14
+ ```
15
+
16
+ For SDK unit tests against an independently installed framework, set
17
+ `STORYSTICK_NEXT_TEST_ROOT` to that installation's `node_modules/next` directory.
18
+ This affects the test resolver only, never the package runtime.
4
19
 
5
20
  ```bash
6
21
  pnpm add @storystick/next@beta
@@ -519,5 +534,20 @@ must fail the next build. See the [Next 15 cache behavior](https://nextjs.org/do
519
534
  ## Candidate distribution contract
520
535
 
521
536
  See [PUBLIC-API.md](./PUBLIC-API.md) for supported entries, reserved SDK contracts,
522
- the qualified runtime matrix and the candidate cohort. Upgrade Storystick
523
- packages together.
537
+ the qualified runtime matrix and the candidate cohort. Keep shared contracts
538
+ compatible. Use the [release guide](../../release/README.md) to select the
539
+ packages and consumers that need an update; an independent adapter fix does
540
+ not require republishing every package.
541
+
542
+ ## Hosted connection
543
+
544
+ Run `storystick connect` from the website repository. The adapter uses the four
545
+ project connection variables written by the CLI and discovers the public
546
+ Storystick services. No infrastructure URL or platform environment selector is
547
+ required. Restart/rebuild Next after changing the connection: public variables
548
+ are embedded at build time.
549
+
550
+ Mount `<Storystick />` from a Server Component so server configuration reaches
551
+ the browser through the adapter. Explicit transport props remain available for
552
+ deliberate local/self-hosted integrations; conflicting service configuration
553
+ fails instead of silently selecting another destination.
package/dist/.source-hash CHANGED
@@ -1 +1 @@
1
- 20e8248dcde770c1a3966e62bbd395af132defa0ac1ada5c01ce32f486997919
1
+ 0e9cc2f9becc7a5e253621d032bfaa2864dac49eb6aedf65d3d3c57c11cd8a89
@@ -4,9 +4,9 @@ export * from './rendering.js';
4
4
  import { renderStorystick } from './storystick.js';
5
5
  import { readPreviewServerRenderReceipt } from './server-runtime.js';
6
6
  export async function Storystick(props = {}) {
7
- const { projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion } = props;
7
+ const { projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion, service } = props;
8
8
  return renderStorystick({
9
- projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion,
9
+ projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion, service,
10
10
  previewServerRenderReceipt: await readPreviewServerRenderReceipt(projectId),
11
11
  });
12
12
  }
@@ -1,13 +1,3 @@
1
- /**
2
- * Internal helpers shared by the Preview activation and token routes.
3
- *
4
- * Server-only. Not re-exported from `@storystick/next/preview`.
5
- *
6
- * ADR-131 C9 — endpoint resolution flows through `resolveInfra()` which
7
- * shares its `resolveProject` cache with `server.ts` (same per-process
8
- * Map in `@storystick/client/resolve.ts`). The `STORYSTICK_ENDPOINT` env
9
- * escape hatch is preserved as an undocumented self-host override.
10
- */
11
1
  import type { NextRequest } from 'next/server';
12
2
  export type PreviewTransport = {
13
3
  endpoint: string;
@@ -56,6 +46,6 @@ export declare function _resetPreviewTransport(): void;
56
46
  /**
57
47
  * Allow tests to inject a transport without going through env vars or
58
48
  * `resolveProject`. The override is consumed by `getPreviewTransport`
59
- * on next call. Returns a dispose function that restores prior state.
49
+ * until `_resetPreviewTransport` clears it.
60
50
  */
61
51
  export declare function _setPreviewTransport(t: PreviewTransport | null): void;
@@ -1,3 +1,4 @@
1
+ import { serverInfraOptions } from '../service-config.js';
1
2
  /**
2
3
  * Internal helpers shared by the Preview activation and token routes.
3
4
  *
@@ -11,13 +12,15 @@
11
12
  import { resolveInfra } from '@storystick/client/adapter';
12
13
  import { previewControlClient } from '@storystick/preview/server/control-client';
13
14
  let _previewTransport = null;
15
+ let _previewTransportIdentity;
16
+ let _previewTransportOverride = null;
14
17
  export async function createPreviewControlClient(token) {
15
18
  const transport = await getPreviewTransport();
16
19
  return previewControlClient(transport.endpoint, token);
17
20
  }
18
21
  export async function getPreviewTransport() {
19
- if (_previewTransport)
20
- return _previewTransport;
22
+ if (_previewTransportOverride)
23
+ return _previewTransportOverride;
21
24
  const apiKey = process.env.STORYSTICK_API_KEY;
22
25
  if (!apiKey) {
23
26
  throw new Error('StorystickError: No STORYSTICK_API_KEY found.\n' +
@@ -32,10 +35,12 @@ export async function getPreviewTransport() {
32
35
  ' STORYSTICK_PROJECT_ID=a3k9m2x7\n' +
33
36
  ' STORYSTICK_API_KEY=ss_sk_live_...\n');
34
37
  }
35
- const directEndpoint = process.env.STORYSTICK_ENDPOINT;
36
- const infra = await resolveInfra(projectId, {
37
- endpoint: directEndpoint || undefined,
38
- });
38
+ const options = serverInfraOptions();
39
+ const identity = JSON.stringify([projectId, apiKey, options]);
40
+ if (_previewTransport && _previewTransportIdentity === identity)
41
+ return _previewTransport;
42
+ const infra = await resolveInfra(projectId, options);
43
+ _previewTransportIdentity = identity;
39
44
  _previewTransport = {
40
45
  endpoint: infra.endpoint,
41
46
  projectId,
@@ -86,12 +91,14 @@ export function resolvePreviewRequestOrigin(request) {
86
91
  /** Reset the transport singleton (testing only). */
87
92
  export function _resetPreviewTransport() {
88
93
  _previewTransport = null;
94
+ _previewTransportIdentity = undefined;
95
+ _previewTransportOverride = null;
89
96
  }
90
97
  /**
91
98
  * Allow tests to inject a transport without going through env vars or
92
99
  * `resolveProject`. The override is consumed by `getPreviewTransport`
93
- * on next call. Returns a dispose function that restores prior state.
100
+ * until `_resetPreviewTransport` clears it.
94
101
  */
95
102
  export function _setPreviewTransport(t) {
96
- _previewTransport = t;
103
+ _previewTransportOverride = t;
97
104
  }
@@ -7,6 +7,7 @@ import { createPreviewControlClient, getPreviewTransport, resolvePreviewRequestO
7
7
  import { resolvePreviewGrantAccess } from '@storystick/preview/server/extract-token';
8
8
  import { prunePreviewAdmissionCookies } from '@storystick/preview/server/route-session-cookie';
9
9
  import { previewControlErrorResponse, previewErrorResponse } from './route-errors.js';
10
+ import { serverInfraOptions } from '../service-config.js';
10
11
  export function createStorystickPreviewTokenHandler(options = {}) {
11
12
  return async function POST(request) {
12
13
  const sessionId = request.nextUrl.searchParams.get(PREVIEW_SESSION_QUERY_PARAM);
@@ -32,7 +33,8 @@ export function createStorystickPreviewTokenHandler(options = {}) {
32
33
  await client.context({ sessionId });
33
34
  const remainingMs = Math.max(0, fields.tokenExpiresAt - now);
34
35
  const response = NextResponse.json({ token: fields.token, expiresAt: fields.tokenExpiresAt,
35
- refreshAfter: now + Math.max(1000, Math.floor(remainingMs * 0.8)), sessionId, projectId: fields.projectId }, { headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' } });
36
+ refreshAfter: now + Math.max(1000, Math.floor(remainingMs * 0.8)), sessionId, projectId: fields.projectId }, { headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',
37
+ 'X-Storystick-Service': JSON.stringify(serverInfraOptions().service ?? null) } });
36
38
  // Safe even if this response arrives after a newer activation: all deletions
37
39
  // have lower sequence AND were observed in this particular request.
38
40
  prunePreviewAdmissionCookies({ response, reader, scope, requestUrl: requestOrigin + request.nextUrl.pathname,
@@ -1,7 +1 @@
1
- export interface PreviewErrorSurfaceProps {
2
- code?: string | null;
3
- studioUrl?: string | null;
4
- }
5
- /** A terminal Preview state owns its viewport, without changing customer DOM.
6
- * Isolate product styling from the customer's page and its error boundary. */
7
- export declare function PreviewErrorSurface({ code, studioUrl }: PreviewErrorSurfaceProps): import("react").JSX.Element;
1
+ export { PreviewTerminalState as PreviewErrorSurface, type PreviewTerminalStateProps as PreviewErrorSurfaceProps } from '@storystick/react/internal/preview-terminal-state';
@@ -1,20 +1,2 @@
1
1
  'use client';
2
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { useEffect, useRef, useState } from 'react';
4
- import { createPortal } from 'react-dom';
5
- import { lookupSdkCopy } from '@storystick/preview/sdk-error-copy';
6
- import { PreviewPageState } from '@storystick/react/internal/preview-page-state';
7
- /** A terminal Preview state owns its viewport, without changing customer DOM.
8
- * Isolate product styling from the customer's page and its error boundary. */
9
- export function PreviewErrorSurface({ code, studioUrl }) {
10
- const copy = lookupSdkCopy(code);
11
- const host = useRef(null);
12
- const [root, setRoot] = useState(null);
13
- useEffect(() => {
14
- if (host.current)
15
- setRoot(host.current.shadowRoot ?? host.current.attachShadow({ mode: 'open' }));
16
- }, []);
17
- return _jsx("div", { ref: host, "data-storystick-preview-error": "", "data-storystick-preview-controls": "", style: {
18
- all: 'initial', position: 'fixed', inset: 0, zIndex: 2147483646, background: '#fff',
19
- }, children: root ? createPortal(_jsx(PreviewPageState, { title: copy.title, description: copy.body, role: "alert", actions: studioUrl ? _jsx("a", { "data-ss-preview-page-action": "", href: studioUrl, children: "Return to Studio" }) : null, children: code || copy.commonCauses.length ? _jsxs("details", { children: [_jsx("summary", { children: "Technical details" }), code ? _jsx("pre", { children: code }) : null, copy.commonCauses.length ? _jsx("ul", { style: { textAlign: 'left', paddingLeft: 18 }, children: copy.commonCauses.map(cause => _jsx("li", { children: cause }, cause)) }) : null] }) : null }), root) : null });
20
- }
2
+ export { PreviewTerminalState as PreviewErrorSurface } from '@storystick/react/internal/preview-terminal-state';
@@ -0,0 +1,5 @@
1
+ import { type ServiceConnection } from '@storystick/types/public-endpoints';
2
+ /** Reuse existing identity carriers; the token route still authorizes every hint. */
3
+ export declare function recoverySessionId(projectId: string): string | null;
4
+ /** Error boundaries have no RSC props. Recover only from the site's authenticated route. */
5
+ export declare function recoverPreviewService(tokenRoute: string, projectId: string, sessionId: string | null, signal: AbortSignal): Promise<ServiceConnection | undefined>;
@@ -0,0 +1,32 @@
1
+ import { parseServiceConnection } from '@storystick/types/public-endpoints';
2
+ import { readPreviewSessionIdFromSearch, readStored } from '@storystick/preview/identity';
3
+ import { readStandalonePreviewSessionId } from '@storystick/preview/identity/browser-context';
4
+ /** Reuse existing identity carriers; the token route still authorizes every hint. */
5
+ export function recoverySessionId(projectId) {
6
+ if (new URLSearchParams(window.location.search).has('_ss_session'))
7
+ return readPreviewSessionIdFromSearch(window.location.search);
8
+ if (window.parent === window)
9
+ return readStandalonePreviewSessionId(projectId);
10
+ const stored = readStored();
11
+ return stored?.projectId === projectId && stored.expiresAt > Date.now() ? stored.sessionId : null;
12
+ }
13
+ /** Error boundaries have no RSC props. Recover only from the site's authenticated route. */
14
+ export async function recoverPreviewService(tokenRoute, projectId, sessionId, signal) {
15
+ if (!sessionId)
16
+ throw new Error('Preview session is required to recover the service.');
17
+ const url = new URL(tokenRoute, window.location.origin);
18
+ if (url.origin !== window.location.origin)
19
+ throw new Error('Preview service recovery must remain same-origin.');
20
+ url.searchParams.set('_ss_session', sessionId);
21
+ const response = await fetch(url.href, { method: 'POST', credentials: 'same-origin', redirect: 'error', cache: 'no-store', signal });
22
+ if (!response.ok)
23
+ throw new Error('Preview service recovery was refused.');
24
+ const body = await response.json();
25
+ if (body?.projectId !== projectId || body?.sessionId !== sessionId)
26
+ throw new Error('Preview service recovery identity mismatch.');
27
+ const raw = response.headers.get('X-Storystick-Service');
28
+ // Missing is not production: the route must understand this SDK contract.
29
+ if (raw === null)
30
+ throw new Error('Preview service configuration is missing.');
31
+ return raw === 'null' ? undefined : parseServiceConnection(raw);
32
+ }
@@ -5,7 +5,7 @@ export interface StorystickRevalidateHandlerOptions {
5
5
  projectId?: string | (() => string | undefined);
6
6
  signatureHeader?: string;
7
7
  }
8
- /** Next 15 revalidateTag expires the project's Data Cache synchronously. This
8
+ /** Expire the project's Data Cache on both Next 15 and Next 16. This
9
9
  * acknowledges the effect only; the publisher separately verifies rendered HTML. */
10
10
  export declare function createStorystickRevalidateHandler(options?: StorystickRevalidateHandlerOptions): (request: Request) => Promise<Response>;
11
11
  export declare const POST: (request: Request) => Promise<Response>;
@@ -3,7 +3,9 @@ import { storystickCacheTag } from './cache-tags.js';
3
3
  import { readSignedWebhook, signWebhookBody } from '@storystick/client/adapter';
4
4
  import { isPublicationEvent } from '@storystick/types/publication';
5
5
  import { revalidateTag } from 'next/cache';
6
- /** Next 15 revalidateTag expires the project's Data Cache synchronously. This
6
+ // Next 15 ignores the extra profile; Next 16 uses it for explicit immediate expiry.
7
+ const expireTag = revalidateTag;
8
+ /** Expire the project's Data Cache on both Next 15 and Next 16. This
7
9
  * acknowledges the effect only; the publisher separately verifies rendered HTML. */
8
10
  export function createStorystickRevalidateHandler(options = {}) {
9
11
  return async (request) => {
@@ -21,7 +23,7 @@ export function createStorystickRevalidateHandler(options = {}) {
21
23
  if (!isPublicationEvent(event) || event.projectId !== projectId)
22
24
  return json({ error: 'publication_invalid' }, 400);
23
25
  try {
24
- revalidateTag(storystickCacheTag(`storystick:project:${projectId}`));
26
+ expireTag(storystickCacheTag(`storystick:project:${projectId}`), { expire: 0 });
25
27
  }
26
28
  catch {
27
29
  return json({ error: 'publication_effect_failed' }, 503);
@@ -1,3 +1,5 @@
1
+ import { serverInfraOptions } from './service-config.js';
2
+ import { routeDataMatches } from '@storystick/types/public-delivery';
1
3
  import { PUBLIC_RENDER_CHALLENGE_HEADER, isPublicRenderChallenge } from '@storystick/types/public-delivery';
2
4
  import { fetchProjectLocaleSettings } from '@storystick/client/adapter';
3
5
  import { createPublicRenderReceipt, createPublicSiteManifest } from '@storystick/client';
@@ -180,20 +182,10 @@ function readProjectId() {
180
182
  ' STORYSTICK_PROJECT_ID=a3k9m2x7\n' +
181
183
  ' STORYSTICK_API_KEY=ss_sk_live_...\n');
182
184
  }
183
- /**
184
- * Resolve the gateway endpoint + Convex RPC URL for `projectId`. ADR-131
185
- * C9 — delegates to `resolveInfra` which auto-derives the `.convex.site` /
186
- * `.convex.cloud` pair from one gateway round-trip. Per-URL env escape
187
- * hatches (`STORYSTICK_ENDPOINT`, `STORYSTICK_CONVEX_URL`) are honoured
188
- * (undocumented in customer `.env.example`) for self-host overrides.
189
- */
185
+ /** Hosted routing follows the connection's environment. Legacy URL overrides
186
+ * are only read when no hosted environment was selected. */
190
187
  async function resolveServerInfra(projectId) {
191
- const directEndpoint = process.env.STORYSTICK_ENDPOINT;
192
- const directConvex = process.env.STORYSTICK_CONVEX_URL;
193
- return resolveInfra(projectId, {
194
- endpoint: directEndpoint && directEndpoint.length > 0 ? directEndpoint : undefined,
195
- convexUrl: directConvex && directConvex.length > 0 ? directConvex : undefined,
196
- });
188
+ return resolveInfra(projectId, serverInfraOptions());
197
189
  }
198
190
  /**
199
191
  * Build a Storystick client bound to the current Next.js request.
@@ -744,6 +736,21 @@ async function routes(storyTypes) {
744
736
  // resolvePage — ADR-094 §1 Next façade
745
737
  // ─────────────────────────────────────────────
746
738
  import { resolveStorystickPage } from '@storystick/client/adapter';
739
+ function compilePublicPageData(declarations, querySchema) {
740
+ if (declarations === undefined)
741
+ return undefined;
742
+ if (!querySchema && Object.keys(declarations).length)
743
+ throw new TypeError('storystick/QUERY_INVALID: resolvePage data requires querySchema.');
744
+ return Object.fromEntries(Object.entries(declarations).map(([key, declaration]) => {
745
+ const limit = declaration.first === undefined ? 10_000 : Math.min(10_000, declaration.first);
746
+ if (!Number.isSafeInteger(limit) || limit < 1 || !Object.hasOwn(querySchema.stories, declaration.query))
747
+ throw new TypeError('storystick/QUERY_INVALID: Invalid public page data declaration.');
748
+ return [key, { limit, ...(declaration.for ? { for: [...declaration.for] } : {}), query: {
749
+ version: 2, target: { kind: 'documents', storyType: declaration.query }, selection: { mode: 'all' }, cardinality: 'many',
750
+ page: { first: Math.min(100, limit) }, locale: { code: 'default', fallback: 'configured' }, generatedSchemaFingerprint: querySchema.fingerprint,
751
+ } }];
752
+ }));
753
+ }
747
754
  const resolveStorystickPageCached = cache(async (cacheKey, previewSessionId, previewRoutePathname, querySchema) => {
748
755
  const input = JSON.parse(cacheKey);
749
756
  // The site manifest must code authored values before the client hydrates
@@ -754,7 +761,7 @@ const resolveStorystickPageCached = cache(async (cacheKey, previewSessionId, pre
754
761
  : {
755
762
  sessionId: previewSessionId ?? null,
756
763
  routePathname: previewRoutePathname,
757
- }, input.publicOrigins ? { ...await readProjectLocaleSettings(), publicOrigins: input.publicOrigins } : undefined, true);
764
+ }, previewRoutePathname !== undefined && input.publicOrigins ? { ...await readProjectLocaleSettings(), publicOrigins: input.publicOrigins } : undefined, true);
758
765
  return resolveStorystickPage(client, input);
759
766
  });
760
767
  function serializeResolvePageSearchParams(searchParams) {
@@ -882,6 +889,7 @@ export async function resolvePage(input) {
882
889
  pathname: publicPathname,
883
890
  locale: input.locale,
884
891
  publicOrigins: input.publicOrigins,
892
+ dataQueries: compilePublicPageData(input.data, input.querySchema),
885
893
  ...(input.storyTypes ? { storyTypes: [...input.storyTypes] } : {}),
886
894
  }), previewRequest?.sessionId, previewRequest?.routePathname, input.querySchema);
887
895
  if (route.type === 'redirect') {
@@ -903,6 +911,7 @@ export async function resolvePage(input) {
903
911
  declaration: input.data,
904
912
  querySchema: input.querySchema,
905
913
  document: route.document,
914
+ composedData: route.data,
906
915
  storyType: route.storyType,
907
916
  localeContext: route.localeContext,
908
917
  previewRequest,
@@ -939,7 +948,7 @@ async function prepareResolvedPageRoute(input) {
939
948
  // Public and Preview draft routes deliberately share this exact boundary.
940
949
  attachDocumentLocaleRouting(input.document, input.localeContext);
941
950
  const [data, document] = await Promise.all([
942
- resolveDeclaredPageData({
951
+ input.composedData !== undefined ? Promise.resolve(input.composedData) : resolveDeclaredPageData({
943
952
  declaration: input.declaration,
944
953
  querySchema: input.querySchema,
945
954
  document: input.document,
@@ -991,19 +1000,7 @@ async function resolveDeclaredPageData(input) {
991
1000
  return Object.fromEntries(resolved);
992
1001
  }
993
1002
  function pageDataDeclarationMatchesRoute(input) {
994
- const conditions = input.declaration.for;
995
- if (conditions === undefined || conditions.length === 0)
996
- return true;
997
- for (const condition of conditions) {
998
- if (typeof condition === 'string') {
999
- if (input.sliceTypes().has(condition))
1000
- return true;
1001
- continue;
1002
- }
1003
- if (condition.storyType === input.storyType)
1004
- return true;
1005
- }
1006
- return false;
1003
+ return routeDataMatches(input.declaration.for, input.storyType, input.sliceTypes);
1007
1004
  }
1008
1005
  async function readStorystickList(input) {
1009
1006
  const context = input.localeContext ??
@@ -0,0 +1,6 @@
1
+ /** Server-side only input. Never read a second browser environment selector. */
2
+ export declare function serverInfraOptions(): {
3
+ service: import("@storystick/types/public-endpoints").ServiceConnection | undefined;
4
+ endpoint: string | undefined;
5
+ convexUrl: string | undefined;
6
+ };
@@ -0,0 +1,14 @@
1
+ import { assertServiceOrigin, serviceConnectionFromEnv } from '@storystick/types/public-endpoints';
2
+ /** Server-side only input. Never read a second browser environment selector. */
3
+ export function serverInfraOptions() {
4
+ const service = serviceConnectionFromEnv(process.env);
5
+ const endpoint = process.env.STORYSTICK_ENDPOINT || undefined;
6
+ const convexUrl = process.env.STORYSTICK_CONVEX_URL || undefined;
7
+ if (service) {
8
+ assertServiceOrigin(process.env.STORYSTICK_ENDPOINT, service.apiOrigin);
9
+ assertServiceOrigin(process.env.STORYSTICK_GATEWAY_URL, service.apiOrigin);
10
+ assertServiceOrigin(process.env.STORYSTICK_CONVEX_URL, service.syncOrigin);
11
+ assertServiceOrigin(process.env.STORYSTICK_DELIVERY_ENDPOINT, service.apiOrigin);
12
+ }
13
+ return { service, endpoint, convexUrl };
14
+ }
@@ -1,4 +1,7 @@
1
+ import type { ServiceConnection } from '@storystick/types/public-endpoints';
1
2
  export interface StorystickClientProps {
3
+ /** Complete alternate service, resolved by the server adapter. */
4
+ service?: ServiceConnection;
2
5
  /** Defaults to `process.env.NEXT_PUBLIC_STORYSTICK_PROJECT_ID`. */
3
6
  projectId?: string;
4
7
  /** Deploy/build signature exposed to the Preview iframe runtime. */
@@ -14,6 +17,8 @@ export interface StorystickClientProps {
14
17
  }
15
18
  /** @internal Props resolved by the server wrapper before the iframe runtime loads. */
16
19
  export interface StorystickPreviewRuntimeProps extends StorystickClientProps {
20
+ /** @internal Recover server selection when an error boundary replaces the RSC mount. */
21
+ readonly recoverServiceFromServer?: boolean;
17
22
  readonly previewServerRenderReceipt?: import('@storystick/preview/framework/render-receipt').PreviewFrameworkRenderReceipt | null;
18
23
  /** @internal Client error-boundary reset; never passed across an RSC boundary. */
19
24
  readonly resetRenderError?: () => void;
@@ -1,6 +1,7 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { isPreviewBrowserContext } from "@storystick/preview/framework/browser-context";
3
+ import { isPreviewBrowserContext, hasExplicitPreviewBrowserContext, readStandalonePreviewSessionId } from "@storystick/preview/framework/browser-context";
4
+ import { PREVIEW_COPY } from '@storystick/preview/framework/preview-copy';
4
5
  import { useEffect, useLayoutEffect, useState, useSyncExternalStore } from "react";
5
6
  import { commitPreviewRenderReceipt } from '@storystick/preview/framework/render-receipt';
6
7
  function subscribeEmbeddingContext() {
@@ -38,8 +39,11 @@ export function Storystick(props = {}) {
38
39
  }, [active]);
39
40
  if (!active)
40
41
  return null;
41
- if (runtime.failed)
42
- return (_jsxs("aside", { role: "alert", children: ["Preview could not start because its runtime could not be loaded.", _jsx("button", { type: "button", onClick: () => window.location.reload(), children: "Reload Preview" })] }));
42
+ const projectId = props.projectId ?? process.env.NEXT_PUBLIC_STORYSTICK_PROJECT_ID;
43
+ const explicit = hasExplicitPreviewBrowserContext(projectId);
44
+ const invalidLink = window.parent === window && explicit && !readStandalonePreviewSessionId(projectId);
45
+ if (runtime.failed && explicit)
46
+ return (_jsxs("aside", { role: "status", "data-storystick-preview-controls": "", children: [PREVIEW_COPY[invalidLink ? 'opening-invalid' : 'runtime-unavailable'].title, ". ", PREVIEW_COPY[invalidLink ? 'opening-invalid' : 'runtime-unavailable'].body, !invalidLink ? _jsx("button", { type: "button", onClick: () => window.location.reload(), children: "Reload Preview" }) : null] }));
43
47
  const Runtime = runtime.module?.StorystickPreviewRuntime;
44
48
  return Runtime ? _jsx(Runtime, { ...props }) : null;
45
49
  }
@@ -7,5 +7,5 @@ import { Storystick } from './storystick-component.js';
7
7
  * A normal public visit does not load the Preview runtime.
8
8
  */
9
9
  export function StorystickErrorRecovery({ error, reset, ...props }) {
10
- return _jsx(Storystick, { ...props, resetRenderError: reset, renderErrorDigest: error.digest });
10
+ return _jsx(Storystick, { ...props, recoverServiceFromServer: true, resetRenderError: reset, renderErrorDigest: error.digest });
11
11
  }
@@ -1,6 +1,10 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { readStandaloneStudioUrl } from '@storystick/preview/identity/browser-context';
3
+ import { parseServiceConnection } from '@storystick/types/public-endpoints';
4
+ import { recoverPreviewService, recoverySessionId } from './preview-service.js';
5
+ import { PREVIEW_COPY } from '@storystick/preview/framework/preview-copy';
6
+ import { hasExplicitPreviewBrowserContext } from '@storystick/preview/framework/browser-context';
7
+ import { readStandalonePreviewSessionId, readStandaloneStudioUrl } from '@storystick/preview/identity/browser-context';
4
8
  import { ensureStandalonePreviewView, PreviewViewRecoveryError } from "./preview-view-bootstrap.js";
5
9
  import { isPreviewBrowserContext } from "@storystick/preview/identity/browser-context";
6
10
  import { PreviewStandaloneHost } from "./preview-standalone-host.js";
@@ -42,27 +46,15 @@ function readProjectId(propId) {
42
46
  process.env.STORYSTICK_PROJECT_ID ??
43
47
  null);
44
48
  }
45
- /**
46
- * Build the `resolveInfra()` options from props + (undocumented) env-var
47
- * escape hatches. The two `NEXT_PUBLIC_STORYSTICK_*` env reads are kept
48
- * as escape hatches for self-host customers and Storystick-internal
49
- * Vercel preview deploys ; they are intentionally absent from the
50
- * customer-facing `.env.example` per the C9 direction produit
51
- * ("Convex doit rester transparent au dev").
52
- */
49
+ /** Read public env variables literally so Next can replace them at build time.
50
+ * An active service rejects conflicting legacy URLs. Explicit props remain
51
+ * available for local/self-hosted adapters. */
53
52
  function buildInfraOptions(props) {
54
- const endpoint = props.endpoint ??
55
- process.env.NEXT_PUBLIC_STORYSTICK_GATEWAY_URL ??
56
- undefined;
57
- const convexUrl = props.gatewaySyncUrl ??
58
- process.env.NEXT_PUBLIC_STORYSTICK_GATEWAY_SYNC_URL ??
59
- undefined;
60
- const opts = {};
61
- if (endpoint)
62
- opts.endpoint = endpoint;
63
- if (convexUrl)
64
- opts.convexUrl = convexUrl;
65
- return opts;
53
+ return {
54
+ service: props.service === undefined ? undefined : parseServiceConnection(props.service),
55
+ endpoint: props.endpoint ?? process.env.NEXT_PUBLIC_STORYSTICK_GATEWAY_URL ?? undefined,
56
+ convexUrl: props.gatewaySyncUrl ?? process.env.NEXT_PUBLIC_STORYSTICK_GATEWAY_SYNC_URL ?? undefined,
57
+ };
66
58
  }
67
59
  function readPublishableKey(propKey) {
68
60
  if (propKey)
@@ -229,6 +221,7 @@ export function StorystickPreviewRuntime(props = {}) {
229
221
  // so the iframe sees a consistent (endpoint, convexUrl) pair.
230
222
  const [infra, setInfra] = useState(null);
231
223
  const [bootstrapError, setBootstrapError] = useState(null);
224
+ const [bootstrapSlow, setBootstrapSlow] = useState(false);
232
225
  const [bootstrapAttempt, setBootstrapAttempt] = useState(0);
233
226
  // Initialize the singleton on mount. Idempotent — StrictMode dev
234
227
  // double-mount and HMR are both safe.
@@ -249,43 +242,53 @@ export function StorystickPreviewRuntime(props = {}) {
249
242
  const cv = readCodeVersion(props.codeVersion);
250
243
  window.__STORYSTICK_CODE_VERSION__ = cv;
251
244
  }
252
- const opts = buildInfraOptions(props);
253
245
  const tokenRoute = storystickRouteForBasePath(basePath, STORYSTICK_PREVIEW_TOKEN_ROUTE_PATH);
254
246
  let cancelled = false;
255
- let timedOut = false;
247
+ const recovery = new AbortController();
256
248
  const deadline = setTimeout(() => {
257
- timedOut = true;
258
249
  if (!cancelled)
259
- setBootstrapError('Preview did not respond. Check your connection and retry.');
250
+ setBootstrapSlow(true);
260
251
  }, 10000);
261
252
  setBootstrapError(null);
253
+ setBootstrapSlow(false);
262
254
  void (async () => {
263
255
  try {
256
+ const opts = buildInfraOptions(props);
264
257
  const viewReady = ensureStandalonePreviewView(projectId);
258
+ if (props.recoverServiceFromServer) {
259
+ await viewReady;
260
+ const selected = await recoverPreviewService(tokenRoute, projectId, recoverySessionId(projectId), recovery.signal);
261
+ if (opts.service !== undefined && JSON.stringify(opts.service) !== JSON.stringify(selected))
262
+ throw new Error('Conflicting recovered Preview service.');
263
+ opts.service = selected;
264
+ }
265
265
  // Keep explicit sync configuration fast; discovery and recovery are independent.
266
266
  const discovered = resolveInfra(projectId, opts);
267
267
  const boot = viewReady.then(async () => {
268
- if (opts.convexUrl !== undefined && !cancelled && !timedOut)
268
+ if (opts.service === undefined && opts.convexUrl !== undefined && !cancelled)
269
269
  void previewRuntime.init({ projectId, gatewaySyncUrl: opts.convexUrl, tokenRoute });
270
270
  });
271
271
  const [resolved] = await Promise.all([discovered, boot]);
272
272
  clearTimeout(deadline);
273
- if (cancelled || timedOut)
273
+ if (cancelled)
274
274
  return;
275
275
  setInfra(resolved);
276
- if (opts.convexUrl === undefined)
276
+ if (opts.service !== undefined || opts.convexUrl === undefined)
277
277
  await previewRuntime.init({ projectId, gatewaySyncUrl: resolved.convexUrl, tokenRoute });
278
278
  }
279
279
  catch (err) {
280
280
  if (!cancelled)
281
- setBootstrapError(err instanceof PreviewViewRecoveryError ? err.message : 'Could not reconnect to Preview. Retry when your connection is restored.');
281
+ setBootstrapError(err instanceof PreviewViewRecoveryError ? PREVIEW_COPY['opening-invalid'].body : PREVIEW_COPY['connection-interrupted'].body);
282
282
  }
283
283
  finally {
284
284
  clearTimeout(deadline);
285
+ if (!cancelled)
286
+ setBootstrapSlow(false);
285
287
  }
286
288
  })();
287
289
  return () => {
288
290
  cancelled = true;
291
+ recovery.abort();
289
292
  clearTimeout(deadline);
290
293
  // Strict cleanup is intentionally NOT called here — the
291
294
  // singleton's lifecycle survives unmount/remount cycles
@@ -297,6 +300,10 @@ export function StorystickPreviewRuntime(props = {}) {
297
300
  basePath,
298
301
  props.projectId,
299
302
  props.gatewaySyncUrl,
303
+ props.recoverServiceFromServer,
304
+ props.service?.apiOrigin,
305
+ props.service?.syncOrigin,
306
+ props.service?.studioOrigin,
300
307
  props.endpoint,
301
308
  props.codeVersion,
302
309
  bootstrapAttempt,
@@ -449,6 +456,7 @@ export function StorystickPreviewRuntime(props = {}) {
449
456
  // Every live view observes the same end revision. Clear only that context,
450
457
  // then refresh the native tree; a late tab cannot end a newer activation.
451
458
  const endingContextRef = useRef(null);
459
+ const [exitAttempt, setExitAttempt] = useState(0);
452
460
  useEffect(() => {
453
461
  const context = state.readContext;
454
462
  if (state.readContextStatus !== 'ended' || !context)
@@ -497,7 +505,7 @@ export function StorystickPreviewRuntime(props = {}) {
497
505
  previewRuntime.reportContextExitUnavailable(context);
498
506
  }
499
507
  })();
500
- }, [basePath, router, state.readContext, state.readContextStatus]);
508
+ }, [basePath, router, state.readContext, state.readContextStatus, exitAttempt]);
501
509
  // A projected content checkpoint updates native pages and layouts, including
502
510
  // ordinary reads that returned null/empty. No per-component subscription.
503
511
  useEffect(() => {
@@ -553,9 +561,12 @@ export function StorystickPreviewRuntime(props = {}) {
553
561
  // of static rendering. Mounted on every render path, including the
554
562
  // error branch, so the reverse channel keeps reporting even when
555
563
  // preview state has degraded to `'error'`.
556
- const reporter = (_jsxs(_Fragment, { children: [typeof window !== 'undefined' && window.parent === window && state.state !== 'idle' && (_jsx(Suspense, { fallback: null, children: _jsx(PreviewStandaloneHost, { basePath: basePath, projectId: readProjectId(props.projectId), state: state, recovery: { error: bootstrapError, retry: () => setBootstrapAttempt(n => n + 1) } }) })), _jsx(PreviewProvenanceRuntimeLoader, { enabled: props.previewProvenanceRuntimeEnabled === true, source: props.previewProvenanceRuntimeSrc ??
564
+ const invalidStandaloneLink = typeof window !== 'undefined' && window.parent === window &&
565
+ hasExplicitPreviewBrowserContext(readProjectId(props.projectId) ?? undefined) &&
566
+ readStandalonePreviewSessionId(readProjectId(props.projectId) ?? undefined) === null;
567
+ const reporter = (_jsxs(_Fragment, { children: [typeof window !== 'undefined' && window.parent === window && !invalidStandaloneLink && (state.state !== 'idle' || bootstrapError !== null || bootstrapSlow) && (_jsx(Suspense, { fallback: null, children: _jsx(PreviewStandaloneHost, { basePath: basePath, projectId: readProjectId(props.projectId), state: state, recovery: { error: bootstrapError, pending: bootstrapSlow, retry: () => setBootstrapAttempt(n => n + 1) } }) })), _jsx(PreviewProvenanceRuntimeLoader, { enabled: props.previewProvenanceRuntimeEnabled === true, source: props.previewProvenanceRuntimeSrc ??
557
568
  storystickRouteForBasePath(basePath, STORYSTICK_PREVIEW_PROVENANCE_RUNTIME_ROUTE_PATH), sessionId: state.sessionId }), !props.resetRenderError && _jsx(Suspense, { fallback: null, children: _jsx(PreviewLocationReporter, { basePath: basePath }) })] }));
558
569
  // Keep the controls at a stable React position through terminal failures so
559
570
  // their last validated Studio destination survives a revoked session.
560
- return _jsxs(_Fragment, { children: [state.state === "error" && _jsx(PreviewErrorSurface, { code: state.errorCode, studioUrl: state.standaloneStudioUrl ?? readStandaloneStudioUrl(readProjectId(props.projectId), state.sessionId) }), reporter] });
571
+ return _jsxs(_Fragment, { children: [(invalidStandaloneLink || state.state === "error" && (state.readContext !== null || hasExplicitPreviewBrowserContext(readProjectId(props.projectId) ?? undefined))) && _jsx(PreviewErrorSurface, { code: invalidStandaloneLink ? "PREVIEW_SESSION_MISSING" : state.errorCode, onRetryExit: state.readContextStatus === 'ended' ? () => { endingContextRef.current = null; setExitAttempt(attempt => attempt + 1); } : undefined, studioUrl: state.standaloneStudioUrl ?? readStandaloneStudioUrl(readProjectId(props.projectId), state.sessionId) }), reporter] });
561
572
  }
@@ -1,4 +1,6 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { serverInfraOptions } from './service-config.js';
3
+ import { assertServiceOrigin, parseServiceConnection } from '@storystick/types/public-endpoints';
2
4
  import { Storystick as StorystickClient, } from './storystick-component.js';
3
5
  import { resolveStorystickServerCodeVersion } from './code-version.js';
4
6
  /**
@@ -8,8 +10,8 @@ import { resolveStorystickServerCodeVersion } from './code-version.js';
8
10
  * `codeVersion` prop.
9
11
  */
10
12
  export function Storystick(props = {}) {
11
- const { projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion } = props;
12
- return renderStorystick({ projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion });
13
+ const { projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion, service } = props;
14
+ return renderStorystick({ projectId, endpoint, gatewaySyncUrl, publishableKey, basePath, codeVersion, service });
13
15
  }
14
16
  /** @internal Runtime assembly and targeted tests; not exported by the SDK root. */
15
17
  export function renderStorystick(props = {}) {
@@ -17,7 +19,15 @@ export function renderStorystick(props = {}) {
17
19
  const includePreviewProvenanceRuntime = previewProvenanceRuntime ?? true;
18
20
  const includePreviewLiveQueryOverlay = previewLiveQueryOverlay ??
19
21
  process.env.STORYSTICK_PREVIEW_LIVE_QUERY_OVERLAY === '1';
20
- return (_jsx(StorystickClient, { ...clientProps, codeVersion: resolveStorystickServerCodeVersion({
22
+ const configured = serverInfraOptions();
23
+ const selected = clientProps.service === undefined ? configured.service : parseServiceConnection(clientProps.service);
24
+ if (configured.service && selected && JSON.stringify(configured.service) !== JSON.stringify(selected))
25
+ throw new TypeError('Conflicting server and component services.');
26
+ if (selected) {
27
+ assertServiceOrigin(clientProps.endpoint, selected.apiOrigin);
28
+ assertServiceOrigin(clientProps.gatewaySyncUrl, selected.syncOrigin);
29
+ }
30
+ return (_jsx(StorystickClient, { ...clientProps, service: selected, codeVersion: resolveStorystickServerCodeVersion({
21
31
  codeVersion: clientProps.codeVersion,
22
32
  }), previewProvenanceRuntimeEnabled: includePreviewProvenanceRuntime, previewProvenanceRuntimeSrc: previewProvenanceRuntimeSrc, previewLiveQueryOverlayEnabled: includePreviewLiveQueryOverlay }));
23
33
  }
package/dist/testing.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { serverInfraOptions } from './service-config.js';
1
2
  import 'server-only';
2
3
  import { createInternalClient } from '@storystick/client/internal';
3
4
  import { resolveInfra } from '@storystick/client/adapter';
@@ -11,12 +12,7 @@ const CONTROL_QUERY_SCHEMA = {
11
12
  export async function _buildBuildTimeClient() {
12
13
  const projectId = requiredEnv('STORYSTICK_PROJECT_ID');
13
14
  const apiKey = requiredEnv('STORYSTICK_API_KEY');
14
- const endpoint = process.env.STORYSTICK_ENDPOINT;
15
- const convexUrl = process.env.STORYSTICK_CONVEX_URL;
16
- const infra = await resolveInfra(projectId, {
17
- ...(endpoint ? { endpoint } : {}),
18
- ...(convexUrl ? { convexUrl } : {}),
19
- });
15
+ const infra = await resolveInfra(projectId, serverInfraOptions());
20
16
  return createInternalClient({
21
17
  schema: CONTROL_QUERY_SCHEMA,
22
18
  projectId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storystick/next",
3
- "version": "0.2.0-rc.1",
3
+ "version": "0.2.0-rc.3",
4
4
  "license": "FSL-1.1-MIT",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -82,17 +82,17 @@
82
82
  "tag": "beta"
83
83
  },
84
84
  "peerDependencies": {
85
- "next": "^15.5.28",
85
+ "next": "^15.5.28 || ^16.2.9",
86
86
  "react": "^19.2.8",
87
87
  "react-dom": "^19.2.8"
88
88
  },
89
89
  "dependencies": {
90
90
  "server-only": "^0.0.1",
91
- "@storystick/client": "0.2.0-rc.1",
92
- "@storystick/media": "0.2.0-rc.1",
93
- "@storystick/react": "0.2.0-rc.1",
94
- "@storystick/preview": "0.2.0-rc.1",
95
- "@storystick/types": "0.1.0-rc.1"
91
+ "@storystick/client": "0.2.0-rc.3",
92
+ "@storystick/media": "0.2.0-rc.3",
93
+ "@storystick/react": "0.2.0-rc.3",
94
+ "@storystick/types": "0.1.0-rc.3",
95
+ "@storystick/preview": "0.2.0-rc.3"
96
96
  },
97
97
  "devDependencies": {
98
98
  "@testing-library/react": "^16.3.2",
@@ -109,7 +109,7 @@
109
109
  "sharp": "0.35.5"
110
110
  },
111
111
  "engines": {
112
- "node": ">=24.19.0 <25"
112
+ "node": "^22.13.0 || ^24.19.0"
113
113
  },
114
114
  "repository": {
115
115
  "type": "git",
@@ -120,6 +120,9 @@
120
120
  "bugs": {
121
121
  "url": "https://storystick.app"
122
122
  },
123
+ "storystick": {
124
+ "serviceConfigVersion": 1
125
+ },
123
126
  "scripts": {
124
127
  "build": "node ../../scripts/package-dist.mjs clean && tsc && node ../../scripts/package-dist.mjs seal",
125
128
  "test": "vitest run",