@storystick/client 0.2.0-rc.2 → 0.2.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/PUBLIC-API.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @storystick/client API contract
2
2
 
3
- Install this candidate explicitly with `@storystick/client@0.2.0-rc.2` 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/client@0.2.0-rc.4` 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.2, cohort `sdk-0.2.0-rc.2`. ESM distribution; no CommonJS or universal Edge compatibility is promised.
5
+ Version 0.2.0-rc.4, cohort `sdk-0.2.0-rc.4`. 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
 
@@ -15,7 +15,7 @@ This package is a product integration facade. Reserved contracts are required be
15
15
  | `./adapter` | Reserved SDK contract |
16
16
  | `./seo` | Supported beta entry |
17
17
 
18
- 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.
18
+ 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.
19
19
 
20
20
  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.
21
21
 
package/README.md CHANGED
@@ -177,5 +177,14 @@ code does not inherit deployment or Studio concepts.
177
177
  ## Candidate distribution contract
178
178
 
179
179
  See [PUBLIC-API.md](./PUBLIC-API.md) for supported entries, reserved SDK contracts,
180
- the qualified runtime matrix and the candidate cohort. Upgrade Storystick
181
- packages together.
180
+ the qualified runtime matrix and the candidate cohort. Keep shared contracts
181
+ compatible. Use the [release guide](../../release/README.md) to select the
182
+ packages and consumers that need an update; an independent adapter fix does
183
+ not require republishing every package.
184
+
185
+ ## Hosted connection
186
+
187
+ Clients use the public production service by default. Framework adapters manage
188
+ service discovery; application content code needs no infrastructure URL or
189
+ platform environment selector. A key's live/test scope is independent of the
190
+ service destination.
package/dist/.source-hash CHANGED
@@ -1 +1 @@
1
- e84684ca7440a20c446216db7c677941f4f4df2daab67911c8f0e9a1f2876aca
1
+ afc37ed09e83e62c0c5d75a393c056760e8274d36e1257bf4fdaf7c8f39f11e3
package/dist/index.d.ts CHANGED
@@ -21,3 +21,5 @@ export type { ReferenceDocument, ResolveReferenceOptions, ResolvedReference, } f
21
21
  export type { QueryRouteAccessors, QueryRoutePathAccessor } from './query-builder.js';
22
22
  export type { PublicLocaleOrigins } from './locale-routing.js';
23
23
  export type { SchemaStoryName, RoutableSchemaStoryName, RequestedStoryName, TypedRouteDocument, TypedDocumentRoute, ResolvedRouteForSchema } from './typed-route.js';
24
+ export { preloadQuery } from './query-snapshot.js';
25
+ export type { QuerySnapshot } from './query-snapshot.js';
package/dist/index.js CHANGED
@@ -7,3 +7,4 @@ export { StorystickError, QueryExecutionError } from './errors.js';
7
7
  export { normalizePathname, pathnameToHref, pathnameToSegments, segmentsToPathname, } from './normalize-pathname.js';
8
8
  export { publicHrefForLocale, publishedLocaleHrefs, normalizePublicLocaleOrigins, prefixHref, publicPathnameForLocale, resolveLocalePathname } from './locale-routing.js';
9
9
  export { resolveReference, resolveReferences } from './reference-resolver.js';
10
+ export { preloadQuery } from './query-snapshot.js';
@@ -1,94 +1,17 @@
1
- /**
2
- * Infrastructure URL resolution — ADR-131 C9.
3
- *
4
- * Centralizes derivation of the three Convex-flavoured URLs the customer-
5
- * bundled SDK packages need at runtime :
6
- *
7
- * - `endpoint` — gateway HTTP root, `.convex.site` form. Hosts the
8
- * custom HTTP routes (JWKS, Pattern-D queries).
9
- * - `convexUrl` — standard Convex RPC + WebSocket sync URL, `.convex.cloud`
10
- * form. Used by `ConvexReactClient` (WS) and the server-
11
- * side `ConvexHttpClient` (preview session lookup,
12
- * observation tap mutation).
13
- * - `jwksUrl` — `${endpoint}/api/jwks.json` by default.
14
- *
15
- * Cascade (per URL, independent) :
16
- *
17
- * 1. Explicit `options.*Url` — call-site override (props, env vars read
18
- * by the adapter and forwarded as options, factory args).
19
- * 2. Auto-derive from `resolveProject(projectId).endpoint`.
20
- * 3. Fail-loud — `resolveProject` throws a typed `StorystickError` if
21
- * the gateway returns 404/503/network error.
22
- *
23
- * The single `resolveProject` round-trip is shared across the three URLs ;
24
- * subsequent calls hit the per-process cache (server) or sessionStorage
25
- * cache (browser).
26
- *
27
- * **Env vars are NOT read here.** The bundler-replace behaviour of
28
- * `process.env.NEXT_PUBLIC_*` requires literal property access in the
29
- * adapter package (Next/React) so the static replacement at build time
30
- * resolves the value into the browser bundle. Adapters call this helper
31
- * after reading their respective env vars and forwarding them as options.
32
- *
33
- * Direction produit (owner 2026-05-26 PM) :
34
- *
35
- * > "Convex doit rester transparent au dev. Hors de question qu'une env
36
- * > var mentionnant convex.cloud / .site / etc apparaisse côté customer."
37
- *
38
- * The 5-var customer allowlist is `STORYSTICK_PROJECT_ID`, `STORYSTICK_API_KEY`,
39
- * `NEXT_PUBLIC_STORYSTICK_PROJECT_ID`, `NEXT_PUBLIC_STORYSTICK_PUBLISHABLE_KEY`,
40
- * `NEXT_PUBLIC_STORYSTICK_STUDIO_ORIGIN`. All Convex-flavoured URLs are
41
- * derived from `projectId` via this module.
42
- * Resource-storage bucket credentials belong exclusively to the server-side
43
- * storage resolver; they are never customer env vars or resolver options.
44
- */
1
+ /** Resolve hosted infrastructure from public discovery. Explicit URLs are for local/self-hosted use. */
2
+ import { type ServiceConnection } from '@storystick/types/public-endpoints';
45
3
  export interface ResolveInfraOptions {
46
- /** Explicit endpoint override (gateway HTTP root, `.convex.site`). */
4
+ service?: ServiceConnection;
47
5
  endpoint?: string;
48
- /** Explicit Convex RPC URL override (`.convex.cloud`). */
49
6
  convexUrl?: string;
50
- /** Explicit JWKS URL override. */
51
7
  jwksUrl?: string;
52
- /**
53
- * Optional gateway URL passed through to `resolveProject()` for self-host
54
- * overrides. Unused by default ; resolution falls back to
55
- * `DEFAULT_GATEWAY_URL` inside `resolve.ts`.
56
- */
57
8
  gatewayUrl?: string;
58
9
  }
59
10
  export interface ResolvedInfra {
60
- /** Gateway HTTP root (`.convex.site` form). HTTP custom routes + JWKS. */
61
11
  endpoint: string;
62
- /** Convex RPC / WS URL (`.convex.cloud` form). */
12
+ /** Internal adapter name; hosted connections use the public sync service. */
63
13
  convexUrl: string;
64
- /** JWKS endpoint (default `${endpoint}/api/jwks.json`). */
65
14
  jwksUrl: string;
66
15
  }
67
- /**
68
- * Synchronously derive `ResolvedInfra` when `endpoint` is already known
69
- * (explicit prop or env override). Used by adapters that need an
70
- * initial value during render — e.g. `<StorystickQueryProvider>`
71
- * synchronously seeds its `infra` state when all required values are
72
- * explicit, so generated clients can execute on the first render
73
- * inside an immediately-available `ConvexProvider` (codex R2 P2 fix).
74
- *
75
- * Returns `null` when `endpoint` is missing (gateway round-trip needed).
76
- */
77
16
  export declare function resolveInfraSync(options?: ResolveInfraOptions): ResolvedInfra | null;
78
- /**
79
- * Resolve the three infrastructure URLs for `projectId`.
80
- *
81
- * Idempotent + cache-aware — repeated calls with the same `projectId` reuse
82
- * the `resolveProject` cache (per-process Map server-side, sessionStorage
83
- * browser-side). Safe to call eagerly at module init.
84
- *
85
- * The `resolveProject` round-trip happens only when no explicit endpoint
86
- * override is supplied — `convexUrl` + `jwksUrl` are pure transforms on
87
- * `endpoint`. If `endpoint` is provided (prop or env escape hatch), the
88
- * helper completes without any network call ; gateway failures cannot
89
- * stall the boot path in that case.
90
- *
91
- * Throws (propagates) the `StorystickError` from `resolveProject` when the
92
- * gateway returns 404/503/network error AND no explicit `endpoint` is set.
93
- */
94
17
  export declare function resolveInfra(projectId: string, options?: ResolveInfraOptions): Promise<ResolvedInfra>;
@@ -1,130 +1,44 @@
1
- /**
2
- * Infrastructure URL resolution — ADR-131 C9.
3
- *
4
- * Centralizes derivation of the three Convex-flavoured URLs the customer-
5
- * bundled SDK packages need at runtime :
6
- *
7
- * - `endpoint` — gateway HTTP root, `.convex.site` form. Hosts the
8
- * custom HTTP routes (JWKS, Pattern-D queries).
9
- * - `convexUrl` — standard Convex RPC + WebSocket sync URL, `.convex.cloud`
10
- * form. Used by `ConvexReactClient` (WS) and the server-
11
- * side `ConvexHttpClient` (preview session lookup,
12
- * observation tap mutation).
13
- * - `jwksUrl` — `${endpoint}/api/jwks.json` by default.
14
- *
15
- * Cascade (per URL, independent) :
16
- *
17
- * 1. Explicit `options.*Url` — call-site override (props, env vars read
18
- * by the adapter and forwarded as options, factory args).
19
- * 2. Auto-derive from `resolveProject(projectId).endpoint`.
20
- * 3. Fail-loud — `resolveProject` throws a typed `StorystickError` if
21
- * the gateway returns 404/503/network error.
22
- *
23
- * The single `resolveProject` round-trip is shared across the three URLs ;
24
- * subsequent calls hit the per-process cache (server) or sessionStorage
25
- * cache (browser).
26
- *
27
- * **Env vars are NOT read here.** The bundler-replace behaviour of
28
- * `process.env.NEXT_PUBLIC_*` requires literal property access in the
29
- * adapter package (Next/React) so the static replacement at build time
30
- * resolves the value into the browser bundle. Adapters call this helper
31
- * after reading their respective env vars and forwarding them as options.
32
- *
33
- * Direction produit (owner 2026-05-26 PM) :
34
- *
35
- * > "Convex doit rester transparent au dev. Hors de question qu'une env
36
- * > var mentionnant convex.cloud / .site / etc apparaisse côté customer."
37
- *
38
- * The 5-var customer allowlist is `STORYSTICK_PROJECT_ID`, `STORYSTICK_API_KEY`,
39
- * `NEXT_PUBLIC_STORYSTICK_PROJECT_ID`, `NEXT_PUBLIC_STORYSTICK_PUBLISHABLE_KEY`,
40
- * `NEXT_PUBLIC_STORYSTICK_STUDIO_ORIGIN`. All Convex-flavoured URLs are
41
- * derived from `projectId` via this module.
42
- * Resource-storage bucket credentials belong exclusively to the server-side
43
- * storage resolver; they are never customer env vars or resolver options.
44
- */
1
+ /** Resolve hosted infrastructure from public discovery. Explicit URLs are for local/self-hosted use. */
2
+ import { DEFAULT_SERVICE_CONNECTION, parseServiceConnection, assertServiceOrigin } from '@storystick/types/public-endpoints';
45
3
  import { resolveProject } from './resolve.js';
46
- const JWKS_PATH = '/api/jwks.json';
47
- /**
48
- * Swap `.convex.site` → `.convex.cloud` on a Convex deployment URL. Returns
49
- * the input unchanged for non-Convex-Cloud deployments (self-host) — the
50
- * customer sets `convexUrl` explicitly in that case.
51
- *
52
- * **CSO trade-off (codex R2 P1, accepted per ADR-131 C9 brief direction
53
- * produit) :** the default `convexUrl` resolves to a raw `.convex.cloud`
54
- * deployment URL, bypassing the sub-gateway Worker (`services/sub-gateway/`).
55
- * Pre-C9, the default was `http://localhost:8787` (dev Worker URL) and
56
- * customers in prod were expected to set
57
- * `NEXT_PUBLIC_STORYSTICK_GATEWAY_SYNC_URL` explicitly — usually to the
58
- * Worker public URL (e.g. `https://gateway.storystick.app`). The Worker
59
- * is not deployed yet (5 Path B manual steps in
60
- * `services/sub-gateway/wrangler.toml`), so the spike-Vercel Fix 2 already
61
- * documents `.convex.cloud` direct as the only working posture today.
62
- *
63
- * Once the Worker is deployed, replace this default with the Worker
64
- * public URL constant ; the rest of the cascade is unchanged. The
65
- * explicit `options.convexUrl` override remains the escape hatch for
66
- * customers needing to bypass the constant (self-host, internal Vercel
67
- * deploys, etc.).
68
- *
69
- * See `storystick-hq/notes/adr-131-chantier/c9-hidden-vars-audit.md` §9
70
- * for the deferred-follow-up list.
71
- */
72
- function gatewayToConvex(endpoint) {
73
- if (endpoint.includes('.convex.site')) {
74
- return endpoint.replace('.convex.site', '.convex.cloud');
75
- }
76
- return endpoint;
77
- }
78
- function stripTrailingSlash(url) {
79
- return url.replace(/\/$/, '');
4
+ function syncForExplicitEndpoint(endpoint) {
5
+ if (endpoint === DEFAULT_SERVICE_CONNECTION.apiOrigin)
6
+ return DEFAULT_SERVICE_CONNECTION.syncOrigin;
7
+ // Only explicitly selected local/self-hosted deployments use this convention.
8
+ const url = new URL(endpoint);
9
+ if (url.hostname.endsWith('.convex.site'))
10
+ url.hostname = url.hostname.replace(/\.convex\.site$/, '.convex.cloud');
11
+ return url.toString().replace(/\/$/, '');
80
12
  }
81
- /**
82
- * Synchronously derive `ResolvedInfra` when `endpoint` is already known
83
- * (explicit prop or env override). Used by adapters that need an
84
- * initial value during render — e.g. `<StorystickQueryProvider>`
85
- * synchronously seeds its `infra` state when all required values are
86
- * explicit, so generated clients can execute on the first render
87
- * inside an immediately-available `ConvexProvider` (codex R2 P2 fix).
88
- *
89
- * Returns `null` when `endpoint` is missing (gateway round-trip needed).
90
- */
91
13
  export function resolveInfraSync(options = {}) {
14
+ if (options.service !== undefined) {
15
+ const service = parseServiceConnection(options.service);
16
+ assertServiceOrigin(options.endpoint, service.apiOrigin);
17
+ assertServiceOrigin(options.gatewayUrl, service.apiOrigin);
18
+ assertServiceOrigin(options.convexUrl, service.syncOrigin);
19
+ if (options.jwksUrl !== undefined && options.jwksUrl !== `${service.apiOrigin}/api/jwks.json`)
20
+ throw new TypeError('Service configuration conflicts with JWKS URL.');
21
+ return null; // Keep discovery validation, including before using cached results.
22
+ }
92
23
  if (options.endpoint === undefined)
93
24
  return null;
94
- const endpoint = stripTrailingSlash(options.endpoint);
95
- const convexUrl = stripTrailingSlash(options.convexUrl ?? gatewayToConvex(endpoint));
96
- const jwksUrl = options.jwksUrl !== undefined ? options.jwksUrl : `${endpoint}${JWKS_PATH}`;
97
- return { endpoint, convexUrl, jwksUrl };
25
+ const endpoint = options.endpoint.replace(/\/$/, '');
26
+ return {
27
+ endpoint,
28
+ convexUrl: (options.convexUrl ?? syncForExplicitEndpoint(endpoint)).replace(/\/$/, ''),
29
+ jwksUrl: options.jwksUrl ?? `${endpoint}/api/jwks.json`,
30
+ };
98
31
  }
99
- /**
100
- * Resolve the three infrastructure URLs for `projectId`.
101
- *
102
- * Idempotent + cache-aware — repeated calls with the same `projectId` reuse
103
- * the `resolveProject` cache (per-process Map server-side, sessionStorage
104
- * browser-side). Safe to call eagerly at module init.
105
- *
106
- * The `resolveProject` round-trip happens only when no explicit endpoint
107
- * override is supplied — `convexUrl` + `jwksUrl` are pure transforms on
108
- * `endpoint`. If `endpoint` is provided (prop or env escape hatch), the
109
- * helper completes without any network call ; gateway failures cannot
110
- * stall the boot path in that case.
111
- *
112
- * Throws (propagates) the `StorystickError` from `resolveProject` when the
113
- * gateway returns 404/503/network error AND no explicit `endpoint` is set.
114
- */
115
32
  export async function resolveInfra(projectId, options = {}) {
116
- // The gateway round-trip is needed only when we don't already know the
117
- // endpoint — convexUrl + jwksUrl are pure transforms on it. Explicit
118
- // endpoint prop alone is enough to skip the round-trip.
119
- let endpointSource = options.endpoint;
120
- if (endpointSource === undefined) {
121
- const config = await resolveProject(projectId, options.gatewayUrl);
122
- endpointSource = config.endpoint;
123
- }
124
- const endpoint = stripTrailingSlash(endpointSource);
125
- const convexUrl = stripTrailingSlash(options.convexUrl ?? gatewayToConvex(endpoint));
126
- const jwksUrl = options.jwksUrl !== undefined
127
- ? options.jwksUrl
128
- : `${endpoint}${JWKS_PATH}`;
129
- return { endpoint, convexUrl, jwksUrl };
33
+ const explicit = resolveInfraSync(options);
34
+ if (explicit)
35
+ return explicit;
36
+ const service = options.service === undefined ? undefined : parseServiceConnection(options.service);
37
+ const gateway = service?.apiOrigin ?? options.gatewayUrl ?? DEFAULT_SERVICE_CONNECTION.apiOrigin;
38
+ const config = await resolveProject(projectId, gateway, service);
39
+ return {
40
+ endpoint: config.endpoint.replace(/\/$/, ''),
41
+ convexUrl: (service?.syncOrigin ?? options.convexUrl ?? config.syncEndpoint ?? syncForExplicitEndpoint(config.endpoint)).replace(/\/$/, ''),
42
+ jwksUrl: options.jwksUrl ?? `${config.endpoint.replace(/\/$/, '')}/api/jwks.json`,
43
+ };
130
44
  }
@@ -31,3 +31,4 @@ export * from './hydrate-slice.js';
31
31
  export * from './content-values.js';
32
32
  export { attachPreviewQueryReceipt } from './preview-query-receipt.js';
33
33
  export type { RequestContext, PreviewReadScopeEcho, PreviewProvenanceReadLifecycle, PreviewProvenanceReadLifecycleInput, Transport, TransportRequest, } from './types.js';
34
+ export { readQuerySnapshot } from './query-snapshot.js';
package/dist/internal.js CHANGED
@@ -18,3 +18,4 @@ export { previewAssetDependenciesFromValue } from './preview-frame-dependencies.
18
18
  export * from './hydrate-slice.js';
19
19
  export * from './content-values.js';
20
20
  export { attachPreviewQueryReceipt } from './preview-query-receipt.js';
21
+ export { readQuerySnapshot } from './query-snapshot.js';
@@ -1,3 +1,4 @@
1
+ import { type ServiceConnection } from '@storystick/types/public-endpoints';
1
2
  import type { PreviewReadContext } from '@storystick/types/preview-query-targeting';
2
3
  import type { ClientAuth, DefaultRequestOptions, RequestContext, Transport, PublicTransport } from './types.js';
3
4
  import { type QueryExecutionHost, type QueryForSchema } from './query-builder.js';
@@ -7,6 +8,7 @@ export type ClientOptions<TSchema extends QuerySchemaDefinition> = ClientAuth &
7
8
  readonly schema: TSchema;
8
9
  readonly projectId: string;
9
10
  readonly endpoint?: string;
11
+ readonly service?: ServiceConnection;
10
12
  /** Explicit public Query V2 gateway; control and Preview keep endpoint. */
11
13
  readonly deliveryEndpoint?: string;
12
14
  /** Customer application build identity for generation-paired reads. */
@@ -26,6 +28,7 @@ export type InternalClientOptions<TSchema extends QuerySchemaDefinition> = Clien
26
28
  readonly requestContext?: RequestContext;
27
29
  };
