@relyon/kit 0.0.0-stage → 1.0.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 (225) hide show
  1. package/AGENTS.md +75 -0
  2. package/CHANGELOG.md +1053 -0
  3. package/LICENSE +21 -0
  4. package/QUICKSTART.md +239 -0
  5. package/README.md +117 -2
  6. package/dist/adapters/express.d.ts +39 -0
  7. package/dist/adapters/express.js +106 -0
  8. package/dist/adapters/hono.d.ts +16 -0
  9. package/dist/adapters/hono.js +15 -0
  10. package/dist/adapters/next.d.ts +29 -0
  11. package/dist/adapters/next.js +38 -0
  12. package/dist/agent-card.d.ts +14 -0
  13. package/dist/agent-card.js +58 -0
  14. package/dist/agent-docs.d.ts +36 -0
  15. package/dist/agent-docs.js +78 -0
  16. package/dist/agent-hooks.d.ts +66 -0
  17. package/dist/agent-hooks.js +280 -0
  18. package/dist/agents.d.ts +24 -0
  19. package/dist/agents.js +120 -0
  20. package/dist/api-key.d.ts +6 -0
  21. package/dist/api-key.js +33 -0
  22. package/dist/cache.d.ts +46 -0
  23. package/dist/cache.js +86 -0
  24. package/dist/cart-tokens.d.ts +31 -0
  25. package/dist/cart-tokens.js +58 -0
  26. package/dist/cart-transfer.d.ts +95 -0
  27. package/dist/cart-transfer.js +387 -0
  28. package/dist/catalog-enrichment.d.ts +6 -0
  29. package/dist/catalog-enrichment.js +71 -0
  30. package/dist/catalog-reads.d.ts +126 -0
  31. package/dist/catalog-reads.js +104 -0
  32. package/dist/catalog.d.ts +78 -0
  33. package/dist/catalog.js +288 -0
  34. package/dist/charge-claims.d.ts +11 -0
  35. package/dist/charge-claims.js +47 -0
  36. package/dist/check.d.ts +44 -0
  37. package/dist/check.js +152 -0
  38. package/dist/checklist-manifest.d.ts +72 -0
  39. package/dist/checklist-manifest.js +341 -0
  40. package/dist/checkout.d.ts +222 -0
  41. package/dist/checkout.js +353 -0
  42. package/dist/cli.d.ts +2 -0
  43. package/dist/cli.js +727 -0
  44. package/dist/confirmation.d.ts +78 -0
  45. package/dist/confirmation.js +124 -0
  46. package/dist/context.d.ts +81 -0
  47. package/dist/context.js +10 -0
  48. package/dist/discovery.d.ts +151 -0
  49. package/dist/discovery.js +346 -0
  50. package/dist/doctor-cart-transfer.d.ts +33 -0
  51. package/dist/doctor-cart-transfer.js +186 -0
  52. package/dist/doctor-catalog.d.ts +8 -0
  53. package/dist/doctor-catalog.js +47 -0
  54. package/dist/doctor-evidence.d.ts +22 -0
  55. package/dist/doctor-evidence.js +57 -0
  56. package/dist/doctor-merchant.d.ts +48 -0
  57. package/dist/doctor-merchant.js +74 -0
  58. package/dist/doctor-source.d.ts +5 -0
  59. package/dist/doctor-source.js +142 -0
  60. package/dist/doctor-variants.d.ts +70 -0
  61. package/dist/doctor-variants.js +102 -0
  62. package/dist/doctor.d.ts +215 -0
  63. package/dist/doctor.js +1689 -0
  64. package/dist/events.d.ts +95 -0
  65. package/dist/events.js +200 -0
  66. package/dist/feed-mapping.d.ts +114 -0
  67. package/dist/feed-mapping.js +152 -0
  68. package/dist/feed-values.d.ts +13 -0
  69. package/dist/feed-values.js +40 -0
  70. package/dist/feeds.d.ts +104 -0
  71. package/dist/feeds.js +366 -0
  72. package/dist/identify.d.ts +102 -0
  73. package/dist/identify.js +124 -0
  74. package/dist/identity.d.ts +37 -0
  75. package/dist/identity.js +54 -0
  76. package/dist/index.d.ts +42 -0
  77. package/dist/index.js +41 -0
  78. package/dist/init.d.ts +157 -0
  79. package/dist/init.js +912 -0
  80. package/dist/kit-config.d.ts +19 -0
  81. package/dist/kit-config.js +43 -0
  82. package/dist/kit-environment.d.ts +20 -0
  83. package/dist/kit-environment.js +32 -0
  84. package/dist/kit-updates.d.ts +47 -0
  85. package/dist/kit-updates.js +77 -0
  86. package/dist/kit-version-project.d.ts +18 -0
  87. package/dist/kit-version-project.js +214 -0
  88. package/dist/kit-version.d.ts +37 -0
  89. package/dist/kit-version.js +162 -0
  90. package/dist/kit.d.ts +516 -0
  91. package/dist/kit.js +1309 -0
  92. package/dist/layers/pages.d.ts +3 -0
  93. package/dist/layers/pages.js +5 -0
  94. package/dist/layers/payments.d.ts +7 -0
  95. package/dist/layers/payments.js +9 -0
  96. package/dist/layers/products.d.ts +10 -0
  97. package/dist/layers/products.js +13 -0
  98. package/dist/live.d.ts +13 -0
  99. package/dist/live.js +52 -0
  100. package/dist/mcp.d.ts +270 -0
  101. package/dist/mcp.js +312 -0
  102. package/dist/next-steps.d.ts +101 -0
  103. package/dist/next-steps.js +257 -0
  104. package/dist/order-pending.d.ts +57 -0
  105. package/dist/order-pending.js +127 -0
  106. package/dist/orders.d.ts +12 -0
  107. package/dist/orders.js +21 -0
  108. package/dist/payments-init.d.ts +19 -0
  109. package/dist/payments-init.js +70 -0
  110. package/dist/payments-routes.d.ts +54 -0
  111. package/dist/payments-routes.js +123 -0
  112. package/dist/payments.d.ts +165 -0
  113. package/dist/payments.js +192 -0
  114. package/dist/pnpm-workspace.d.ts +58 -0
  115. package/dist/pnpm-workspace.js +250 -0
  116. package/dist/policies.d.ts +111 -0
  117. package/dist/policies.js +317 -0
  118. package/dist/preview-hosts.d.ts +64 -0
  119. package/dist/preview-hosts.js +175 -0
  120. package/dist/private-config.d.ts +169 -0
  121. package/dist/private-config.js +820 -0
  122. package/dist/progress.d.ts +54 -0
  123. package/dist/progress.js +153 -0
  124. package/dist/protocol-inputs.d.ts +22 -0
  125. package/dist/protocol-inputs.js +151 -0
  126. package/dist/public-origin.d.ts +50 -0
  127. package/dist/public-origin.js +180 -0
  128. package/dist/refusals.d.ts +86 -0
  129. package/dist/refusals.js +157 -0
  130. package/dist/relay.d.ts +107 -0
  131. package/dist/relay.js +655 -0
  132. package/dist/release-notes.d.ts +2 -0
  133. package/dist/release-notes.js +290 -0
  134. package/dist/relyon-cart-tokens.d.ts +101 -0
  135. package/dist/relyon-cart-tokens.js +521 -0
  136. package/dist/relyon.d.ts +141 -0
  137. package/dist/relyon.js +238 -0
  138. package/dist/robots.d.ts +27 -0
  139. package/dist/robots.js +127 -0
  140. package/dist/rules.d.ts +144 -0
  141. package/dist/rules.js +347 -0
  142. package/dist/sdk/generated/public-api.d.ts +4816 -0
  143. package/dist/sdk/generated/public-api.js +1 -0
  144. package/dist/sdk/index.d.ts +24 -0
  145. package/dist/sdk/index.js +34 -0
  146. package/dist/sdk/signatures.d.ts +17 -0
  147. package/dist/sdk/signatures.js +33 -0
  148. package/dist/setup.d.ts +37 -0
  149. package/dist/setup.js +94 -0
  150. package/dist/signatures.d.ts +112 -0
  151. package/dist/signatures.js +443 -0
  152. package/dist/state.d.ts +185 -0
  153. package/dist/state.js +96 -0
  154. package/dist/store-payments.d.ts +48 -0
  155. package/dist/store-payments.js +143 -0
  156. package/dist/structured-fields.d.ts +26 -0
  157. package/dist/structured-fields.js +200 -0
  158. package/dist/templates.d.ts +19 -0
  159. package/dist/templates.js +193 -0
  160. package/dist/test-checkout-command.d.ts +32 -0
  161. package/dist/test-checkout-command.js +161 -0
  162. package/dist/test-checkout.d.ts +88 -0
  163. package/dist/test-checkout.js +292 -0
  164. package/dist/types.d.ts +103 -0
  165. package/dist/types.js +18 -0
  166. package/dist/ucp-versions.d.ts +57 -0
  167. package/dist/ucp-versions.js +129 -0
  168. package/dist/util.d.ts +23 -0
  169. package/dist/util.js +68 -0
  170. package/dist/variants.d.ts +67 -0
  171. package/dist/variants.js +146 -0
  172. package/dist/version.d.ts +9 -0
  173. package/dist/version.js +10 -0
  174. package/dist/waiting.d.ts +43 -0
  175. package/dist/waiting.js +57 -0
  176. package/dist/webhook-command.d.ts +48 -0
  177. package/dist/webhook-command.js +367 -0
  178. package/dist/webhook-registration.d.ts +47 -0
  179. package/dist/webhook-registration.js +69 -0
  180. package/dist/webmcp-schema.d.ts +14 -0
  181. package/dist/webmcp-schema.js +140 -0
  182. package/dist/webmcp-script.d.ts +3 -0
  183. package/dist/webmcp-script.js +176 -0
  184. package/dist/webmcp-store.d.ts +102 -0
  185. package/dist/webmcp-store.js +116 -0
  186. package/dist/webmcp.d.ts +242 -0
  187. package/dist/webmcp.js +866 -0
  188. package/dist/wire-names.d.ts +85 -0
  189. package/dist/wire-names.js +109 -0
  190. package/package.json +118 -4
  191. package/release-notes.json +290 -0
  192. package/scripts/install-notice.cjs +7 -0
  193. package/skills/relyon-agents/SKILL.md +327 -0
  194. package/skills/relyon-catalog/SKILL.md +499 -0
  195. package/skills/relyon-catalog/references/example-store.md +218 -0
  196. package/skills/relyon-checkout/SKILL.md +603 -0
  197. package/skills/relyon-checkout/references/checkout-flow.md +257 -0
  198. package/skills/relyon-checkout/references/checkout-page.md +315 -0
  199. package/skills/relyon-go-live/SKILL.md +344 -0
  200. package/skills/relyon-orders/SKILL.md +191 -0
  201. package/skills/relyon-orders/references/webhook-receiver.md +113 -0
  202. package/skills/relyon-payments/SKILL.md +117 -0
  203. package/skills/relyon-setup/SKILL.md +1061 -0
  204. package/skills/relyon-setup/references/QUICKSTART.md +239 -0
  205. package/skills/relyon-setup/references/durable-state.md +209 -0
  206. package/skills/relyon-setup/references/express-server.md +388 -0
  207. package/skills/relyon-setup/references/next-app-router.md +251 -0
  208. package/templates/common/STORE-README.md +67 -0
  209. package/templates/common/gitignore +8 -0
  210. package/templates/common/scripts/check-pricing.ts +22 -0
  211. package/templates/common/scripts/serve.mjs +13 -0
  212. package/templates/common/server/catalog.ts +79 -0
  213. package/templates/common/server/checkout-flow.d.ts +34 -0
  214. package/templates/common/server/pages.ts +184 -0
  215. package/templates/common/server/storage.ts +114 -0
  216. package/templates/common/server/store.ts +67 -0
  217. package/templates/express/server/express.ts +20 -0
  218. package/templates/express/tsconfig.build.json +6 -0
  219. package/templates/express/tsconfig.json +9 -0
  220. package/templates/next/app/[[...path]]/route.ts +24 -0
  221. package/templates/next/next.config.mjs +19 -0
  222. package/templates/next/tsconfig.json +12 -0
  223. package/templates/payments/express.ts +39 -0
  224. package/templates/payments/next.ts +38 -0
  225. package/templates/payments/node.ts +39 -0
