@shop-on/theme-server 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/dist/account-state.js +1 -2
  2. package/dist/account.d.ts +1 -3
  3. package/dist/account.js +1 -3
  4. package/dist/activity.d.ts +1 -3
  5. package/dist/activity.js +1 -2
  6. package/dist/analytics-proxy.d.ts +8 -14
  7. package/dist/analytics-proxy.js +111 -28
  8. package/dist/analytics-script-proxy.d.ts +1 -5
  9. package/dist/analytics-script-proxy.js +4 -14
  10. package/dist/api-contract/src/addresses.js +32 -0
  11. package/dist/api-contract/src/areas.js +49 -0
  12. package/dist/api-contract/src/custom-data.d.ts +31 -0
  13. package/dist/api-contract/src/custom-data.js +303 -0
  14. package/dist/api-contract/src/ids.js +110 -0
  15. package/dist/api-contract/src/image.js +65 -0
  16. package/dist/api-contract/src/limits.js +44 -0
  17. package/dist/api-contract/src/media.js +13 -0
  18. package/dist/api-contract/src/pickup.js +11 -0
  19. package/dist/api-contract/src/recommendations.js +4 -0
  20. package/dist/api-contract/src/shops.js +27 -0
  21. package/dist/api-contract/src/storefront/analytics.d.ts +100 -0
  22. package/dist/api-contract/src/storefront/analytics.js +138 -0
  23. package/dist/api-contract/src/storefront/areas.d.ts +2 -0
  24. package/dist/api-contract/src/storefront/cart.d.ts +132 -0
  25. package/dist/api-contract/src/storefront/cart.js +248 -0
  26. package/dist/api-contract/src/storefront/catalog.d.ts +3 -0
  27. package/dist/api-contract/src/storefront/checkout-analytics.d.ts +2 -0
  28. package/dist/api-contract/src/storefront/checkout.d.ts +2 -0
  29. package/dist/api-contract/src/storefront/checkout.js +624 -0
  30. package/dist/api-contract/src/storefront/client.d.ts +3 -0
  31. package/dist/api-contract/src/storefront/client.js +6 -0
  32. package/dist/api-contract/src/storefront/content.d.ts +3 -0
  33. package/dist/api-contract/src/storefront/custom-data.d.ts +2 -0
  34. package/dist/api-contract/src/storefront/custom-data.js +27 -0
  35. package/dist/api-contract/src/storefront/customer.d.ts +2 -0
  36. package/dist/api-contract/src/storefront/customer.js +261 -0
  37. package/dist/api-contract/src/storefront/downloads.d.ts +2 -0
  38. package/dist/api-contract/src/storefront/draft-order-invoice.d.ts +2 -0
  39. package/dist/api-contract/src/storefront/forms.d.ts +2 -0
  40. package/dist/api-contract/src/storefront/forms.js +82 -0
  41. package/dist/api-contract/src/storefront/index.d.ts +20956 -0
  42. package/dist/api-contract/src/storefront/orders.d.ts +2 -0
  43. package/dist/api-contract/src/storefront/policies.d.ts +2 -0
  44. package/dist/api-contract/src/storefront/procedure.d.ts +2 -0
  45. package/dist/api-contract/src/storefront/procedure.js +29 -0
  46. package/dist/api-contract/src/storefront/reviews.d.ts +20 -0
  47. package/dist/api-contract/src/storefront/search.d.ts +3 -0
  48. package/dist/api-contract/src/storefront/seo.d.ts +2 -0
  49. package/dist/api-contract/src/storefront/seo.js +132 -0
  50. package/dist/api-contract/src/storefront/shop.d.ts +2 -0
  51. package/dist/api-contract/src/storefront/shop.js +101 -0
  52. package/dist/api-contract/src/taxonomy.js +5 -0
  53. package/dist/api-contract/src/text.js +15 -0
  54. package/dist/api-contract/src/theme-documents.js +13 -0
  55. package/dist/api-contract/src/theme-translations.d.ts +14 -0
  56. package/dist/api-contract/src/theme-translations.js +30 -0
  57. package/dist/api-contract/src/video.js +19 -0
  58. package/dist/availability.d.ts +6 -3
  59. package/dist/availability.js +11 -5
  60. package/dist/blog.d.ts +53 -59
  61. package/dist/blog.js +197 -497
  62. package/dist/cache.d.ts +5 -6
  63. package/dist/cache.js +1 -2
  64. package/dist/canonical-host.d.ts +4 -6
  65. package/dist/canonical-host.js +5 -6
  66. package/dist/card.js +159 -0
  67. package/dist/cart-customer.d.ts +1 -3
  68. package/dist/cart-customer.js +64 -105
  69. package/dist/cart-mutations.d.ts +43 -77
  70. package/dist/cart-mutations.js +106 -232
  71. package/dist/cart-recommendations.d.ts +1 -3
  72. package/dist/cart-recommendations.js +1 -2
  73. package/dist/cart-session.d.ts +1 -3
  74. package/dist/cart-session.js +1 -2
  75. package/dist/cart.d.ts +63 -224
  76. package/dist/cart.js +70 -197
  77. package/dist/checkout.d.ts +13 -17
  78. package/dist/checkout.js +75 -101
  79. package/dist/coalesce.js +57 -0
  80. package/dist/collection.d.ts +89 -298
  81. package/dist/collection.js +210 -656
  82. package/dist/contact.d.ts +20 -10
  83. package/dist/contact.js +36 -30
  84. package/dist/content-version.d.ts +37 -21
  85. package/dist/content-version.js +64 -42
  86. package/dist/contract-kit/src/client.d.ts +12 -0
  87. package/dist/contract-kit/src/client.js +156 -0
  88. package/dist/contract-kit/src/errors.d.ts +1 -0
  89. package/dist/contract-kit/src/errors.js +81 -0
  90. package/dist/contract-kit/src/ids.d.ts +1 -0
  91. package/dist/contract-kit/src/ids.js +118 -0
  92. package/dist/contract-kit/src/index.d.ts +7 -0
  93. package/dist/contract-kit/src/money.d.ts +1 -0
  94. package/dist/contract-kit/src/money.js +10 -0
  95. package/dist/contract-kit/src/pagination.d.ts +1 -0
  96. package/dist/contract-kit/src/procedure.d.ts +69 -0
  97. package/dist/contract-kit/src/procedure.js +16 -0
  98. package/dist/contract-kit/src/realtime.d.ts +1 -0
  99. package/dist/cookie-secret.js +1 -2
  100. package/dist/csrf.js +1 -2
  101. package/dist/customer-handoff.d.ts +1 -3
  102. package/dist/customer-handoff.js +10 -25
  103. package/dist/customer-session.d.ts +1 -3
  104. package/dist/customer-session.js +1 -2
  105. package/dist/customer.d.ts +2 -3
  106. package/dist/customer.js +27 -44
  107. package/dist/files.d.ts +49 -10
  108. package/dist/files.js +106 -89
  109. package/dist/fonts.d.ts +3 -5
  110. package/dist/fonts.js +16 -35
  111. package/dist/html.d.ts +1 -3
  112. package/dist/html.js +1 -2
  113. package/dist/liquid.d.ts +4 -10
  114. package/dist/liquid.js +25 -32
  115. package/dist/listing.js +79 -0
  116. package/dist/marketing-cookies.d.ts +1 -3
  117. package/dist/marketing-cookies.js +1 -2
  118. package/dist/menu.d.ts +46 -155
  119. package/dist/menu.js +51 -61
  120. package/dist/metafields.d.ts +9 -5
  121. package/dist/metafields.js +10 -38
  122. package/dist/metaobject.d.ts +10 -5
  123. package/dist/metaobject.js +43 -66
  124. package/dist/money.d.ts +7 -0
  125. package/dist/money.js +18 -0
  126. package/dist/newsletter.d.ts +19 -10
  127. package/dist/newsletter.js +31 -25
  128. package/dist/page.d.ts +13 -17
  129. package/dist/page.js +49 -105
  130. package/dist/password-session.d.ts +1 -3
  131. package/dist/password-session.js +1 -2
  132. package/dist/password.d.ts +25 -18
  133. package/dist/password.js +41 -59
  134. package/dist/policy.d.ts +7 -7
  135. package/dist/policy.js +19 -55
  136. package/dist/product.d.ts +42 -67
  137. package/dist/product.js +144 -644
  138. package/dist/read-ahead.d.ts +18 -0
  139. package/dist/read-ahead.js +32 -0
  140. package/dist/recommendations.d.ts +6 -12
  141. package/dist/recommendations.js +36 -60
  142. package/dist/review.d.ts +134 -94
  143. package/dist/review.js +257 -469
  144. package/dist/search.d.ts +59 -64
  145. package/dist/search.js +170 -469
  146. package/dist/seo-context.d.ts +1 -3
  147. package/dist/seo-context.js +4 -5
  148. package/dist/seo-documents.d.ts +50 -0
  149. package/dist/seo-documents.js +149 -0
  150. package/dist/shop-seo.d.ts +3 -5
  151. package/dist/shop-seo.js +7 -26
  152. package/dist/shop.d.ts +38 -42
  153. package/dist/shop.js +37 -51
  154. package/dist/store-availability.d.ts +12 -14
  155. package/dist/store-availability.js +18 -56
  156. package/dist/storefront.js +199 -0
  157. package/dist/structured-data.d.ts +3 -28
  158. package/dist/structured-data.js +19 -49
  159. package/dist/trace.js +1 -2
  160. package/dist/translations.d.ts +26 -31
  161. package/dist/translations.js +55 -28
  162. package/package.json +16 -14
  163. package/dist/graphql-env.d.ts +0 -22778
  164. package/dist/graphql.d.ts +0 -64
  165. package/dist/graphql.js +0 -344
  166. package/dist/schema.storefront.graphql +0 -10483
  167. package/dist/seo-proxy.d.ts +0 -11
  168. package/dist/seo-proxy.js +0 -26