28
30
  export interface InternalClientRuntime {
31
+ readonly readServiceIdentity: string;
29
32
  readonly contextEpoch: string;
30
33
  readonly executionHost: QueryExecutionHost;
31
34
  readonly transport: Transport;
@@ -1,4 +1,4 @@
1
- import { STORYSTICK_GATEWAY_ORIGIN } from '@storystick/types/public-endpoints';
1
+ import { DEFAULT_SERVICE_CONNECTION, parseServiceConnection, assertServiceOrigin } from '@storystick/types/public-endpoints';
2
2
  import { isExactPublicQueryResultV2 } from '@storystick/types/delivery-contract';
3
3
  import { attachPublicReadIdentity } from './public-delivery.js';
4
4
  import { createHttpTransportV2, assertResponseProject, assertProjectMatch, } from './transport.js';
@@ -51,11 +51,10 @@ export function bindClientSchemaToAuthority(authority, schema) {
51
51
  defaults: runtime.defaults,
52
52
  localeRouting: runtime.localeRouting,
53
53
  });
54
- const bound = createClientWithTransport(options, runtime.transport);
54
+ const bound = createClientWithTransport(options, runtime.transport, runtime.readServiceIdentity);
55
55
  schemas.set(schema, bound);
56
56
  return bound;
57
57
  }