@@ -0,0 +1,257 @@
1
+ # Checkout flow on the server: one attempt, never two charges
2
+
3
+ `checkout-flow.js` is the server half of the store's own checkout. The Express
4
+ server (`relyon-setup`, `references/express-server.md`) and the builder-platform
5
+ functions both use it. It keeps one record per order reference and guarantees:
6
+
7
+ - **A payment is recorded before it is sent.** One conditional write moves the
8
+ checkout from `open` to `confirming` and stores the exact attempt (the
9
+ re-priced cart and the payment method). Only the request that wins that write
10
+ sends it.
11
+ - **Anything already sent is only ever replayed.** A retry, a second click, a
12
+ status check or a reload replays the stored attempt with the same order
13
+ reference, so `kit.createPayment` reuses the same `Idempotency-Key`. A new
14
+ payment method from the browser is ignored once an attempt exists.
15
+ - **An unknown outcome stays unknown.** `PaymentOutcomeUnknownError`, a crash
16
+ or any unexpected error leaves the checkout `confirming`. It is never shown
17
+ as "didn't go through" and never closed until Relyon gives a final answer.
18
+ - **Paid but not saved is still pending.** When the payment succeeded but the
19
+ app's `createOrder` threw, the checkout stays `confirming` (marked paid) and
20
+ a replay charges nothing new and retries the order.
21
+ - **An order an earlier call already saved is found, not waited for.** When a
22
+ replay's payment succeeded and the kit answers `orderStatus: "already_created"`
23
+ (an earlier call's `createOrder` saved it, for example before a crash), the
24
+ flow looks the order up by payment ID with the app's `findOrder` and finishes
25
+ the checkout. `in_progress` (another request is still creating it) stays
26
+ pending.
27
+ - **A reload never starts a second payment while one may be in flight.** A
28
+ checkout that is `confirming` (or `paid`) is shown as its status, not as new
29
+ card fields. Only an `open` checkout, where nothing was sent, is replaced.
30
+
31
+ States the browser sees (`state` in every JSON answer):
32
+
33
+ | `state` | HTTP | Meaning | The page |
34
+ | --- | --- | --- | --- |
35
+ | `open` | 200 | Nothing was sent for this checkout. | Pay may be enabled. |
36
+ | `pending` | 202 | A payment was sent; the outcome isn't final, or it's paid and the order is still being saved. | Pay stays disabled; keep checking the order status. |
37
+ | `paid` | 200 | Charged and the order saved. | Show the thank-you page. |
38
+ | `closed` | 409 | Declined or refused; nothing was charged. | A reload starts a new checkout. |
39
+ | `not_found` | 404 | No such checkout. | A reload starts a new checkout. |
40
+
41
+ The starter's `pending` answer also carries `payment_succeeded`: `true` means
42
+ the payment went through but the store order is not saved yet. This is the
43
+ store's own response field, not a Relyon API field. Keep that evidence in the
44
+ rendered status page so a reload or a lost polling answer cannot turn a known
45
+ successful payment into an uncertain one.
46
+
47
+ ```js checkout-flow.js
48
+ // Server-only. The store's own checkout records, so a payment attempt is sent
49
+ // under one order reference and only ever replayed, never sent twice.
50
+ import {
51
+ AgentRefusedError, PaymentOutcomeUnknownError, RelyonProblemError, StoreRefusal,
52
+ } from "@relyon/store-kit";
53
+
54
+ /**
55
+ * Checkout records for one process (development, tests). In production use
56
+ * the app's database (`postgresStoreCheckouts` in relyon-setup's
57
+ * durable-state.js): `update` must be one conditional write there.
58
+ */
59
+ export function memoryCheckouts() {
60
+ const rows = new Map();
61
+ return {
62
+ async get(ref) { return rows.get(ref) ?? null; },
63
+ async insert(ref, row) { rows.set(ref, row); },
64
+ // Writes `row` only while the stored state is still `expected`.
65
+ async update(ref, expected, row) {
66
+ const current = rows.get(ref) ?? null;
67
+ if (current?.state !== expected) return { updated: false, row: current };
68
+ rows.set(ref, row);
69
+ return { updated: true, row };
70
+ },
71
+ async confirming() { return [...rows].filter(([, row]) => row.state === "confirming").map(([ref]) => ref); },
72
+ };
73
+ }
74
+
75
+ // The request is replayed for agent rules; credentials and cookies are not kept.
76
+ const PRIVATE_HEADER = /^cookie$|authorization$/;
77
+ const snapshot = (request) => request
78
+ ? { url: request.url, method: request.method, headers: [...request.headers].filter(([name]) => !PRIVATE_HEADER.test(name)) }
79
+ : null;
80
+ const rebuild = (saved) => saved ? new Request(saved.url, { method: saved.method, headers: saved.headers }) : undefined;
81
+
82
+ const MESSAGES = {
83
+ open: "No payment was sent for this checkout. You can pay now.",
84
+ pending: "We can't confirm your payment yet. Don't pay again: we're checking whether it went through.",
85
+ paidUnsaved: "Your payment went through. Your order is still being placed",
86
+ paid: "Your order is paid.",
87
+ notFound: "We can't find this checkout. Reload to start again.",
88
+ };
89
+
90
+ /** What the browser is told about a checkout record. */
91
+ export function checkoutView(ref, row) {
92
+ if (!row) return { httpStatus: 404, body: { state: "not_found", order_reference: ref ?? null, message: MESSAGES.notFound } };
93
+ const body = { order_reference: ref };
94
+ switch (row.state) {
95
+ case "open": return { httpStatus: 200, body: { ...body, state: "open", message: MESSAGES.open } };
96
+ case "paid": return { httpStatus: 200, body: { ...body, state: "paid", order: row.order ?? null, message: MESSAGES.paid } };
97
+ case "closed": return { httpStatus: 409, body: { ...body, state: "closed", error: row.error, message: row.message } };
98
+ default: return { httpStatus: 202, body: { ...body, state: "pending", payment_succeeded: row.paid === true, message: row.paid ? MESSAGES.paidUnsaved : MESSAGES.pending } };
99
+ }
100
+ }
101
+
102
+ /**
103
+ * `priceCart` is the app's own (the same function the kit calls for agents).
104
+ * `checkouts` is `memoryCheckouts()` or a durable store with the same methods.
105
+ * `findOrder(paymentId)` returns the app's saved order for a payment, or null
106
+ * (`findOrderByPayment` in the example store; a lookup by the orders table's
107
+ * unique payment ID in production).
108
+ */
109
+ export function createCheckoutFlow(kit, { priceCart, checkouts, findOrder = async () => null }) {
110
+ const price = (inputs) => priceCart(inputs.lines, inputs.address, inputs.coupons, {
111
+ protocol: "web", operation: "landing", shippingOptionId: inputs.shipping_option_id, agentCheckoutId: null,
112
+ });
113
+
114
+ async function close(ref, expected, row, error, message) {
115
+ const { attempt, ...rest } = row;
116
+ const saved = await checkouts.update(ref, expected, { ...rest, state: "closed", error, message });
117
+ return checkoutView(ref, saved.row);
118
+ }
119
+
120
+ /** Sends (or replays) the stored attempt. Same order reference, so the same Idempotency-Key. */
121
+ async function send(ref, row, { first }) {
122
+ const { attempt } = row;
123
+ let result;
124
+ try {
125
+ result = await kit.createPayment({
126
+ cart: attempt.cart, paymentMethod: attempt.paymentMethod, orderReference: ref,
127
+ channel: row.channel ?? undefined, agentCheckoutId: row.agentCheckoutId ?? null,
128
+ request: rebuild(attempt.request), info: attempt.info ?? undefined,
129
+ });
130
+ } catch (error) {
131
+ // A first send that is refused never reached a charge.
132
+ if (first && error instanceof AgentRefusedError) {
133
+ return close(ref, "confirming", row, error.code, error.message);
134
+ }
135
+ if (first && error instanceof RelyonProblemError) {
136
+ return close(ref, "confirming", row, error.code, "The payment couldn't be made and nothing was charged. Reload checkout to try again.");
137
+ }
138
+ // Anything else may have charged: keep the attempt and answer "pending".
139
+ if (!(error instanceof PaymentOutcomeUnknownError)) {
140
+ console.error(`payment outcome unknown for ${ref}:`, error instanceof Error ? error.message : String(error));
141
+ }
142
+ return checkoutView(ref, (await checkouts.get(ref)) ?? row);
143
+ }
144
+ if (result.payment.status !== "succeeded") {
145
+ return close(ref, "confirming", row, "payment_failed", "The payment didn't go through and nothing was charged. Reload checkout to try again.");
146
+ }
147
+ let orderId = result.order?.id ?? null;
148
+ if (!result.orderError && !orderId && result.orderStatus === "already_created") {
149
+ // An earlier call saved the order: find it by the payment.
150
+ orderId = (await findOrder(result.payment.id))?.id ?? null;
151
+ }
152
+ if (result.orderError || !orderId) {
153
+ // Paid, but the order isn't saved yet (createOrder failed, or another
154
+ // request is still creating it). Keep the attempt: a replay charges
155
+ // nothing new and retries the order.
156
+ const saved = await checkouts.update(ref, "confirming", { ...row, paid: true, paymentId: result.payment.id });
157
+ return checkoutView(ref, saved.row);
158
+ }
159
+ const { attempt: sent, ...rest } = row;
160
+ const saved = await checkouts.update(ref, "confirming", {
161
+ ...rest, state: "paid", paid: true, paymentId: result.payment.id, order: orderId,
162
+ });
163
+ return checkoutView(ref, saved.row);
164
+ }
165
+
166
+ /** The current state; replays the attempt when its outcome isn't final. Never a new charge. */
167
+ async function confirm(ref) {
168
+ const row = typeof ref === "string" ? await checkouts.get(ref) : null;
169
+ if (row?.state !== "confirming") return checkoutView(ref, row);
170
+ return send(ref, row, { first: false });
171
+ }
172
+
173
+ return {
174
+ price,
175
+
176
+ /**
177
+ * Opens a checkout for the shopper's cart. `previous` is the shopper's
178
+ * last order reference (cookie or local storage). When it is still
179
+ * being confirmed (or is paid and `startNew` isn't set), its status is
180
+ * returned instead of new card fields.
181
+ */
182
+ async open({ inputs, cart, previous, startNew = false, channel, agentCheckoutId }) {
183
+ if (typeof previous === "string" && previous) {
184
+ let prior = await checkouts.get(previous);
185
+ if (prior?.state === "confirming") return { orderReference: previous, view: await confirm(previous) };
186
+ if (prior?.state === "paid" && !startNew) return { orderReference: previous, view: checkoutView(previous, prior) };
187
+ if (prior?.state === "open") {
188
+ // Nothing was sent for it; retire it unless a payment claims it first.
189
+ const { attempt, ...rest } = prior;
190
+ const retired = await checkouts.update(previous, "open", { ...rest, state: "closed", error: "replaced", message: "A newer checkout replaced this one." });
191
+ prior = retired.row;
192
+ if (prior?.state === "confirming") return { orderReference: previous, view: await confirm(previous) };
193
+ }
194
+ }
195
+ const priced = cart ?? await price(inputs); // throws StoreRefusal
196
+ const orderReference = `order_${crypto.randomUUID()}`;
197
+ // One payment session for exactly the store's total; throws PaymentUnavailableError.
198
+ const fields = await kit.cardFields({ amount: priced.totals.total, currency: priced.currency, orderReference });
199
+ await checkouts.insert(orderReference, {
200
+ state: "open", inputs, total: priced.totals.total, currency: priced.currency,
201
+ channel: channel ?? null, agentCheckoutId: agentCheckoutId ?? null,
202
+ });
203
+ return { orderReference, cart: priced, fields };
204
+ },
205
+
206
+ /** The browser's Pay: only an order reference and the tokenized payment method. */
207
+ async pay({ orderReference, paymentMethod, request, info }) {
208
+ const row = typeof orderReference === "string" ? await checkouts.get(orderReference) : null;
209
+ if (!row) return checkoutView(orderReference, null);
210
+ if (row.state !== "open") return confirm(orderReference);
211
+ if (!paymentMethod || typeof paymentMethod !== "object") {
212
+ return { httpStatus: 400, body: { ...checkoutView(orderReference, row).body, error: "payment_method_required" } };
213
+ }
214
+ // Re-price on the server. Never take a total from the browser.
215
+ let cart;
216
+ try {
217
+ cart = await price(row.inputs);
218
+ } catch (error) {
219
+ if (!(error instanceof StoreRefusal)) throw error;
220
+ return close(orderReference, "open", row, error.code, error.message);
221
+ }
222
+ if (cart.totals.total !== row.total || cart.currency !== row.currency) {
223
+ return close(orderReference, "open", row, "cart_changed", "The total changed. Reload checkout to see it.");
224
+ }
225
+ // Record the attempt before sending it; this one conditional write
226
+ // decides which request sends it.
227
+ const attempt = { cart, paymentMethod, request: snapshot(request), info: info ?? null, at: Date.now() };
228
+ const claim = await checkouts.update(orderReference, "open", { ...row, state: "confirming", attempt });
229
+ if (!claim.updated) return confirm(orderReference);
230
+ return send(orderReference, claim.row, { first: true });
231
+ },
232
+
233
+ confirm,
234
+
235
+ /** Read-only: what the order status page shows. */
236
+ async status(ref) {
237
+ return checkoutView(ref, typeof ref === "string" ? await checkouts.get(ref) : null);
238
+ },
239
+
240
+ /** Run every minute or so: replays attempts whose outcome still isn't final. */
241
+ async reconcile({ minAgeMs = 60_000 } = {}) {
242
+ for (const ref of await checkouts.confirming()) {
243
+ const row = await checkouts.get(ref);
244
+ if (row?.state === "confirming" && Date.now() - (row.attempt?.at ?? 0) >= minAgeMs) await confirm(ref);
245
+ }
246
+ },
247
+ };
248
+ }
249
+ ```
250
+
251
+ - Keep the checkout record (and its attempt) until the state is final. Delete
252
+ the stored payment method once a checkout is `paid` or `closed`; the flow
253
+ already drops it from those records.
254
+ - Run `reconcile()` on a timer (or a scheduled job) so a shopper who closed
255
+ the tab still gets their order saved.
256
+ - Order references are random and unguessable; the status answer shows only
257
+ the state and the store's order ID.
@@ -0,0 +1,315 @@
1
+ # Checkout page in the browser
2
+
3
+ The checkout page is the app's own page on the store's domain (the
4
+ `relyon-setup` skill's `references/express-server.md` renders one, with
5
+ `checkout-flow.js` from `references/checkout-flow.md` on the server). The server
6
+ puts `fields.html` from `kit.cardFields` into the page: the card fields
7
+ script tag and one `<relyon-card-fields>` element. That element is the only
8
+ Relyon code in the browser. The card number is typed into fields the
9
+ processor hosts, and the app only ever sees the tokenized payment method.
10
+
11
+ The card fields script loads `async`, and in Test the fields announce
12
+ `relyon-ready` as soon as the element upgrades. That can happen before the
13
+ page's own script has attached its listener (for example when the script
14
+ comes from the browser cache), so the page records readiness itself. Put
15
+ this ready latch in the page **before** `fields.html`; it runs before the
16
+ card fields script can, and marks the element once it is ready:
17
+
18
+ ```html
19
+ <script>
20
+ addEventListener("relyon-ready", (event) => { event.target.dataset.relyonReady = "true"; }, true);
21
+ addEventListener("relyon-error", (event) => { delete event.target.dataset.relyonReady; }, true);
22
+ </script>
23
+ ```
24
+
25
+ ## Checkout page marker
26
+
27
+ Put `data-relyon-cart-items` on one element of the checkout page, set to the
28
+ number of items in the cart, including `0` for an empty cart:
29
+
30
+ ```html
31
+ <main id="checkout" data-relyon-cart-items="2"> … </main>
32
+ ```
33
+
34
+ Render it in both states: an empty checkout shows the page with
35
+ `data-relyon-cart-items="0"` (do not send the shopper on to the cart or the home
36
+ page). `npx @relyon/store-kit doctor` requires this marker, or the kit's
37
+ `<relyon-card-fields>` mount, on the checkout page; landing on the home page
38
+ or a 200 placeholder is NOT DONE. In Test, doctor also transfers a real item
39
+ through `POST /ucp/carts`, opens the `continue_url` and requires
40
+ `data-relyon-cart-items` with a non-empty cart (card fields alone don't show
41
+ that the item landed). The attribute is `CHECKOUT_CART_ITEMS_ATTRIBUTE` and
42
+ `cartItemCount(inputs)` counts the items. Do not reuse
43
+ `data-relyon-checkout`; the WebMCP script uses it.
44
+
45
+ ## Transferred carts and hand-offs: `kit.landing()`
46
+
47
+ A Google cart transfer's `continue_url` (`?relyon_transfer=…`) and an agent
48
+ hand-off link (`?relyon_cart=…`) both land on the checkout page. Call
49
+ `kit.landing()` there and, when it returns `inputs`, show that cart: its
50
+ lines carry each product ID, quantity and, for a variant, its `options`.
51
+ `landing()` takes the page's `Request`, its URL (a `URL` or path string),
52
+ `URLSearchParams`, or a Next.js `searchParams` object, so a server component
53
+ can call it directly:
54
+
55
+ ```ts
56
+ import { CHECKOUT_CART_ITEMS_ATTRIBUTE, cartItemCount, type StoreKit } from "@relyon/store-kit";
57
+ declare const kit: StoreKit; // the app's kit (relyon-setup), server only
58
+
59
+ type SearchParams = Promise<Record<string, string | string[] | undefined>>;
60
+
61
+ // app/checkout/page.tsx (a server component). Next.js 15 and 16 pass searchParams as a Promise.
62
+ // Render <main {...marker}> around the cart; with Express pass kit.landing(webRequest(req)).
63
+ export async function landedCheckout(searchParams: SearchParams) {
64
+ const landing = await kit.landing(await searchParams);
65
+ const items = cartItemCount(landing.inputs); // 0 when nothing landed: show the app's own cart
66
+ return { landing, items, marker: { [CHECKOUT_CART_ITEMS_ATTRIBUTE]: String(items) } };
67
+ }
68
+ ```
69
+
70
+ Links minted by store kit 0.1.10 carry no options; they still land, and a
71
+ variant feed ID in them is mapped to its product plus that variant's options.
72
+ A transfer landing is never attributed (no agent checkout): take the cart from
73
+ `landing.inputs` and charge it through the app's own checkout.
74
+
75
+ ## Sending the shopper to checkout from the server
76
+
77
+ A "Buy now" or cart form that posts to the app answers with
78
+ `kit.redirect(request, path)`: a `303 See Other` to `path` (starting with a
79
+ single `/`) on this request's validated store address. Never build that
80
+ Location or a link from `request.url` (for example
81
+ `new URL("/checkout", request.url)`): a dev server bound to every interface
82
+ (`next dev --hostname 0.0.0.0`) hands the app a `request.url` on `0.0.0.0`,
83
+ which no browser can open, so the pay form never appears. In Test the kit
84
+ reads the browser's Host header instead, and only when it names loopback or one
85
+ of the store's hostnames; an unknown Host falls back to the primary hostname.
86
+ A full URL or `//host` as `path` throws.
87
+
88
+ ```ts
89
+ import type { StoreKit } from "@relyon/store-kit";
90
+ declare const kit: StoreKit; // the app's kit (relyon-setup)
91
+
92
+ // A route that takes a Web Request, such as a Next.js route handler (app/cart/route.ts).
93
+ export async function POST(request: Request): Promise<Response> {
94
+ const form = await request.formData();
95
+ const product = String(form.get("product") ?? "");
96
+ const quantity = Math.min(99, Math.max(1, Math.trunc(Number(form.get("quantity")) || 1)));
97
+ const query = new URLSearchParams({ product, quantity: String(quantity) });
98
+ return kit.redirect(request, `/checkout?${query}`);
99
+ }
100
+ ```
101
+
102
+ With Express, pass `webRequest(req)` (see `express-server.md`) and send the
103
+ answer's status and `Location`.
104
+
105
+ The page's own script (served by the app as `/checkout.js`):
106
+
107
+ ```js checkout.js
108
+ // Browser code. It never reads, stores or sends card numbers.
109
+ const form = document.getElementById("pay");
110
+ const page = form ?? document.getElementById("checkout-status");
111
+ const status = document.getElementById("status");
112
+ const button = form?.querySelector("button[type=submit]");
113
+ const fields = form?.querySelector("relyon-card-fields");
114
+ const reference = page.dataset.orderReference;
115
+ const statusUrl = `/checkout/status?order_reference=${encodeURIComponent(reference)}`;
116
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
117
+ const orderPending = "Your payment went through. Your order is still being placed";
118
+ // Payment success is evidence, not a polling status: once known, never forget it.
119
+ let paymentSucceeded = page.dataset.paymentSucceeded === "true";
120
+ let attemptSent = !form;
121
+ // Set once the server says this checkout definitely charged nothing.
122
+ let newCheckoutHref = null;
123
+ function remember(result) {
124
+ if (result.payment_succeeded === true || result.state === "paid") paymentSucceeded = true;
125
+ }
126
+
127
+ /** One call to the store's server. No answer, a timeout or an unreadable one is "unknown". */
128
+ async function call(path, body) {
129
+ try {
130
+ const response = await fetch(path, {
131
+ method: "POST",
132
+ headers: { "Content-Type": "application/json" },
133
+ body: JSON.stringify(body),
134
+ signal: AbortSignal.timeout(30_000),
135
+ });
136
+ const result = await response.json();
137
+ return typeof result?.state === "string" ? result : { state: "unknown" };
138
+ } catch {
139
+ return { state: "unknown" };
140
+ }
141
+ }
142
+
143
+ function paid(result) {
144
+ window.location.assign(`/orders/thanks?order=${encodeURIComponent(result.order ?? "")}`);
145
+ }
146
+
147
+ /**
148
+ * A definite non-charge: `closed`, or `not_found` answering this page's own
149
+ * Pay request (the server had no checkout, so it sent nothing). This checkout
150
+ * is over, so Pay is never left stuck. It becomes "Try again", which opens a
151
+ * new checkout (new order reference) instead of paying here.
152
+ */
153
+ function offerNewCheckout(message) {
154
+ status.textContent = message;
155
+ newCheckoutHref = form?.dataset.newCheckout || "/checkout?new=1";
156
+ if (button) {
157
+ button.textContent = "Try again";
158
+ button.disabled = false;
159
+ }
160
+ }
161
+
162
+ /** Keep known success even when a later answer is lost or unreadable. */
163
+ function showPending(message) {
164
+ if (button) button.disabled = true;
165
+ const link = document.createElement("a");
166
+ link.href = statusUrl;
167
+ link.textContent = "Check your order status";
168
+ status.replaceChildren(`${paymentSucceeded ? orderPending : message} `, link);
169
+ }
170
+
171
+ /**
172
+ * After a payment was sent (or may have been): ask the server until the
173
+ * outcome is final. The server only replays the attempt it already has, with
174
+ * the same Idempotency-Key, so this never charges again.
175
+ */
176
+ async function confirmOutcome() {
177
+ for (let attempt = 0; attempt < 30; attempt += 1) {
178
+ const result = await call("/checkout/confirm", { orderReference: reference });
179
+ remember(result);
180
+ if (result.state === "paid" && result.order) return paid(result);
181
+ if (!paymentSucceeded && result.state === "open") {
182
+ // The server never received the payment: nothing was sent, so Pay is safe again.
183
+ status.textContent = result.message;
184
+ attemptSent = false;
185
+ if (button) button.disabled = false;
186
+ return;
187
+ }
188
+ if (!paymentSucceeded && result.state === "closed") {
189
+ return offerNewCheckout(result.message); // nothing was charged
190
+ }
191
+ if (result.state === "not_found") {
192
+ // A payment may already have been sent: a missing record is not proof
193
+ // that nothing was charged. Never offer a new checkout from here.
194
+ return showPending("We can't find this payment to confirm it. Don't pay again: check your order status or contact the store.");
195
+ }
196
+ showPending(result.state === "pending" ? result.message : "We can't confirm your payment yet. Don't pay again.");
197
+ await sleep(Math.min(30_000, 2_000 * 2 ** Math.min(attempt, 4)));
198
+ }
199
+ // Still not final: the server keeps checking. Pay stays disabled.
200
+ showPending("We're still confirming your payment. Don't pay again.");
201
+ }
202
+
203
+ if (form) {
204
+ fields.addEventListener("relyon-ready", () => { if (!attemptSent) button.disabled = false; });
205
+ fields.addEventListener("relyon-error", (event) => { if (!attemptSent) status.textContent = event.detail.message; });
206
+ // The card fields script loads async, so the fields can be ready before
207
+ // this script runs. The page's ready latch (above fields.html) recorded it.
208
+ button.disabled = fields.dataset.relyonReady !== "true";
209
+
210
+ /** Sends a tokenized method to the store's server and follows the outcome. */
211
+ async function pay(paymentMethod) {
212
+ status.textContent = "Paying…";
213
+ // Only the order reference and the token. Never totals: the server re-prices.
214
+ const result = await call("/checkout/pay", { orderReference: reference, paymentMethod });
215
+ remember(result);
216
+ if (result.state === "paid" && result.order) return paid(result);
217
+ if (!paymentSucceeded && result.state === "open") {
218
+ status.textContent = result.message; // the server sent nothing
219
+ attemptSent = false;
220
+ if (button) button.disabled = false;
221
+ return;
222
+ }
223
+ if (!paymentSucceeded && (result.state === "closed" || result.state === "not_found")) {
224
+ return offerNewCheckout(result.message); // declined or refused: nothing was charged
225
+ }
226
+ // "pending" or no usable answer: the payment may have gone through.
227
+ showPending(result.state === "pending" ? result.message : "We can't confirm your payment yet. Don't pay again.");
228
+ await confirmOutcome();
229
+ }
230
+
231
+ form.addEventListener("submit", async (event) => {
232
+ event.preventDefault();
233
+ if (newCheckoutHref) return window.location.assign(newCheckoutHref); // "Try again": a new checkout
234
+ if (attemptSent) return; // late ready events or duplicate submissions cannot start a new attempt
235
+ attemptSent = true;
236
+ button.disabled = true;
237
+ let paymentMethod;
238
+ try {
239
+ // Resolves to the payment_method object; the card data stays in the fields.
240
+ paymentMethod = await fields.tokenize();
241
+ } catch (error) {
242
+ status.textContent = error.message; // incomplete card details; nothing was sent
243
+ attemptSent = false;
244
+ button.disabled = false;
245
+ return;
246
+ }
247
+ await pay(paymentMethod);
248
+ });
249
+
250
+ // Google Pay (only rendered when the store enabled it): the wallet sheet's
251
+ // answer arrives as an event. Submit at once — the wallet's cardSecurity
252
+ // expires about a minute after the sheet closes.
253
+ fields.addEventListener("relyon-payment", (event) => {
254
+ if (newCheckoutHref || attemptSent || !event.detail?.paymentMethod) return;
255
+ attemptSent = true;
256
+ if (button) button.disabled = true;
257
+ void pay(event.detail.paymentMethod);
258
+ });
259
+ // A cancelled sheet sent nothing: the shopper can pay by card instead.
260
+ fields.addEventListener("relyon-payment-cancelled", () => {
261
+ status.textContent = "Google Pay was cancelled. You can pay by card instead.";
262
+ });
263
+ } else if (page.dataset.state === "pending") {
264
+ // Render the saved evidence before the first poll, including after a reload.
265
+ if (paymentSucceeded) showPending(orderPending);
266
+ void confirmOutcome();
267
+ }
268
+ ```
269
+
270
+ - `relyon-ready` fires when the fields can take a card; `relyon-error`
271
+ carries a message to show the shopper.
272
+ - When the store enabled Google Pay, the fields render its button and a
273
+ completed sheet fires `relyon-payment` with the tokenized method; the page
274
+ submits it immediately because the wallet's `cardSecurity` expires about a
275
+ minute after the sheet closes. `relyon-payment-cancelled` means the shopper
276
+ backed out and nothing was sent.
277
+ - Pay is enabled by whichever comes first: the `relyon-ready` listener, or
278
+ the ready latch's `data-relyon-ready` mark when the fields were ready before
279
+ `/checkout.js` ran. Without the latch, Pay can stay disabled forever.
280
+ - `tokenize()` rejects when the card details are incomplete. Nothing was sent,
281
+ so the page lets the shopper fix them and press Pay again.
282
+ - Once `/checkout/pay` was called, Pay is enabled again only when the server
283
+ says the checkout is still `open` (nothing was sent). After a definite
284
+ non-charge (`closed`: declined or refused; or `not_found` as the answer to
285
+ the Pay request itself, so nothing was sent) the button is never left
286
+ stuck: it becomes **Try again**, which opens a new checkout
287
+ (`data-new-checkout` on the form, such as `/checkout?…&new=1`) with a new
288
+ order reference. It never pays again under the closed reference, and it is
289
+ never offered while a payment may have gone through. A lost connection, a
290
+ timeout, a `5xx` or a `pending` answer means the payment may have gone
291
+ through: the page says so, links to the order status page and keeps asking
292
+ `/checkout/confirm`. It never says "didn't go through" unless the server
293
+ answered `closed`. A `not_found` from `/checkout/confirm` (after a payment
294
+ may have been sent, for example when the server lost its record) is not
295
+ proof of a non-charge: Pay stays disabled with the status link and no
296
+ **Try again**.
297
+ - The page never reloads itself. It polls `/checkout/confirm` with `fetch`
298
+ and stops on a final answer; calling `location.reload()` from a status
299
+ answer (or a status page that sends the browser back to itself) is how a page
300
+ reload loop starts.
301
+ - A reload while a payment is being confirmed shows the order status page
302
+ (the server remembers the shopper's order reference), not new card fields,
303
+ so it can't start a second payment.
304
+ - For `payment_succeeded: true`, show exactly "Your payment went through. Your
305
+ order is still being placed" immediately, while polling and after polling
306
+ stops. Keep the status link and Pay disabled. The status page's
307
+ `data-payment-succeeded` restores that evidence on reload. Lost or unreadable
308
+ answers never erase it; genuinely unknown outcomes keep their cautious wording.
309
+ - Ignore late card-field events once an attempt starts, and only navigate to
310
+ the thank-you page when the server returns a saved store order.
311
+ - The thank-you page is the app's own. Showing it is not proof of payment;
312
+ the server's `createPayment` result and `createOrder` are.
313
+ - In Test without a processor sandbox account, the fields show a Test notice
314
+ and `tokenize()` returns a mock payment method the Test processor accepts.
315
+ Never type real card numbers in Test.