package/dist/contact.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- //#region src/contact.d.ts
2
1
  export interface SubmitContactFormInput {
3
2
  email: string;
4
- turnstileToken: string;
3
+ /** The widget's token; empty or absent when the shop has no widget. */
4
+ turnstileToken?: string;
5
5
  name?: string;
6
6
  phone?: string;
7
7
  body?: string;
@@ -10,16 +10,26 @@ export interface SubmitContactFormInput {
10
10
  value: string;
11
11
  }[];
12
12
  }
13
- /** A refusal carries the API's first user error: its `code` (`INVALID_EMAIL`,
14
- * `RATE_LIMITED`, …) for the form to word, and its `message` — English, `null`
15
- * when the API gave none — for a theme that shows it. */
13
+ /** Why the api did not send the message, for the form to word:
14
+ * `TURNSTILE_FAILED` (the bot check did not pass), `CONTACT_EMAIL_MISSING`
15
+ * (the shop has no contact email to send it to), `VALIDATION_FAILED` (`field`
16
+ * the input it names: `email`, `body`, `fields`; null when it names none),
17
+ * `RATE_LIMITED` (too many messages from this buyer's address, or to this
18
+ * shop; `retryAfterSeconds` until the next is counted). */
16
19
  export type SubmitContactFormResult = {
17
20
  ok: true;
18
21
  } | {
19
22
  ok: false;
20
- code: string;
21
- message: string | null;
23
+ code: "TURNSTILE_FAILED" | "CONTACT_EMAIL_MISSING";
24
+ } | {
25
+ ok: false;
26
+ code: "VALIDATION_FAILED";
27
+ field: string | null;
28
+ } | {
29
+ ok: false;
30
+ code: "RATE_LIMITED";
31
+ retryAfterSeconds: number;
22
32
  };
