@shop-on/customer-runtime 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/LICENSE.md CHANGED
@@ -1,9 +1,9 @@
1
- # Cody Theme Development License
1
+ # Shopon Theme Development License
2
2
 
3
3
  Copyright (c) 2026 Cody LLC. All rights reserved except as granted below.
4
4
 
5
5
  "The Software" is this package, its source, and its documentation. "The
6
- Platform" is Cody, the commerce platform operated by Cody LLC.
6
+ Platform" is Shopon, the commerce platform operated by Cody LLC.
7
7
 
8
8
  ## 1. Grant
9
9
 
package/dist/handoff.d.ts CHANGED
@@ -1,12 +1,4 @@
1
1
  //#region src/handoff.d.ts
2
- export interface HandoffPayload {
3
- shopHandle: string;
4
- cartToken: string;
5
- customerSessionToken?: string;
6
- customerSessionExpiresAt?: string;
7
- customerEmail?: string;
8
- createdAt: number;
9
- }
10
2
  export type ConsumeResult<P> = {
11
3
  ok: true;
12
4
  payload: P;
@@ -14,6 +6,4 @@ export type ConsumeResult<P> = {
14
6
  ok: false;
15
7
  reason: "missing_or_consumed" | "malformed";
16
8
  };
17
- export declare function createHandoff(payload: HandoffPayload): Promise<string>;
18
- export declare function consumeHandoff(nonce: string): Promise<ConsumeResult<HandoffPayload>>;
19
9
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shop-on/customer-runtime",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "license": "SEE LICENSE IN dist/LICENSE.md",
5
5
  "files": [
6
6
  "dist"
@@ -8,18 +8,12 @@
8
8
  "type": "module",
9
9
  "exports": {
10
10
  "./customer-session-handoff": "./dist/customer-session-handoff.js",
11
- "./graphql": "./dist/graphql.js",
12
- "./handoff": "./dist/handoff.js",
13
11
  "./handoff-state": "./dist/handoff-state.js",
14
- "./internal-api": "./dist/internal-api.js",
15
12
  "./lease": "./dist/lease.js",
16
- "./oauth": "./dist/oauth.js",
17
13
  "./relay": "./dist/relay.js",
18
14
  "./request-scope": "./dist/request-scope.js",
19
15
  "./sealed-session": "./dist/sealed-session.js",
20
16
  "./session-cookie": "./dist/session-cookie.js",
21
- "./shop-context": "./dist/shop-context.js",
22
- "./storefront-bounce": "./dist/storefront-bounce.js",
23
17
  "./trace": "./dist/trace.js",
24
18
  "./package.json": "./package.json"
25
19
  },
package/dist/graphql.d.ts DELETED
@@ -1,21 +0,0 @@
1
- import { TadaDocumentNode } from "gql.tada";
2
- //#region src/graphql.d.ts
3
- export interface StorefrontRequestOptions {
4
- /** Pass through as `X-Customer-Session` so the Rails resolver can attach
5
- * customer context to the call. Required for customer-scoped operations
6
- * (e.g. `customerLogout`); omit for unauthenticated cart/checkout flows. */
7
- customerSessionToken?: string;
8
- }
9
- /**
10
- * Typed GraphQL request against the Rails storefront endpoint, authenticated
11
- * via the per-shop OAuth client_credentials token from `oauth.ts`. On a 401
12
- * the token it sent is evicted and the request retried once — handles clock
13
- * skew and silent revocation without bubbling a transient error up.
14
- *
15
- * GraphQL-level errors surface as `ClientError` from `graphql-request`.
16
- * `customer-runtime` doesn't own the schema (each consuming app brings its
17
- * own gql.tada setup) so `TResult` / `TVariables` come from the caller's
18
- * document type.
19
- */
20
- export declare function storefrontRequest<TResult, TVariables extends Record<string, unknown> = Record<string, unknown>>(shopHandle: string, document: TadaDocumentNode<TResult, TVariables>, variables?: TVariables, options?: StorefrontRequestOptions): Promise<TResult>;
21
- //#endregion
package/dist/graphql.js DELETED
@@ -1,43 +0,0 @@
1
- import { relayHeaders } from "./relay.js";
2
- import { traceHeaders } from "./trace.js";
3
- import { evictStorefrontToken, getStorefrontToken } from "./oauth.js";
4
- import { ClientError, GraphQLClient } from "graphql-request";
5
- //#region src/graphql.ts
6
- const API_URL = process.env.SPN_CUSTOMER_API_URL ?? "http://localhost:3003";
7
- function buildClient(token, extra) {
8
- return new GraphQLClient(`${API_URL}/graphql`, { headers: {
9
- Authorization: `Bearer ${token}`,
10
- ...extra
11
- } });
12
- }
13
- /**
14
- * Typed GraphQL request against the Rails storefront endpoint, authenticated
15
- * via the per-shop OAuth client_credentials token from `oauth.ts`. On a 401
16
- * the token it sent is evicted and the request retried once — handles clock
17
- * skew and silent revocation without bubbling a transient error up.
18
- *
19
- * GraphQL-level errors surface as `ClientError` from `graphql-request`.
20
- * `customer-runtime` doesn't own the schema (each consuming app brings its
21
- * own gql.tada setup) so `TResult` / `TVariables` come from the caller's
22
- * document type.
23
- */
24
- async function storefrontRequest(shopHandle, document, variables, options) {
25
- const extra = {
26
- ...options?.customerSessionToken ? { "X-Customer-Session": options.customerSessionToken } : {},
27
- ...traceHeaders(),
28
- ...relayHeaders()
29
- };
30
- let token = await getStorefrontToken(shopHandle);
31
- try {
32
- return await buildClient(token, extra).request(document, variables);
33
- } catch (err) {
34
- if (err instanceof ClientError && err.response.status === 401) {
35
- evictStorefrontToken(shopHandle, token);
36
- token = await getStorefrontToken(shopHandle);
37
- return await buildClient(token, extra).request(document, variables);
38
- }
39
- throw err;
40
- }
41
- }
42
- //#endregion
43
- export { storefrontRequest };
package/dist/handoff.js DELETED
@@ -1,12 +0,0 @@
1
- import { internalDelete, internalPost } from "./internal-api.js";
2
- //#region src/handoff.ts
3
- const KIND = "checkout_handoff";
4
- async function createHandoff(payload) {
5
- const { nonce } = await internalPost(`handoff/${KIND}`, { payload });
6
- return nonce;
7
- }
8
- async function consumeHandoff(nonce) {
9
- return internalDelete(`handoff/${KIND}/${encodeURIComponent(nonce)}`);
10
- }
11
- //#endregion
12
- export { consumeHandoff, createHandoff };
@@ -1,21 +0,0 @@
1
- //#region src/internal-api.d.ts
2
- export declare class InternalApiError extends Error {
3
- readonly status: number;
4
- readonly bodySnippet: string;
5
- constructor(path: string, status: number, bodySnippet: string);
6
- }
7
- /**
8
- * POST a JSON body to `/api/internal/customer/<path>`. Throws
9
- * `InternalApiError` on non-2xx so callers can decide how to map status →
10
- * domain outcome (e.g. token mint maps 404 → CredentialsUnavailableError).
11
- */
12
- export declare function internalPost<TResponse>(path: string, body: unknown, { signal }?: {
13
- signal?: AbortSignal;
14
- }): Promise<TResponse>;
15
- /**
16
- * DELETE `/api/internal/customer/<path>`. Used by the handoff consume path —
17
- * the endpoint always returns 200 (with `{ ok: false, reason }` on miss), so
18
- * a non-2xx here is a real error, not a domain miss.
19
- */
20
- export declare function internalDelete<TResponse>(path: string): Promise<TResponse>;
21
- //#endregion
package/dist/oauth.d.ts DELETED
@@ -1,38 +0,0 @@
1
- //#region src/oauth.d.ts
2
- export declare const MINT_LEASE_MS = 3000;
3
- export declare const MINT_FAILURE_HOLD_MS = 2000;
4
- export declare class OAuthMintError extends Error {
5
- readonly shopHandle: string;
6
- /** True when Rails returned 404 — the shop doesn't exist. (A shop with no
7
- * storefront application is a 422, treated as transient.) Distinguishes
8
- * "this shop is gone" from "the network is flaky". Routes use this to
9
- * decide between rendering the shop-not-found page and the transient-error
10
- * page. */
11
- readonly notFound: boolean;
12
- /** True when Rails returned 429 naming the `relay/ip` throttle — the
13
- * buyer's own bucket, not one other buyers share. */
14
- readonly buyerThrottled: boolean;
15
- constructor(shopHandle: string, detail: string, opts?: {
16
- notFound?: boolean;
17
- buyerThrottled?: boolean;
18
- });
19
- }
20
- /**
21
- * Get (or mint) the storefront access token for `shopHandle`. Cached
22
- * in-process; concurrent requests for one shop share one mint's outcome
23
- * through the mint lease, so a cold cache costs exactly one Rails round-trip.
24
- * Throws `ShopHandleInvalidError` on a malformed handle, which can arrive here
25
- * unchecked from a server route or an RPC call.
26
- */
27
- export declare function getStorefrontToken(shopHandle: string): Promise<string>;
28
- /**
29
- * Drop the cached token for `shopHandle` if it is still `token`. Call when a
30
- * Rails response signals `token` is no longer valid (typically a 401 from a
31
- * downstream GraphQL request) so the next call re-mints. Compare-and-clear: a
32
- * concurrent caller may already have re-minted, and a late 401 on the old
33
- * token must not throw the new one away.
34
- */
35
- export declare function evictStorefrontToken(shopHandle: string, token: string): void;
36
- export declare function __resetForTesting(): void;
37
- export declare function __mintHoldCountForTesting(): number;
38
- //#endregion
package/dist/oauth.js DELETED
@@ -1,137 +0,0 @@
1
- import { InternalApiError, internalPost } from "./internal-api.js";
2
- import { createLease } from "./lease.js";
3
- import { resolveShopHandleFromParams } from "./shop-context.js";
4
- //#region src/oauth.ts
5
- const REFRESH_SKEW_MS = 3e5;
6
- const STALE_TOKEN_MARGIN_MS = 3e4;
7
- const CACHE_MAX_ENTRIES = 1e3;
8
- const cache = /* @__PURE__ */ new Map();
9
- const MINT_LEASE_MS = 3e3;
10
- let mintLease = createLease({ leaseMs: MINT_LEASE_MS });
11
- const MINT_TIMEOUT_MS = 2750;
12
- const MINT_FAILURE_HOLD_MS = 2e3;
13
- const mintHolds = /* @__PURE__ */ new Map();
14
- function touch(shopHandle, token) {
15
- cache.delete(shopHandle);
16
- cache.set(shopHandle, token);
17
- if (cache.size > CACHE_MAX_ENTRIES) {
18
- const oldest = cache.keys().next().value;
19
- if (oldest !== void 0) cache.delete(oldest);
20
- }
21
- }
22
- var OAuthMintError = class extends Error {
23
- shopHandle;
24
- /** True when Rails returned 404 — the shop doesn't exist. (A shop with no
25
- * storefront application is a 422, treated as transient.) Distinguishes
26
- * "this shop is gone" from "the network is flaky". Routes use this to
27
- * decide between rendering the shop-not-found page and the transient-error
28
- * page. */
29
- notFound;
30
- /** True when Rails returned 429 naming the `relay/ip` throttle — the
31
- * buyer's own bucket, not one other buyers share. */
32
- buyerThrottled;
33
- constructor(shopHandle, detail, opts) {
34
- super(`[customer-runtime/oauth] token mint failed for shop ${shopHandle}: ${detail}`);
35
- this.name = "OAuthMintError";
36
- this.shopHandle = shopHandle;
37
- this.notFound = opts?.notFound ?? false;
38
- this.buyerThrottled = opts?.buyerThrottled ?? false;
39
- }
40
- };
41
- function throttleName(bodySnippet) {
42
- try {
43
- return JSON.parse(bodySnippet).throttle;
44
- } catch {
45
- return;
46
- }
47
- }
48
- async function mintToken(shopHandle) {
49
- let response;
50
- try {
51
- response = await internalPost("storefront-token", { shop_handle: shopHandle }, { signal: AbortSignal.timeout(MINT_TIMEOUT_MS) });
52
- } catch (err) {
53
- if (err instanceof InternalApiError) throw new OAuthMintError(shopHandle, `${err.status}: ${err.bodySnippet}`, {
54
- notFound: err.status === 404,
55
- buyerThrottled: err.status === 429 && throttleName(err.bodySnippet) === "relay/ip"
56
- });
57
- throw new OAuthMintError(shopHandle, err instanceof Error ? err.message : String(err));
58
- }
59
- if (typeof response.access_token !== "string" || response.access_token.length === 0) throw new OAuthMintError(shopHandle, "missing or invalid access_token in response");
60
- const expiresAtMs = Date.parse(response.expires_at);
61
- if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) throw new OAuthMintError(shopHandle, `invalid expires_at: ${String(response.expires_at)}`);
62
- return {
63
- accessToken: response.access_token,
64
- expiresAtMs
65
- };
66
- }
67
- function activeMintHold(shopHandle) {
68
- const hold = mintHolds.get(shopHandle);
69
- return hold && hold.until > Date.now() ? hold : null;
70
- }
71
- function holdMint(shopHandle, error) {
72
- const now = Date.now();
73
- for (const [k, hold] of mintHolds) if (hold.until <= now) mintHolds.delete(k);
74
- mintHolds.set(shopHandle, {
75
- until: now + MINT_FAILURE_HOLD_MS,
76
- error
77
- });
78
- }
79
- async function mintUnderLease(shopHandle) {
80
- let fresh;
81
- try {
82
- fresh = await mintToken(shopHandle);
83
- } catch (err) {
84
- if (err instanceof OAuthMintError && err.notFound) cache.delete(shopHandle);
85
- if (!(err instanceof OAuthMintError && err.buyerThrottled)) holdMint(shopHandle, err);
86
- throw err;
87
- }
88
- mintHolds.delete(shopHandle);
89
- touch(shopHandle, fresh);
90
- return fresh;
91
- }
92
- /**
93
- * Get (or mint) the storefront access token for `shopHandle`. Cached
94
- * in-process; concurrent requests for one shop share one mint's outcome
95
- * through the mint lease, so a cold cache costs exactly one Rails round-trip.
96
- * Throws `ShopHandleInvalidError` on a malformed handle, which can arrive here
97
- * unchecked from a server route or an RPC call.
98
- */
99
- async function getStorefrontToken(shopHandle) {
100
- resolveShopHandleFromParams({ shopHandle });
101
- const now = Date.now();
102
- const hit = cache.get(shopHandle);
103
- if (hit && hit.expiresAtMs - REFRESH_SKEW_MS > now) {
104
- touch(shopHandle, hit);
105
- return hit.accessToken;
106
- }
107
- const prev = hit && hit.expiresAtMs - STALE_TOKEN_MARGIN_MS > now ? hit.accessToken : null;
108
- const held = activeMintHold(shopHandle);
109
- if (prev && (held || mintLease.heldByOther(shopHandle))) return prev;
110
- if (held) throw held.error;
111
- try {
112
- return (await mintLease.run(shopHandle, () => mintUnderLease(shopHandle))).accessToken;
113
- } catch (err) {
114
- if (prev && cache.get(shopHandle)?.accessToken === prev) return prev;
115
- throw err;
116
- }
117
- }
118
- /**
119
- * Drop the cached token for `shopHandle` if it is still `token`. Call when a
120
- * Rails response signals `token` is no longer valid (typically a 401 from a
121
- * downstream GraphQL request) so the next call re-mints. Compare-and-clear: a
122
- * concurrent caller may already have re-minted, and a late 401 on the old
123
- * token must not throw the new one away.
124
- */
125
- function evictStorefrontToken(shopHandle, token) {
126
- if (cache.get(shopHandle)?.accessToken === token) cache.delete(shopHandle);
127
- }
128
- function __resetForTesting() {
129
- cache.clear();
130
- mintHolds.clear();
131
- mintLease = createLease({ leaseMs: MINT_LEASE_MS });
132
- }
133
- function __mintHoldCountForTesting() {
134
- return mintHolds.size;
135
- }
136
- //#endregion
137
- export { MINT_FAILURE_HOLD_MS, MINT_LEASE_MS, OAuthMintError, __mintHoldCountForTesting, __resetForTesting, evictStorefrontToken, getStorefrontToken };
@@ -1,55 +0,0 @@
1
- //#region src/shop-context.d.ts
2
- /**
3
- * Route-context shape returned by `resolveShopContext`. Intentionally NO
4
- * token field — anything returned from a TanStack Router `beforeLoad` is
5
- * dehydrated into the SSR hydration payload and shipped to the browser.
6
- * Server-only consumers (oauth, graphql) re-resolve the token from cache
7
- * on each call, so the bearer never needs to leave the server.
8
- */
9
- export interface ShopContext {
10
- shopHandle: string;
11
- }
12
- export declare class ShopHandleInvalidError extends Error {
13
- constructor(value: unknown);
14
- }
15
- export declare class CredentialsUnavailableError extends Error {
16
- readonly shopHandle: string;
17
- constructor(shopHandle: string);
18
- }
19
- /**
20
- * Validate a shopHandle pulled from a route param. Matches the format
21
- * enforced by the Rails Shop model (lowercase alnum + hyphens, leading
22
- * hyphen permitted). Throws on missing/malformed so router error
23
- * boundaries can surface a clean 4xx rather than carrying garbage
24
- * downstream.
25
- */
26
- export declare function resolveShopHandleFromParams(params: {
27
- shopHandle?: string | undefined;
28
- }): string;
29
- /**
30
- * One-shot resolver for a shop-scoped layout route's `beforeLoad`. Pulls
31
- * the handle from params, primes the storefront token via a Rails round-
32
- * trip so a missing shop / shop-without-storefront-application surfaces
33
- * the typed `CredentialsUnavailableError` page before any child route
34
- * runs, and returns the minimal context.
35
- *
36
- * The token preload doubles as a cache warmer: every downstream GraphQL
37
- * call in this request will reuse the cached token, so the probe is not
38
- * wasted work.
39
- *
40
- * Returns only `{ shopHandle }` — the token is intentionally discarded
41
- * from the return value. Anything returned from `beforeLoad` is
42
- * serialized into the SSR hydration payload and shipped to the browser,
43
- * so secrets must stay server-side.
44
- *
45
- * Routes render a typed error page from `CredentialsUnavailableError`;
46
- * the structured log emitted below is the load-bearing observability
47
- * signal. (TanStack Start's `setResponseStatus` doesn't propagate through
48
- * a thrown `beforeLoad`, so the wire status is 500, not 503.) Recovery
49
- * for a transient Rails outage is operational; for a missing shop the
50
- * recovery is to point the URL at a real handle.
51
- */
52
- export declare function resolveShopContext(params: {
53
- shopHandle?: string | undefined;
54
- }): Promise<ShopContext>;
55
- //#endregion
@@ -1,72 +0,0 @@
1
- //#region src/shop-context.ts
2
- const SHOP_HANDLE_PATTERN = /^[a-z0-9-]{1,63}$/;
3
- var ShopHandleInvalidError = class extends Error {
4
- constructor(value) {
5
- super(`[customer-runtime/shop-context] invalid shopHandle: ${String(value)}`);
6
- this.name = "ShopHandleInvalidError";
7
- }
8
- };
9
- var CredentialsUnavailableError = class extends Error {
10
- shopHandle;
11
- constructor(shopHandle) {
12
- super(`[customer-runtime/shop-context] credentials unavailable for shop: ${shopHandle}`);
13
- this.name = "CredentialsUnavailableError";
14
- this.shopHandle = shopHandle;
15
- }
16
- };
17
- /**
18
- * Validate a shopHandle pulled from a route param. Matches the format
19
- * enforced by the Rails Shop model (lowercase alnum + hyphens, leading
20
- * hyphen permitted). Throws on missing/malformed so router error
21
- * boundaries can surface a clean 4xx rather than carrying garbage
22
- * downstream.
23
- */
24
- function resolveShopHandleFromParams(params) {
25
- const handle = params.shopHandle;
26
- if (typeof handle !== "string" || !SHOP_HANDLE_PATTERN.test(handle)) throw new ShopHandleInvalidError(handle);
27
- return handle;
28
- }
29
- /**
30
- * One-shot resolver for a shop-scoped layout route's `beforeLoad`. Pulls
31
- * the handle from params, primes the storefront token via a Rails round-
32
- * trip so a missing shop / shop-without-storefront-application surfaces
33
- * the typed `CredentialsUnavailableError` page before any child route
34
- * runs, and returns the minimal context.
35
- *
36
- * The token preload doubles as a cache warmer: every downstream GraphQL
37
- * call in this request will reuse the cached token, so the probe is not
38
- * wasted work.
39
- *
40
- * Returns only `{ shopHandle }` — the token is intentionally discarded
41
- * from the return value. Anything returned from `beforeLoad` is
42
- * serialized into the SSR hydration payload and shipped to the browser,
43
- * so secrets must stay server-side.
44
- *
45
- * Routes render a typed error page from `CredentialsUnavailableError`;
46
- * the structured log emitted below is the load-bearing observability
47
- * signal. (TanStack Start's `setResponseStatus` doesn't propagate through
48
- * a thrown `beforeLoad`, so the wire status is 500, not 503.) Recovery
49
- * for a transient Rails outage is operational; for a missing shop the
50
- * recovery is to point the URL at a real handle.
51
- */
52
- async function resolveShopContext(params) {
53
- const shopHandle = resolveShopHandleFromParams(params);
54
- const { getStorefrontToken, OAuthMintError } = await import("./oauth.js");
55
- try {
56
- await getStorefrontToken(shopHandle);
57
- } catch (err) {
58
- if (err instanceof OAuthMintError) {
59
- console.error(JSON.stringify({
60
- event: "credentials_unavailable",
61
- shopHandle,
62
- notFound: err.notFound,
63
- ts: Date.now()
64
- }));
65
- throw new CredentialsUnavailableError(shopHandle);
66
- }
67
- throw err;
68
- }
69
- return { shopHandle };
70
- }
71
- //#endregion
72
- export { CredentialsUnavailableError, ShopHandleInvalidError, resolveShopContext, resolveShopHandleFromParams };
@@ -1,10 +0,0 @@
1
- //#region src/storefront-bounce.d.ts
2
- /**
3
- * The storefront's own `/account` bounce, coming back to `returnToPath`.
4
- * Account and checkout sign a buyer in through it rather than linking to
5
- * account directly: the theme issues the `state` its customer handoff is
6
- * bound to, bounces to account, and consumes the handoff on the way back.
7
- * Pure, so either app can build the link in a component.
8
- */
9
- export declare function storefrontAccountBounceUrl(storefrontRoot: string, returnToPath: string): string;
10
- //#endregion
@@ -1,15 +0,0 @@
1
- //#region src/storefront-bounce.ts
2
- /**
3
- * The storefront's own `/account` bounce, coming back to `returnToPath`.
4
- * Account and checkout sign a buyer in through it rather than linking to
5
- * account directly: the theme issues the `state` its customer handoff is
6
- * bound to, bounces to account, and consumes the handoff on the way back.
7
- * Pure, so either app can build the link in a component.
8
- */
9
- function storefrontAccountBounceUrl(storefrontRoot, returnToPath) {
10
- const url = new URL("/account", storefrontRoot);
11
- url.searchParams.set("return_to", returnToPath);
12
- return url.toString();
13
- }
14
- //#endregion
15
- export { storefrontAccountBounceUrl };