58
- const DEFAULT_GATEWAY_URL = STORYSTICK_GATEWAY_ORIGIN;
59
58
  export function createClient(options) {
60
59
  // An untyped caller cannot opt into internal Preview authority through this entry.
61
60
  return createInternalClient({ ...options, requestContext: undefined });
@@ -64,7 +63,7 @@ export function createInternalClient(options) {
64
63
  const normalized = normalizeClientOptions(options);
65
64
  const sourceTransport = normalized.transport ?? createHttpTransportV2({
66
65
  projectId: normalized.projectId,
67
- endpoint: normalized.endpoint ?? DEFAULT_GATEWAY_URL,
66
+ endpoint: normalized.endpoint ?? normalized.service?.apiOrigin ?? DEFAULT_SERVICE_CONNECTION.apiOrigin,
68
67
  deliveryEndpoint: normalized.deliveryEndpoint,
69
68
  apiKey: normalized.apiKey ?? normalized.publishableKey,
70
69
  applicationBuildId: normalized.applicationBuildId,
@@ -73,6 +72,14 @@ export function createInternalClient(options) {
73
72
  }
74
73
  function normalizeClientOptions(options) {
75
74
  validateSchema(options.schema);
75
+ if (options.service !== undefined) {
76
+ const service = parseServiceConnection(options.service);
77
+ assertServiceOrigin(options.endpoint, service.apiOrigin);
78
+ assertServiceOrigin(options.deliveryEndpoint, service.apiOrigin);
79
+ if (options.transport !== undefined)
80
+ throw new TypeError('A service-bound client cannot override its transport.');
81
+ options = { ...options, service };
82
+ }
76
83
  if (options.localeRouting?.publicOrigins) {
77
84
  for (const locale of options.localeRouting.locales) {
78
85
  if (locale.enabled && !options.localeRouting.publicOrigins[locale.code]) {
@@ -88,7 +95,10 @@ function normalizeClientOptions(options) {
88
95
  return options;
89
96
  }
90
97
  /** Schema rebinding reuses authority; only the outer factory selects HTTP. */
91
- function createClientWithTransport(options, sourceTransport) {
98
+ function createClientWithTransport(options, sourceTransport, readServiceIdentity = JSON.stringify([
99
+ options.endpoint ?? options.service?.apiOrigin ?? DEFAULT_SERVICE_CONNECTION.apiOrigin,
100
+ options.deliveryEndpoint ?? options.endpoint ?? options.service?.apiOrigin ?? DEFAULT_SERVICE_CONNECTION.apiOrigin,
101
+ ])) {
92
102
  const transport = {
93
103
  async request(input) {
94
104
  assertProjectMatch(input.expectedProjectId ?? options.projectId, options.projectId);
@@ -122,7 +132,7 @@ function createClientWithTransport(options, sourceTransport) {
122
132
  kind,
123
133
  cacheKey: createPreviewProvenanceReadCacheKey(kind, {
124
134
  projectId: options.projectId,
125
- endpoint: options.endpoint ?? DEFAULT_GATEWAY_URL,
135
+ endpoint: options.endpoint ?? options.service?.apiOrigin ?? DEFAULT_SERVICE_CONNECTION.apiOrigin,
126
136
  authority: previewReadCacheAuthority(options.requestContext),
127
137
  query: canonical,
128
138
  options: requestOptions,
@@ -181,6 +191,7 @@ function createClientWithTransport(options, sourceTransport) {
181
191
  },
182
192
  };
183
193
  CLIENT_RUNTIMES.set(client, {
194
+ readServiceIdentity,
184
195
  contextEpoch,
185
196
  executionHost,
186
197
  transport,
@@ -0,0 +1,25 @@
1
+ import type { QueryPageInfo, QueryResult } from '@storystick/types/query-contract';
2
+ import { type QueryExecuteOptions } from './query-builder.js';
3
+ import { type Client } from './query-client.js';
4
+ /** A render seed, not an access grant or proof of a browser read. */
5
+ export interface QuerySnapshot<TData, TPageInfo extends QueryPageInfo | null = QueryPageInfo | null> {
6
+ readonly version: 1;
7
+ readonly projectId: string;
8
+ readonly schemaFingerprint: string;
9
+ readonly canonical: string;
10
+ readonly readServiceIdentity: string;
11
+ readonly preview: null | {
12
+ readonly contextId: string;
13
+ readonly revision: number;
14
+ };
15
+ readonly result: QueryResult<TData, TPageInfo>;
16
+ }
17
+ /** Execute once on the server; pass this plain JSON value to useQuery's initialData. */
18
+ export declare function preloadQuery<TData, TPageInfo extends QueryPageInfo | null>(query: {
19
+ compile(): {
20
+ readonly canonical: string;
21
+ };
22
+ execute(options?: QueryExecuteOptions): Promise<QueryResult<TData, TPageInfo>>;
23
+ }, options?: QueryExecuteOptions): Promise<QuerySnapshot<TData, TPageInfo>>;
24
+ /** @internal Validate identity before using an RSC seed in a query store. */
25
+ export declare function readQuerySnapshot<TData, TPageInfo extends QueryPageInfo | null>(snapshot: QuerySnapshot<TData, TPageInfo> | undefined, client: Client, canonical: string): QueryResult<TData, TPageInfo> | undefined;
@@ -0,0 +1,38 @@
1
+ import { assertExactQueryResult } from './errors.js';
2
+ import { rawContentValues, prepareContentValues } from './content-values.js';
3
+ import { getExecutableQueryDescriptor } from './query-builder.js';
4
+ import { getInternalClientRuntime } from './query-client.js';
5
+ /** Execute once on the server; pass this plain JSON value to useQuery's initialData. */
6
+ export async function preloadQuery(query, options) {
7
+ const client = getExecutableQueryDescriptor(query).host.client;
8
+ const context = getInternalClientRuntime(client).requestContext;
9
+ const read = context?.previewReadContext;
10
+ if (context?.previewToken && !read) {
11
+ throw new TypeError('A Preview query snapshot requires a bound read context.');
12
+ }
13
+ const result = await query.execute(options);
14
+ assertExactQueryResult(result);
15
+ // Strip process-local identities and WeakMap receipts deliberately. A mounted
16
+ // browser query obtains its own receipt; serialized data never authorizes I/O.
17
+ return JSON.parse(JSON.stringify({
18
+ version: 1,
19
+ projectId: client.projectId,
20
+ schemaFingerprint: client.schema.fingerprint,
21
+ canonical: query.compile().canonical,
22
+ readServiceIdentity: getInternalClientRuntime(client).readServiceIdentity,
23
+ preview: read ? { contextId: read.contextId, revision: read.revision } : null,
24
+ result: rawContentValues(result),
25
+ }));
26
+ }
27
+ /** @internal Validate identity before using an RSC seed in a query store. */
28
+ export function readQuerySnapshot(snapshot, client, canonical) {
29
+ if (!snapshot)
30
+ return undefined;
31
+ if (snapshot.version !== 1 || snapshot.projectId !== client.projectId ||
32
+ snapshot.schemaFingerprint !== client.schema.fingerprint || snapshot.canonical !== canonical ||
33
+ snapshot.readServiceIdentity !== getInternalClientRuntime(client).readServiceIdentity) {
34
+ throw new TypeError('The query snapshot belongs to a different query, project, schema or service.');
35
+ }
36
+ assertExactQueryResult(snapshot.result);
37
+ return prepareContentValues(snapshot.result, true, snapshot.preview !== null);
38
+ }
package/dist/resolve.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type ServiceConnection } from '@storystick/types/public-endpoints';
1
2
  /**
2
3
  * Project shortId resolution
3
4
  *
@@ -24,6 +25,7 @@ export interface ProjectConfig {
24
25
  /** Storystick gateway endpoint.
25
26
  * Same URL for every project on this Storystick deployment. */
26
27
  readonly endpoint: string;
28
+ readonly syncEndpoint?: string;
27
29
  /** Public project identifier — the 8-char Crockford shortId that
28
30
  * appears in URLs, SDK env config, API key prefixes, logs. */
29
31
  readonly projectId: string;
@@ -40,4 +42,4 @@ export interface ProjectConfig {
40
42
  * const config = await resolveProject('a3k9m2x7')
41
43
  * // → { endpoint: 'https://...', projectId: 'a3k9m2x7', plan: 'free', ... }
42
44
  */
43
- export declare function resolveProject(projectId: string, gatewayUrl?: string): Promise<ProjectConfig>;
45
+ export declare function resolveProject(projectId: string, gatewayUrl?: string, selectedService?: ServiceConnection): Promise<ProjectConfig>;
package/dist/resolve.js CHANGED
@@ -1,9 +1,9 @@
1
- import { STORYSTICK_GATEWAY_ORIGIN } from '@storystick/types/public-endpoints';
1
+ import { STORYSTICK_GATEWAY_ORIGIN, DEFAULT_SERVICE_CONNECTION, parseServiceConnection, assertServiceOrigin } from '@storystick/types/public-endpoints';
2
2
  // ─────────────────────────────────────────────
3
3
  // Constants
4
4
  // ─────────────────────────────────────────────
5
5
  const DEFAULT_GATEWAY_URL = STORYSTICK_GATEWAY_ORIGIN;
6
- const PROJECT_CACHE_PREFIX = 'storystick:project:v1:';
6
+ const PROJECT_CACHE_PREFIX = 'storystick:project:v2:';
7
7
  const PROJECT_CACHE_TTL_MS = 5 * 60 * 1000;
8
8
  // Module-level cache for server-side (bounded and refreshed after five minutes)
9
9
  const PROJECT_CACHE_MAX_ENTRIES = 128;
@@ -21,8 +21,19 @@ const inFlight = new Map();
21
21
  * const config = await resolveProject('a3k9m2x7')
22
22
  * // → { endpoint: 'https://...', projectId: 'a3k9m2x7', plan: 'free', ... }
23
23
  */
24
- export async function resolveProject(projectId, gatewayUrl) {
25
- const gateway = gatewayUrl ?? DEFAULT_GATEWAY_URL;
24
+ export async function resolveProject(projectId, gatewayUrl, selectedService) {
25
+ const service = selectedService === undefined
26
+ ? (gatewayUrl === undefined || gatewayUrl === DEFAULT_GATEWAY_URL ? DEFAULT_SERVICE_CONNECTION : undefined)
27
+ : parseServiceConnection(selectedService);
28
+ if (service)
29
+ assertServiceOrigin(gatewayUrl, service.apiOrigin);
30
+ const gateway = gatewayUrl ?? service?.apiOrigin ?? DEFAULT_GATEWAY_URL;
31
+ const checked = (config) => {
32
+ if (service && (config.endpoint !== service.apiOrigin || config.syncEndpoint !== service.syncOrigin)) {
33
+ throw new Error('StorystickError: Project discovery returned an unexpected service origin.');
34
+ }
35
+ return config;
36
+ };
26
37
  // ADR-131 C9 codex R3 P2 fix : the cache key must include the gateway
27
38
  // URL so that a self-host customer passing a non-default `gatewayUrl`
28
39
  // does not get the default-gateway-resolved config back from the cache.
@@ -31,25 +42,25 @@ export async function resolveProject(projectId, gatewayUrl) {
31
42
  const cacheKey = `${projectId}::${gateway}`;
32
43
  const cached = getFromCache(cacheKey, projectId);
33
44
  if (cached)
34
- return cached;
45
+ return checked(cached);
35
46
  const pending = inFlight.get(cacheKey);
36
47
  if (pending)
37
- return pending;
38
- const request = fetchProject(projectId, gateway, cacheKey);
48
+ return checked(await pending);
49
+ const request = fetchProject(projectId, gateway, cacheKey, checked);
39
50
  // Bound bookkeeping even when a discovery endpoint is unavailable.
40
51
  if (inFlight.size < PROJECT_CACHE_MAX_ENTRIES)
41
52
  inFlight.set(cacheKey, request);
42
53
  try {
43
- return await request;
54
+ return checked(await request);
44
55
  }
45
56
  finally {
46
57
  if (inFlight.get(cacheKey) === request)
47
58
  inFlight.delete(cacheKey);
48
59
  }
49
60
  }
50
- async function fetchProject(projectId, gateway, cacheKey) {
61
+ async function fetchProject(projectId, gateway, cacheKey, checked) {
51
62
  const url = `${gateway}/api/projects/${encodeURIComponent(projectId)}/config`;
52
- const response = await fetch(url);
63
+ const response = await fetch(url, { redirect: 'error' });
53
64
  if (!response.ok) {
54
65
  if (response.status === 404) {
55
66
  const body = await response.json().catch(() => ({}));
@@ -64,15 +75,13 @@ async function fetchProject(projectId, gateway, cacheKey) {
64
75
  }
65
76
  throw new Error(`StorystickError: Failed to resolve project "${projectId}" (HTTP ${response.status})`);
66
77
  }
67
- // Gateway returns { endpoint, projectId: <convex _id>, name, shortId,
68
- // urlLabel, plan, features }. Post-Wave-2 the SDK treats the shortId
69
- // as the public projectId; the Convex `_id` stays hidden inside the
70
- // gateway (used only for JWT minting + internal FK integrity).
78
+ // The shortId is the public project identity; deployment IDs are not needed.
71
79
  const raw = await response.json();
72
80
  if (!isRecord(raw))
73
81
  throw new Error('StorystickError: Invalid project discovery response.');
74
82
  const config = {
75
83
  endpoint: raw.endpoint,
84
+ ...(typeof raw.syncEndpoint === 'string' ? { syncEndpoint: raw.syncEndpoint } : {}),
76
85
  projectId: raw.shortId,
77
86
  name: raw.name,
78
87
  plan: raw.plan,
@@ -81,6 +90,7 @@ async function fetchProject(projectId, gateway, cacheKey) {
81
90
  if (!isProjectConfig(config, projectId)) {
82
91
  throw new Error('StorystickError: Invalid project discovery response.');
83
92
  }
93
+ checked(config);
84
94
  Object.freeze(config.features);
85
95
  Object.freeze(config);
86
96
  // Store in cache (keyed by projectId + gateway URL — see cacheKey above)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storystick/client",
3
- "version": "0.2.0-rc.2",
3
+ "version": "0.2.0-rc.4",
4
4
  "license": "FSL-1.1-MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -43,8 +43,8 @@
43
43
  "tag": "beta"
44
44
  },
45
45
  "dependencies": {
46
- "@storystick/media": "0.2.0-rc.2",
47
- "@storystick/types": "0.1.0-rc.2"
46
+ "@storystick/media": "0.2.0-rc.3",
47
+ "@storystick/types": "0.1.0-rc.3"
48
48
  },
49
49
  "devDependencies": {
50
50
  "typescript": "^5.8.2",
@@ -52,7 +52,7 @@
52
52
  "@types/node": "^22.13.10"
53
53
  },
54
54
  "engines": {
55
- "node": ">=24.19.0 <25"
55
+ "node": "^22.13.0 || ^24.19.0"
56
56
  },
57
57
  "repository": {
58
58
  "type": "git",