23
- /** Send the form. A transport or GraphQL failure throws. */
24
- export declare function submitContactForm(input: SubmitContactFormInput): Promise<SubmitContactFormResult>;
25
- //#endregion
33
+ /** Send the form. The token goes only when the form has one: a shop without a
34
+ * widget asks for none. Any other failure throws. */
35
+ export declare function submitContactForm(input: SubmitContactFormInput): Promise<SubmitContactFormResult>;
package/dist/contact.js CHANGED
@@ -1,33 +1,39 @@
1
- import { graphql, request } from "./graphql.js";
2
- //#region src/contact.ts
3
- const ShopContactFormMutation = graphql(`
4
- mutation ShopContactForm($input: ShopContactFormInput!) {
5
- shopContactForm(input: $input) {
6
- submitted
7
- userErrors {
8
- code
9
- message
10
- }
11
- }
12
- }
13
- `);
14
- /** Send the form. A transport or GraphQL failure throws. */
1
+ import { errorCode, invalidField, storefront } from "./storefront.js";
2
+ // src/contact.ts
3
+ /** Send the form. The token goes only when the form has one: a shop without a
4
+ * widget asks for none. Any other failure throws. */
15
5
  async function submitContactForm(input) {
16
- const payload = (await request(ShopContactFormMutation, { input: {
17
- email: input.email,
18
- turnstileToken: input.turnstileToken,
19
- name: input.name ?? null,
20
- phone: input.phone ?? null,
21
- body: input.body ?? null,
22
- fields: input.fields ?? null
23
- } })).shopContactForm;
24
- if (payload?.submitted) return { ok: true };
25
- const error = payload?.userErrors[0];
26
- return {
27
- ok: false,
28
- code: error?.code ?? "UNKNOWN",
29
- message: error?.message ?? null
30
- };
6
+ const { turnstileToken, ...form } = input;
7
+ try {
8
+ await storefront().contact.submit({
9
+ ...form,
10
+ ...turnstileToken ? { turnstileToken } : {}
11
+ });
12
+ return { ok: true };
13
+ } catch (error) {
14
+ const code = errorCode(error);
15
+ if (code === "RATE_LIMITED") {
16
+ const { retryAfterSeconds } = error.data;
17
+ return {
18
+ ok: false,
19
+ code,
20
+ retryAfterSeconds
21
+ };
22
+ }
23
+ if (code === "VALIDATION_FAILED") return {
24
+ ok: false,
25
+ code,
26
+ field: invalidField(error)
27
+ };
28
+ if (code === "TURNSTILE_FAILED") return {
29
+ ok: false,
30
+ code
31
+ };
32
+ if (code === "PRECONDITION_FAILED" && error.data?.condition === "shops.contact_email_missing") return {
33
+ ok: false,
34
+ code: "CONTACT_EMAIL_MISSING"
35
+ };
36
+ throw error;
37
+ }
31
38
  }
32
- //#endregion
33
39
  export { submitContactForm };
@@ -1,35 +1,51 @@
1
- //#region src/content-version.d.ts
2
1
  /**
3
- * Per-shop storefront content version. Rails bumps a per-shop counter on any
4
- * catalog content write and serves it as the storefront `shop.contentVersion`
5
- * field; the catalog loaders prepend it to their `memoTTL` keys so an edit
6
- * busts the per-process cache within seconds instead of waiting out the 60s
7
- * TTL.
8
- * Stock / availability changes are deliberately NOT covered — they stay on
9
- * the TTL.
2
+ * Per-shop storefront content version: a token that changes whenever
3
+ * something the storefront procedures answer has changed. The api holds it in
4
+ * Postgres and moves it in the transaction of the write (a product,
5
+ * collection, page, menu, file, setting, moderated review, a merchant's stock
6
+ * edit; a buyer's hold or order does not move it, so availability they change
7
+ * stays on the TTL), so it is never ahead of the data. The catalog loaders
8
+ * prepend it to their `memoTTL` keys so an edit busts the per-process cache
9
+ * within seconds instead of waiting out the 60s TTL.
10
10
  *
11
- * Never throws: a failed read resolves the last version this reader saw, else
12
- * the fallback, so the loaders keep their keys rather than failing the render.
13
- * A read of the fallback after a real version counts as failed too — Rails
14
- * answers "0" when its Redis read fails, and the INCR'd counter never returns
15
- * to it.
11
+ * Compare it for difference only, never greater-than: a restored database can
12
+ * answer a lower one, and that is a change like any other.
13
+ *
14
+ * This reader never throws: a failed read resolves the last version it saw,
15
+ * else the fallback, so the loaders keep their keys rather than failing the
16
+ * render. A read of the fallback after a real version counts as failed too:
17
+ * the shard router forwards "0" when Redis has no version for the shop.
16
18
  */
17
19
  export declare function createContentVersionReader({ read, fallback, onError }: {
18
20
  read: () => Promise<string | null>;
19
21
  fallback?: string;
20
22
  onError?: (error: unknown) => void;
21
23
  }): () => Promise<string>;
22
- /** Set by the storefront shard's router on every request it forwards. */
24
+ /**
25
+ * Set by the storefront shard's router on every request it forwards. Not the
26
+ * api's `x-content-version`: the router reads this one from Redis. Its name is
27
+ * pinned against the router's (the orchestrator's content-version contract
28
+ * test).
29
+ */
23
30
  export declare const CONTENT_VERSION_HEADER = "x-shard-content-version";
24
31
  /** In the env of an isolate whose shard router sets or drops that header. */
25
32
  export declare const CONTENT_VERSION_FLAG = "SHARD_FORWARDS_CONTENT_VERSION";
26
33
  /**
27
- * The version the shard router forwarded with this request (read from Redis by
28
- * the orchestrator, at most one resolve cache old: ~5s), else the polled one.
29
- * The header counts only under CONTENT_VERSION_FLAG: off a shard, such as
30
- * behind `theme dev`'s tunnel or under `wrangler dev`, nothing strips a
31
- * caller's copy, and a made-up version would miss every catalog cache entry.
34
+ * The version for this request, from one of two sources, never mixed within a
35
+ * request:
36
+ * - On a shard: the version the router forwarded (Redis, which an api job sets
37
+ * to the committed version; at most one resolve cache old, ~5s). The header
38
+ * counts only under CONTENT_VERSION_FLAG: off a shard, such as behind
39
+ * `theme dev`'s tunnel or under `wrangler dev`, nothing strips a caller's
40
+ * copy, and a made-up version would miss every catalog cache entry.
41
+ * - Elsewhere: the version the latest storefront answer carried, if its call
42
+ * went out within the last second; else a poll of `shop.contentVersion`.
43
+ * Under steady traffic that reaches the api no poll goes out; a page served
44
+ * whole from cache polls once a second.
45
+ * Taking the version from any answer is safe because a loader reads the
46
+ * version before it fetches, and the api commits the version with the write:
47
+ * an entry is only ever stored under a version at or behind its data. A stale
48
+ * version costs one extra miss, never stale data served under a new key.
32
49
  * Wired into the catalog loaders via the `version` option of `memoTTL`.
33
50
  */
34
- export declare function getContentVersion(): Promise<string>;
35
- //#endregion
51
+ export declare function getContentVersion(): Promise<string>;
@@ -1,23 +1,26 @@
1
1
  import { memoTTL } from "./cache.js";
2
2
  import { currentRequest } from "./request-scope.js";
3
- import { graphql, request } from "./graphql.js";
4
- //#region src/content-version.ts
3
+ import { StorefrontConfigError, errorCode, lastSeenContentVersion, storefront } from "./storefront.js";
4
+ // src/content-version.ts
5
5
  const CONTENT_VERSION_TTL_MS = 1e3;
6
6
  const FALLBACK_VERSION = "0";
7
7
  /**
8
- * Per-shop storefront content version. Rails bumps a per-shop counter on any
9
- * catalog content write and serves it as the storefront `shop.contentVersion`
10
- * field; the catalog loaders prepend it to their `memoTTL` keys so an edit
11
- * busts the per-process cache within seconds instead of waiting out the 60s
12
- * TTL.
13
- * Stock / availability changes are deliberately NOT covered — they stay on
14
- * the TTL.
8
+ * Per-shop storefront content version: a token that changes whenever
9
+ * something the storefront procedures answer has changed. The api holds it in
10
+ * Postgres and moves it in the transaction of the write (a product,
11
+ * collection, page, menu, file, setting, moderated review, a merchant's stock
12
+ * edit; a buyer's hold or order does not move it, so availability they change
13
+ * stays on the TTL), so it is never ahead of the data. The catalog loaders
14
+ * prepend it to their `memoTTL` keys so an edit busts the per-process cache
15
+ * within seconds instead of waiting out the 60s TTL.
15
16
  *
16
- * Never throws: a failed read resolves the last version this reader saw, else
17
- * the fallback, so the loaders keep their keys rather than failing the render.
18
- * A read of the fallback after a real version counts as failed too — Rails
19
- * answers "0" when its Redis read fails, and the INCR'd counter never returns
20
- * to it.
17
+ * Compare it for difference only, never greater-than: a restored database can
18
+ * answer a lower one, and that is a change like any other.
19
+ *
20
+ * This reader never throws: a failed read resolves the last version it saw,
21
+ * else the fallback, so the loaders keep their keys rather than failing the
22
+ * render. A read of the fallback after a real version counts as failed too:
23
+ * the shard router forwards "0" when Redis has no version for the shop.
21
24
  */
22
25
  function createContentVersionReader({ read, fallback = FALLBACK_VERSION, onError }) {
23
26
  let lastGood;
@@ -34,51 +37,70 @@ function createContentVersionReader({ read, fallback = FALLBACK_VERSION, onError
34
37
  }
35
38
  };
36
39
  }
37
- const ContentVersionQuery = graphql(`
38
- query StorefrontContentVersion {
39
- shop {
40
- contentVersion
41
- }
42
- }
43
- `);
44
- const readContentVersion = createContentVersionReader({
45
- read: async () => {
46
- if (!process.env.STOREFRONT_CLIENT_ID || !process.env.STOREFRONT_CLIENT_SECRET) return null;
47
- return (await request(ContentVersionQuery)).shop?.contentVersion ?? null;
48
- },
49
- onError: (error) => {
50
- console.warn("[theme/content-version] read failed:", error);
40
+ /**
41
+ * `shop.contentVersion`. With no STOREFRONT_KEY (standalone theme dev without
42
+ * a shop) there is nothing to ask: the fallback, so loaders use plain TTL
43
+ * caching. A refused key (`StorefrontConfigError`) is thrown, as every loader
44
+ * throws it: a revoked storefront answers 500, a cached page included. Any
45
+ * other failure resolves the last version an answer carried, else the
46
+ * fallback.
47
+ */
48
+ async function readFromApi() {
49
+ if (!process.env.STOREFRONT_KEY) return FALLBACK_VERSION;
50
+ try {
51
+ return (await storefront().shop.contentVersion({})).version;
52
+ } catch (error) {
53
+ if (error instanceof StorefrontConfigError) throw error;
54
+ console.warn(`[theme/content-version] read failed: ${errorCode(error) ?? String(error)}`);
55
+ return lastSeenContentVersion()?.version ?? FALLBACK_VERSION;
51
56
  }
52
- });
57
+ }
53
58
  /**
54
- * Memoized for 1s so a fan-out of loaders in a single render shares one Rails
55
- * round trip, and concurrent renders take the lease holder's result — this
56
- * caps the polling cost at one tiny query per second per isolate, failed reads
57
- * included (the reader never throws, so its fallback is cached for the TTL).
59
+ * Memoized for 1s so a fan-out of loaders in a single render shares one api
60
+ * call, and concurrent renders take the lease holder's result. This caps the
61
+ * polling cost at one call per second per isolate, failed reads included
62
+ * (their answer is cached for the TTL like a success).
58
63
  */
59
- const pollContentVersion = memoTTL(readContentVersion, {
64
+ const pollContentVersion = memoTTL(readFromApi, {
60
65
  ttlMs: CONTENT_VERSION_TTL_MS,
61
66
  key: () => "v"
62
67
  });
63
- /** Set by the storefront shard's router on every request it forwards. */
68
+ /**
69
+ * Set by the storefront shard's router on every request it forwards. Not the
70
+ * api's `x-content-version`: the router reads this one from Redis. Its name is
71
+ * pinned against the router's (the orchestrator's content-version contract
72
+ * test).
73
+ */
64
74
  const CONTENT_VERSION_HEADER = "x-shard-content-version";
65
75
  /** In the env of an isolate whose shard router sets or drops that header. */
66
76
  const CONTENT_VERSION_FLAG = "SHARD_FORWARDS_CONTENT_VERSION";
67
77
  /**
68
- * The version the shard router forwarded with this request (read from Redis by
69
- * the orchestrator, at most one resolve cache old: ~5s), else the polled one.
70
- * The header counts only under CONTENT_VERSION_FLAG: off a shard, such as
71
- * behind `theme dev`'s tunnel or under `wrangler dev`, nothing strips a
72
- * caller's copy, and a made-up version would miss every catalog cache entry.
78
+ * The version for this request, from one of two sources, never mixed within a
79
+ * request:
80
+ * - On a shard: the version the router forwarded (Redis, which an api job sets
81
+ * to the committed version; at most one resolve cache old, ~5s). The header
82
+ * counts only under CONTENT_VERSION_FLAG: off a shard, such as behind
83
+ * `theme dev`'s tunnel or under `wrangler dev`, nothing strips a caller's
84
+ * copy, and a made-up version would miss every catalog cache entry.
85
+ * - Elsewhere: the version the latest storefront answer carried, if its call
86
+ * went out within the last second; else a poll of `shop.contentVersion`.
87
+ * Under steady traffic that reaches the api no poll goes out; a page served
88
+ * whole from cache polls once a second.
89
+ * Taking the version from any answer is safe because a loader reads the
90
+ * version before it fetches, and the api commits the version with the write:
91
+ * an entry is only ever stored under a version at or behind its data. A stale
92
+ * version costs one extra miss, never stale data served under a new key.
73
93
  * Wired into the catalog loaders via the `version` option of `memoTTL`.
74
94
  */
75
95
  function getContentVersion() {
76
- return forwardedHeader() ? readForwarded() : pollContentVersion();
96
+ if (forwardedHeader()) return readForwarded();
97
+ const seen = lastSeenContentVersion();
98
+ if (seen && Date.now() - seen.sentAt < CONTENT_VERSION_TTL_MS) return Promise.resolve(seen.version);
99
+ return pollContentVersion();
77
100
  }
78
101
  function forwardedHeader() {
79
102
  if (process.env["SHARD_FORWARDS_CONTENT_VERSION"] !== "1") return null;
80
103
  return currentRequest()?.headers.get("x-shard-content-version") || null;
81
104
  }
82
105
  const readForwarded = createContentVersionReader({ read: async () => forwardedHeader() });
83
- //#endregion
84
106
  export { CONTENT_VERSION_FLAG, CONTENT_VERSION_HEADER, createContentVersionReader, getContentVersion };
@@ -0,0 +1,12 @@
1
+ import { AnyContractRouter, ContractRouterClient } from "@orpc/contract";
2
+ /** What one call can carry besides its input: `client.x.y(input, { context })`. */
3
+ export interface RpcCallContext {
4
+ /**
5
+ * Sent as `Idempotency-Key`: a retry with the same key is answered with
6
+ * the first attempt's outcome. Every call to a provider carries one.
7
+ */
8
+ idempotencyKey?: string;
9
+ /** This call's deadline, in place of the client's `timeoutMs`. */
10
+ timeoutMs?: number;
11
+ }
12
+ export type RpcClient<TContract extends AnyContractRouter> = ContractRouterClient<TContract, RpcCallContext>;
@@ -0,0 +1,156 @@
1
+ import { commonErrors } from "./errors.js";
2
+ import { ORPCError, createORPCClient, isORPCErrorJson, mapEventIterator } from "@orpc/client";
3
+ import { RPCLink } from "@orpc/client/fetch";
4
+ // ../contract-kit/src/client.ts
5
+ const BROWSER_TIMEOUT_MS = 3e4;
6
+ const MAX_RETRY_AFTER_SECONDS = 86400;
7
+ /** What an RPC mount answers with: JSON, an event stream, or a form when the output holds files. */
8
+ const RPC_CONTENT_TYPES = [
9
+ "application/json",
10
+ "text/event-stream",
11
+ "multipart/form-data"
12
+ ];
13
+ /** The fields of oRPC's JSON answer; an output of nothing is `{}`. */
14
+ const ENVELOPE_FIELDS = /* @__PURE__ */ new Set([
15
+ "json",
16
+ "meta",
17
+ "maps"
18
+ ]);
19
+ /** The longest wait a timer holds. */
20
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
21
+ function assertTimeout(ms) {
22
+ if (!Number.isInteger(ms) || ms <= 0 || ms > MAX_TIMEOUT_MS) throw new TypeError(`timeoutMs is a whole number of milliseconds, 1 to ${MAX_TIMEOUT_MS}`);
23
+ return ms;
24
+ }
25
+ /** What the caller's own `headers()` threw: its failure, not the service's. */
26
+ var CallerFailure = class {
27
+ thrown;
28
+ constructor(thrown) {
29
+ this.thrown = thrown;
30
+ }
31
+ };
32
+ function createRpcClient(audience, credentials, options) {
33
+ const timeoutMs = options.timeoutMs ?? (typeof globalThis.document === "undefined" ? void 0 : BROWSER_TIMEOUT_MS);
34
+ if (timeoutMs === void 0) throw new TypeError(`a ${audience} client made on a server needs \`timeoutMs\``);
35
+ assertTimeout(timeoutMs);
36
+ const send = options.fetch ?? ((request) => fetch(request));
37
+ const link = new RPCLink({
38
+ url: `${options.baseUrl.replace(/\/$/, "")}/rpc/${audience}`,
39
+ headers: async ({ context }) => {
40
+ const headers = { ...await Promise.resolve().then(() => options.headers?.()).catch((thrown) => {
41
+ throw new CallerFailure(thrown);
42
+ }) };
43
+ if (context.idempotencyKey !== void 0) headers["idempotency-key"] = context.idempotencyKey;
44
+ return headers;
45
+ },
46
+ fetch: async (request, init) => screen(await send(new Request(request, {
47
+ ...init,
48
+ credentials
49
+ }))),
50
+ interceptors: [async ({ next, ...call }) => {
51
+ const ms = call.context.timeoutMs === void 0 ? timeoutMs : assertTimeout(call.context.timeoutMs);
52
+ const deadline = new AbortController();
53
+ const timer = setTimeout(() => deadline.abort(), ms);
54
+ const caller = call.signal;
55
+ try {
56
+ const output = await next({
57
+ ...call,
58
+ signal: caller ? AbortSignal.any([caller, deadline.signal]) : deadline.signal
59
+ });
60
+ if (!isAsyncIterable(output)) return output;
61
+ return mapEventIterator(output, {
62
+ value: async (value) => value,
63
+ error: async (error) => caller?.aborted ? error : toContractError(error)
64
+ });
65
+ } catch (error) {
66
+ if (caller?.aborted) throw error;
67
+ if (error instanceof CallerFailure) throw error.thrown;
68
+ if (deadline.signal.aborted) throw contractError("DEADLINE_EXCEEDED", { deadlineMs: ms });
69
+ throw toContractError(error);
70
+ } finally {
71
+ clearTimeout(timer);
72
+ }
73
+ }]
74
+ });
75
+ return createORPCClient(link);
76
+ }
77
+ function contractError(code, data) {
78
+ return new ORPCError(code, {
79
+ status: commonErrors[code].status,
80
+ data,
81
+ defined: true
82
+ });
83
+ }
84
+ function isCommonCode(code) {
85
+ return Object.hasOwn(commonErrors, code);
86
+ }
87
+ /**
88
+ * The service's own error: one a procedure declares (oRPC marks it
89
+ * defined), or a common code with its params, as the edge sends them.
90
+ */
91
+ function isServiceError(error) {
92
+ if (error.defined) return true;
93
+ if (!isCommonCode(error.code)) return false;
94
+ const entry = commonErrors[error.code];
95
+ return error.status === entry.status && entry.data.safeParse(error.data).success;
96
+ }
97
+ /**
98
+ * Turns an answer that is not the service's into the contract's error before
99
+ * oRPC reads it: a redirect, and an error status whose body is not one of
100
+ * the service's errors (a proxy's page, a path an older deploy lacks).
101
+ */
102
+ async function screen(response) {
103
+ if (response.type === "opaqueredirect" || response.status === 0) throw contractError("UNAVAILABLE", {});
104
+ if (response.status >= 300 && response.status < 400) throw contractError("UNAVAILABLE", { status: response.status });
105
+ if (response.status < 400) {
106
+ const type = response.headers.get("content-type");
107
+ if (type === null) return response;
108
+ if (!RPC_CONTENT_TYPES.some((rpc) => type.startsWith(rpc))) throw contractError("UNAVAILABLE", { status: response.status });
109
+ if (type.startsWith("application/json") && !isEnvelope(await response.clone().text())) throw contractError("UNAVAILABLE", { status: response.status });
110
+ return response;
111
+ }
112
+ const body = await response.clone().text().then((text) => JSON.parse(text)).catch(() => void 0);
113
+ const error = typeof body === "object" && body !== null ? body.json : null;
114
+ if (isORPCErrorJson(error) && isServiceError(error)) return response;
115
+ throw byStatus(response.status, response.headers.get("retry-after"));
116
+ }
117
+ /** Whether a JSON body is oRPC's answer. One that does not parse is left for oRPC to refuse. */
118
+ function isEnvelope(text) {
119
+ if (text === "") return true;
120
+ let body;
121
+ try {
122
+ body = JSON.parse(text);
123
+ } catch {
124
+ return true;
125
+ }
126
+ return typeof body === "object" && body !== null && !Array.isArray(body) && Object.keys(body).every((field) => ENVELOPE_FIELDS.has(field));
127
+ }
128
+ function byStatus(status, retryAfter) {
129
+ if (status === 429) return contractError("RATE_LIMITED", { retryAfterSeconds: retryAfterSeconds(retryAfter) });
130
+ if (status === 408 || status === 504) return contractError("DEADLINE_EXCEEDED", {});
131
+ return contractError("UNAVAILABLE", { status });
132
+ }
133
+ /** `Retry-After` in seconds or as an HTTP date; anything else is the default wait. */
134
+ function retryAfterSeconds(header, now = Date.now()) {
135
+ const value = header?.trim() ?? "";
136
+ let seconds = NaN;
137
+ if (/^\d+$/.test(value)) seconds = Number(value);
138
+ else if (value.endsWith("GMT")) seconds = Math.ceil((Date.parse(value) - now) / 1e3);
139
+ if (Number.isNaN(seconds)) return 60;
140
+ return Math.min(Math.max(seconds, 0), MAX_RETRY_AFTER_SECONDS);
141
+ }
142
+ /** Any failure as the contract's error; the service's own pass through, marked defined. */
143
+ function toContractError(error) {
144
+ if (!(error instanceof ORPCError)) return contractError("UNAVAILABLE", {});
145
+ if (!isServiceError(error)) return byStatus(error.status, null);
146
+ if (error.defined) return error;
147
+ return new ORPCError(error.code, {
148
+ status: error.status,
149
+ data: error.data,
150
+ defined: true
151
+ });
152
+ }
153
+ function isAsyncIterable(value) {
154
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
155
+ }
156
+ export { createRpcClient, retryAfterSeconds };
@@ -0,0 +1 @@
1
+ import "zod";
@@ -0,0 +1,81 @@
1
+ import { z } from "zod";
2
+ // ../contract-kit/src/errors.ts
3
+ const validationIssue = z.object({
4
+ /** Where in the input: keys and array indexes from the root. */
5
+ path: z.array(z.union([z.string(), z.int()])),
6
+ /** The zod issue code (`too_small`, `invalid_type`, …) or a procedure's own. */
7
+ code: z.string(),
8
+ /** What the translation needs: `minimum`, `maximum`, `expected`, `format`… */
9
+ params: z.record(z.string(), z.union([
10
+ z.string(),
11
+ z.number(),
12
+ z.boolean()
13
+ ]))
14
+ });
15
+ const commonErrors = {
16
+ UNAUTHENTICATED: {
17
+ status: 401,
18
+ data: z.object({ reason: z.enum([
19
+ "missing",
20
+ "invalid",
21
+ "expired",
22
+ "revoked"
23
+ ]) })
24
+ },
25
+ PERMISSION_DENIED: {
26
+ status: 403,
27
+ data: z.object({ permission: z.string() })
28
+ },
29
+ NOT_FOUND: {
30
+ status: 404,
31
+ data: z.object({
32
+ resource: z.string(),
33
+ id: z.string().optional()
34
+ })
35
+ },
36
+ CONFLICT: {
37
+ status: 409,
38
+ data: z.object({
39
+ resource: z.string(),
40
+ field: z.string().optional()
41
+ })
42
+ },
43
+ PRECONDITION_FAILED: {
44
+ status: 412,
45
+ data: z.object({
46
+ condition: z.string(),
47
+ /** What stands in the way, by name and how many (an amount for money): only a condition that counts says. */
48
+ categories: z.record(z.string(), z.int()).optional()
49
+ })
50
+ },
51
+ /** The request's body is larger than its mount reads: the edge refuses it before any procedure runs. */
52
+ PAYLOAD_TOO_LARGE: {
53
+ status: 413,
54
+ data: z.object({ limitBytes: z.int().positive() })
55
+ },
56
+ VALIDATION_FAILED: {
57
+ status: 422,
58
+ data: z.object({ issues: z.array(validationIssue).min(1) })
59
+ },
60
+ RATE_LIMITED: {
61
+ status: 429,
62
+ data: z.object({ retryAfterSeconds: z.int().nonnegative() })
63
+ },
64
+ /**
65
+ * The service did not answer in the contract's shape: it could not be
66
+ * reached, or something in front of it answered instead (a proxy's page,
67
+ * a redirect, an older deploy without the procedure). Retry later. The
68
+ * client raises it (`./client`); `status` is the HTTP status that came
69
+ * back, for a log, absent when nothing did.
70
+ */
71
+ UNAVAILABLE: {
72
+ status: 503,
73
+ data: z.object({ status: z.int().optional() })
74
+ },
75
+ /** The call ran past its deadline, the client's own or the server's. */
76
+ DEADLINE_EXCEEDED: {
77
+ status: 504,
78
+ data: z.object({ deadlineMs: z.int().positive().optional() })
79
+ }
80
+ };
81
+ export { commonErrors };
@@ -0,0 +1 @@
1
+ import "zod";