@oxvo/ai-live-assist 7.5.19 → 7.5.21

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 (99) hide show
  1. package/cjs/AiLiveAssist.d.ts +8 -1
  2. package/cjs/AiLiveAssist.js +113 -8
  3. package/cjs/client.d.ts +5 -3
  4. package/cjs/client.js +44 -5
  5. package/cjs/commerce/cartContracts.d.ts +158 -0
  6. package/cjs/commerce/cartContracts.js +228 -0
  7. package/cjs/commerce/cartSession.d.ts +86 -0
  8. package/cjs/commerce/cartSession.js +475 -0
  9. package/cjs/commerce/contracts.d.ts +152 -0
  10. package/cjs/commerce/contracts.js +322 -0
  11. package/cjs/commerce/pageContext.d.ts +50 -0
  12. package/cjs/commerce/pageContext.js +173 -0
  13. package/cjs/commerce/productPanel.d.ts +65 -0
  14. package/cjs/commerce/productPanel.js +662 -0
  15. package/cjs/commerce/realtimeCommerce.d.ts +73 -0
  16. package/cjs/commerce/realtimeCommerce.js +342 -0
  17. package/cjs/commerce/shopifyCart.d.ts +130 -0
  18. package/cjs/commerce/shopifyCart.js +1135 -0
  19. package/cjs/commerce/shopifyCartPresentation.d.ts +12 -0
  20. package/cjs/commerce/shopifyCartPresentation.js +379 -0
  21. package/cjs/commerce/shoppingNotes.d.ts +61 -0
  22. package/cjs/commerce/shoppingNotes.js +313 -0
  23. package/cjs/commerce/shoppingNotesView.d.ts +46 -0
  24. package/cjs/commerce/shoppingNotesView.js +269 -0
  25. package/cjs/control.d.ts +9 -1
  26. package/cjs/control.js +51 -1
  27. package/cjs/guideAdmission.d.ts +5 -2
  28. package/cjs/guideAdmission.js +21 -2
  29. package/cjs/guideInstaller.js +1 -1
  30. package/cjs/guideMeasurement.d.ts +5 -0
  31. package/cjs/guideMeasurement.js +29 -0
  32. package/cjs/guideSubjectStore.js +2 -0
  33. package/cjs/guideTypes.d.ts +18 -0
  34. package/cjs/liveControlChannel.d.ts +43 -1
  35. package/cjs/liveControlChannel.js +166 -14
  36. package/cjs/liveGuideAdmission.d.ts +3 -2
  37. package/cjs/liveGuideAdmission.js +10 -2
  38. package/cjs/liveGuideWidget.d.ts +18 -0
  39. package/cjs/liveGuideWidget.js +228 -23
  40. package/cjs/locales/resources.js +2240 -0
  41. package/cjs/messages.js +56 -0
  42. package/cjs/tabLock.d.ts +2 -0
  43. package/cjs/tabLock.js +11 -1
  44. package/cjs/types.d.ts +6 -2
  45. package/cjs/types.js +56 -0
  46. package/cjs/ui.d.ts +37 -0
  47. package/cjs/ui.js +261 -9
  48. package/cjs/version.d.ts +1 -1
  49. package/cjs/version.js +1 -1
  50. package/lib/AiLiveAssist.d.ts +8 -1
  51. package/lib/AiLiveAssist.js +113 -8
  52. package/lib/client.d.ts +5 -3
  53. package/lib/client.js +44 -5
  54. package/lib/commerce/cartContracts.d.ts +158 -0
  55. package/lib/commerce/cartContracts.js +221 -0
  56. package/lib/commerce/cartSession.d.ts +86 -0
  57. package/lib/commerce/cartSession.js +471 -0
  58. package/lib/commerce/contracts.d.ts +152 -0
  59. package/lib/commerce/contracts.js +300 -0
  60. package/lib/commerce/pageContext.d.ts +50 -0
  61. package/lib/commerce/pageContext.js +168 -0
  62. package/lib/commerce/productPanel.d.ts +65 -0
  63. package/lib/commerce/productPanel.js +657 -0
  64. package/lib/commerce/realtimeCommerce.d.ts +73 -0
  65. package/lib/commerce/realtimeCommerce.js +337 -0
  66. package/lib/commerce/shopifyCart.d.ts +130 -0
  67. package/lib/commerce/shopifyCart.js +1130 -0
  68. package/lib/commerce/shopifyCartPresentation.d.ts +12 -0
  69. package/lib/commerce/shopifyCartPresentation.js +376 -0
  70. package/lib/commerce/shoppingNotes.d.ts +61 -0
  71. package/lib/commerce/shoppingNotes.js +307 -0
  72. package/lib/commerce/shoppingNotesView.d.ts +46 -0
  73. package/lib/commerce/shoppingNotesView.js +265 -0
  74. package/lib/control.d.ts +9 -1
  75. package/lib/control.js +51 -1
  76. package/lib/guideAdmission.d.ts +5 -2
  77. package/lib/guideAdmission.js +21 -2
  78. package/lib/guideInstaller.js +1 -1
  79. package/lib/guideMeasurement.d.ts +5 -0
  80. package/lib/guideMeasurement.js +24 -0
  81. package/lib/guideSubjectStore.js +2 -0
  82. package/lib/guideTypes.d.ts +18 -0
  83. package/lib/liveControlChannel.d.ts +43 -1
  84. package/lib/liveControlChannel.js +166 -14
  85. package/lib/liveGuideAdmission.d.ts +3 -2
  86. package/lib/liveGuideAdmission.js +10 -2
  87. package/lib/liveGuideWidget.d.ts +18 -0
  88. package/lib/liveGuideWidget.js +228 -23
  89. package/lib/locales/resources.js +2240 -0
  90. package/lib/messages.js +56 -0
  91. package/lib/tabLock.d.ts +2 -0
  92. package/lib/tabLock.js +11 -1
  93. package/lib/types.d.ts +6 -2
  94. package/lib/types.js +56 -0
  95. package/lib/ui.d.ts +37 -0
  96. package/lib/ui.js +261 -9
  97. package/lib/version.d.ts +1 -1
  98. package/lib/version.js +1 -1
  99. package/package.json +1 -1
@@ -0,0 +1,1130 @@
1
+ import { commerceUuid, isCommerceMarket, isCommerceOptions, isCommerceStore, sameCommerceMarket, } from "./contracts.js";
2
+ import { readShopifyCommerceContext } from "./pageContext.js";
3
+ const PROPERTY = "_oxvo_guide_operation";
4
+ const RESPONSE_BYTES = 512000;
5
+ const REQUEST_MS = 5000;
6
+ const LEDGER_LIMIT = 32;
7
+ const PREPARED_BYTES = 8192;
8
+ const LEDGER_BYTES = LEDGER_LIMIT * (PREPARED_BYTES + 2048);
9
+ const RETAIN_MS = 86400000;
10
+ const sha = async (value) => [
11
+ ...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))),
12
+ ]
13
+ .map((byte) => byte.toString(16).padStart(2, "0"))
14
+ .join("");
15
+ const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
16
+ const count = (value) => Number.isSafeInteger(value) && Number(value) >= 0;
17
+ const positive = (value) => count(value) && value > 0;
18
+ const id = (value) => {
19
+ const text = typeof value === "number" && Number.isSafeInteger(value)
20
+ ? String(value)
21
+ : value;
22
+ return typeof text === "string" &&
23
+ /^[1-9]\d{0,19}$/u.test(text) &&
24
+ BigInt(text) <= 18446744073709551615n
25
+ ? text
26
+ : null;
27
+ };
28
+ const result = (status, reason) => ({
29
+ status,
30
+ reason,
31
+ canUndo: false,
32
+ receipt: null,
33
+ execution: null,
34
+ local: { itemCount: null },
35
+ });
36
+ const reportScopeIdentity = (value) => JSON.stringify([
37
+ value.schemaVersion,
38
+ value.requestId,
39
+ value.operationId,
40
+ value.proposalChecksum,
41
+ value.contextDigest,
42
+ value.contextRevision,
43
+ value.pageId,
44
+ value.provider.kind,
45
+ value.provider.kind === "live"
46
+ ? [value.provider.taskId, value.provider.inputEpoch]
47
+ : value.provider.generationDigest,
48
+ ]);
49
+ const pendingEntry = (entry, sessionId) => !entry.resolved ||
50
+ (!!entry.prepared?.reportScope &&
51
+ !entry.reportAccepted &&
52
+ (!sessionId ||
53
+ !entry.prepared.reportSessionId ||
54
+ entry.prepared.reportSessionId === sessionId));
55
+ const intent = (value) => JSON.stringify([
56
+ value.operationId,
57
+ value.operationMarker,
58
+ value.guideId,
59
+ value.store.provider,
60
+ value.store.storeRef,
61
+ value.store.origin,
62
+ value.store.policyRevision,
63
+ value.market.country,
64
+ value.market.locale,
65
+ value.market.currency,
66
+ value.productRef,
67
+ value.variantRef,
68
+ value.shopifyVariantId,
69
+ [...value.selectedOptions]
70
+ .sort((left, right) => left.name.localeCompare(right.name))
71
+ .map((option) => [option.name, option.value]),
72
+ value.quantity,
73
+ value.unitPrice.amount,
74
+ value.unitPrice.currency,
75
+ value.quantityRule.minimum,
76
+ value.quantityRule.maximum,
77
+ value.quantityRule.increment,
78
+ value.productUrl,
79
+ value.expiresAt,
80
+ value.requiresSellingPlan,
81
+ value.requiresComponents,
82
+ value.reportScope ? reportScopeIdentity(value.reportScope) : null,
83
+ value.reportSessionId ?? null,
84
+ ]);
85
+ /** Theme money uses integer hundredths, including JPY/KRW's appended hundredths.
86
+ * Three/four-decimal currencies are deliberately unsupported until their Ajax
87
+ * representation is separately qualified. No Number rounding can approve a price.
88
+ * https://shopify.dev/docs/api/liquid/objects/variant#variant-price
89
+ * https://shopify.dev/docs/api/ajax/reference/product
90
+ */
91
+ function ajaxPrice(amount, currency) {
92
+ if (!/^(?:0|[1-9]\d{0,9})(?:\.\d{1,6})?$/u.test(amount))
93
+ return null;
94
+ const digits = new Intl.NumberFormat("en", {
95
+ style: "currency",
96
+ currency,
97
+ }).resolvedOptions().maximumFractionDigits;
98
+ if (digits !== 0 && digits !== 2)
99
+ return null;
100
+ const [whole = "0", fraction = ""] = amount.split(".");
101
+ if (digits === 0 && /[^0]/u.test(fraction))
102
+ return null;
103
+ if (/[^0]/u.test(fraction.slice(2)))
104
+ return null;
105
+ const value = BigInt(whole) * 100n + BigInt(fraction.slice(0, 2).padEnd(2, "0"));
106
+ return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : null;
107
+ }
108
+ const decimal = (price) => `${BigInt(price) / 100n}.${String(BigInt(price) % 100n).padStart(2, "0")}`;
109
+ function validPrepared(value) {
110
+ const rule = value.quantityRule;
111
+ return (commerceUuid(value.operationId) &&
112
+ commerceUuid(value.operationMarker) &&
113
+ value.operationMarker !== value.operationId &&
114
+ commerceUuid(value.guideId) &&
115
+ isCommerceStore(value.store) &&
116
+ isCommerceMarket(value.market) &&
117
+ /^gid:\/\/shopify\/Product\/[1-9]\d{0,19}$/u.test(value.productRef) &&
118
+ id(value.productRef.split("/").pop()) !== null &&
119
+ typeof value.shopifyVariantId === "string" &&
120
+ id(value.shopifyVariantId) === value.shopifyVariantId &&
121
+ value.variantRef ===
122
+ `gid://shopify/ProductVariant/${value.shopifyVariantId}` &&
123
+ isCommerceOptions(value.selectedOptions) &&
124
+ positive(value.quantity) &&
125
+ object(rule) &&
126
+ positive(rule.minimum) &&
127
+ positive(rule.increment) &&
128
+ (rule.maximum === null || positive(rule.maximum)) &&
129
+ rule.minimum % rule.increment === 0 &&
130
+ (rule.maximum === null ||
131
+ (rule.maximum >= rule.minimum && rule.maximum % rule.increment === 0)) &&
132
+ value.quantity >= rule.minimum &&
133
+ (rule.maximum === null || value.quantity <= rule.maximum) &&
134
+ value.quantity % rule.increment === 0 &&
135
+ object(value.unitPrice) &&
136
+ typeof value.unitPrice.amount === "string" &&
137
+ value.unitPrice.currency === value.market.currency &&
138
+ typeof value.productUrl === "string" &&
139
+ value.productUrl.length <= 2048 &&
140
+ typeof value.expiresAt === "string" &&
141
+ Number.isFinite(Date.parse(value.expiresAt)) &&
142
+ value.requiresSellingPlan === false &&
143
+ value.requiresComponents === false &&
144
+ (value.reportScope === undefined ||
145
+ validReportScope(value.reportScope, value.operationId)) &&
146
+ (value.reportSessionId === undefined ||
147
+ (!!value.reportScope && validSessionId(value.reportSessionId))));
148
+ }
149
+ function route(prepared, requireMarket = true) {
150
+ if (window.location.protocol !== "https:" ||
151
+ window.location.origin !== prepared.store.origin)
152
+ return null;
153
+ const shopify = window.Shopify;
154
+ const root = shopify?.routes?.root;
155
+ // Shopify provides either / or a single locale/market prefix, never a caller URL.
156
+ if (typeof root !== "string" ||
157
+ !/^\/(?:[a-z]{2,3}(?:-[a-z0-9]{2,8})*\/)?$/iu.test(root))
158
+ return null;
159
+ const current = readShopifyCommerceContext(window, { pageId: prepared.operationId, contextRevision: 0 }, false);
160
+ if (requireMarket &&
161
+ (!current || !sameCommerceMarket(current.market, prepared.market)))
162
+ return null;
163
+ try {
164
+ const url = new URL(prepared.productUrl);
165
+ if (url.origin !== prepared.store.origin ||
166
+ url.username ||
167
+ url.password ||
168
+ url.hash ||
169
+ /[\\\s]/u.test(prepared.productUrl))
170
+ return null;
171
+ const handle = /^\/(?:[a-z]{2,3}(?:-[a-z0-9]{2,8})*\/)?products\/([a-z0-9][a-z0-9-]{0,254})\/?$/iu.exec(url.pathname)?.[1];
172
+ if (!handle)
173
+ return null;
174
+ return { root, product: `${root}products/${handle}.js` };
175
+ }
176
+ catch {
177
+ return null;
178
+ }
179
+ }
180
+ class AjaxTransportError extends Error {
181
+ constructor(outcome) {
182
+ super("transport");
183
+ this.outcome = outcome;
184
+ }
185
+ }
186
+ async function request(path, body, onResponse) {
187
+ const controller = new AbortController();
188
+ let timer;
189
+ let timedOut = false;
190
+ const deadline = new Promise((_resolve, reject) => {
191
+ timer = setTimeout(() => {
192
+ timedOut = true;
193
+ controller.abort();
194
+ reject(new AjaxTransportError("timeout"));
195
+ }, REQUEST_MS);
196
+ });
197
+ const task = (async () => {
198
+ const response = await fetch(path, {
199
+ method: body === undefined ? "GET" : "POST",
200
+ mode: "same-origin",
201
+ credentials: "same-origin",
202
+ redirect: "error",
203
+ cache: "no-store",
204
+ headers: {
205
+ Accept: "application/json",
206
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
207
+ },
208
+ ...(body === undefined ? {} : { body }),
209
+ signal: controller.signal,
210
+ });
211
+ if (!Number.isInteger(response.status) ||
212
+ response.status < 200 ||
213
+ response.status > 599)
214
+ throw new AjaxTransportError("network_error");
215
+ onResponse?.(response.status);
216
+ if (!/^application\/json(?:;|$)/iu.test(response.headers.get("content-type") ?? "") ||
217
+ Number(response.headers.get("content-length") ?? "0") > RESPONSE_BYTES ||
218
+ response.redirected)
219
+ throw new Error("transport");
220
+ if (!response.body)
221
+ throw new Error("transport");
222
+ const reader = response.body.getReader();
223
+ const decoder = new TextDecoder("utf-8", { fatal: true });
224
+ let size = 0;
225
+ let text = "";
226
+ try {
227
+ while (true) {
228
+ const next = await reader.read();
229
+ if (next.done)
230
+ break;
231
+ size += next.value.byteLength;
232
+ if (size > RESPONSE_BYTES)
233
+ throw new Error("transport");
234
+ text += decoder.decode(next.value, { stream: true });
235
+ }
236
+ text += decoder.decode();
237
+ return { status: response.status, value: JSON.parse(text) };
238
+ }
239
+ finally {
240
+ void reader.cancel().catch(() => undefined);
241
+ }
242
+ })();
243
+ try {
244
+ return await Promise.race([task, deadline]);
245
+ }
246
+ catch (error) {
247
+ if (timedOut)
248
+ throw new AjaxTransportError("timeout");
249
+ if (error instanceof AjaxTransportError)
250
+ throw error;
251
+ throw new AjaxTransportError(error instanceof Error && error.name === "AbortError"
252
+ ? "aborted"
253
+ : "network_error");
254
+ }
255
+ finally {
256
+ clearTimeout(timer);
257
+ controller.abort();
258
+ }
259
+ }
260
+ /** A same-origin navigation link, never a mutation URL or a caller-selected path. */
261
+ export function getShopifyCartUrl(prepared) {
262
+ try {
263
+ if (!validPrepared(prepared))
264
+ return null;
265
+ const paths = route(prepared);
266
+ return paths ? `${prepared.store.origin}${paths.root}cart` : null;
267
+ }
268
+ catch {
269
+ return null;
270
+ }
271
+ }
272
+ function parseCart(value) {
273
+ if (!object(value) ||
274
+ typeof value.token !== "string" ||
275
+ !value.token ||
276
+ value.token.length > 512 ||
277
+ typeof value.currency !== "string" ||
278
+ !/^[A-Z]{3}$/u.test(value.currency) ||
279
+ !count(value.item_count) ||
280
+ !Array.isArray(value.items) ||
281
+ value.items.length > 250 ||
282
+ !value.items.every((line) => object(line) && positive(line.quantity)))
283
+ throw new Error("transport");
284
+ const items = value.items;
285
+ if (items.reduce((sum, line) => sum + Number(line.quantity), 0) !==
286
+ value.item_count)
287
+ throw new Error("transport");
288
+ return {
289
+ token: value.token,
290
+ currency: value.currency,
291
+ itemCount: value.item_count,
292
+ items,
293
+ };
294
+ }
295
+ async function readCart(root) {
296
+ const response = await request(`${root}cart.js`);
297
+ if (response.status !== 200)
298
+ throw new Error("transport");
299
+ return parseCart(response.value);
300
+ }
301
+ function preflightProduct(value, prepared, price) {
302
+ if (!object(value) ||
303
+ `gid://shopify/Product/${id(value.id)}` !== prepared.productRef ||
304
+ !Array.isArray(value.variants) ||
305
+ value.variants.length > 250 ||
306
+ !Array.isArray(value.options) ||
307
+ value.options.length > 3 ||
308
+ value.requires_selling_plan === true ||
309
+ value.requires_components === true ||
310
+ value.gift_card === true ||
311
+ (Array.isArray(value.selling_plan_groups) &&
312
+ value.selling_plan_groups.length > 0))
313
+ return false;
314
+ const matches = value.variants.filter((variant) => object(variant) && id(variant.id) === prepared.shopifyVariantId);
315
+ if (matches.length !== 1)
316
+ return false;
317
+ const variant = matches[0];
318
+ if (variant.available !== true ||
319
+ variant.price !== price ||
320
+ variant.requires_selling_plan === true ||
321
+ variant.requires_components === true ||
322
+ (Array.isArray(variant.selling_plan_allocations) &&
323
+ variant.selling_plan_allocations.length > 0) ||
324
+ !Array.isArray(variant.options) ||
325
+ variant.options.length !== value.options.length ||
326
+ prepared.selectedOptions.length !== value.options.length)
327
+ return false;
328
+ const options = value.options;
329
+ if (!options.every((option, index) => object(option) &&
330
+ typeof option.name === "string" &&
331
+ option.position === index + 1 &&
332
+ prepared.selectedOptions.some((choice) => choice.name === option.name &&
333
+ choice.value === variant.options[index])))
334
+ return false;
335
+ return sameRule(variant.quantity_rule, prepared.quantityRule);
336
+ }
337
+ function sameRule(raw, expected) {
338
+ const rule = raw === undefined ? { min: 1, max: null, increment: 1 } : raw;
339
+ return (object(rule) &&
340
+ rule.min === expected.minimum &&
341
+ rule.max === expected.maximum &&
342
+ rule.increment === expected.increment);
343
+ }
344
+ function sameOptions(value, expected) {
345
+ return (isCommerceOptions(value) &&
346
+ value.length === expected.length &&
347
+ value.every((option) => expected.some((choice) => choice.name === option.name && choice.value === option.value)));
348
+ }
349
+ const validSessionId = commerceUuid;
350
+ function validReportScope(value, operationId) {
351
+ if (!object(value) ||
352
+ Object.keys(value).length !== 8 ||
353
+ value.schemaVersion !== 1 ||
354
+ !commerceUuid(value.requestId) ||
355
+ value.operationId !== operationId ||
356
+ typeof value.proposalChecksum !== "string" ||
357
+ !/^[0-9a-f]{64}$/u.test(value.proposalChecksum) ||
358
+ typeof value.contextDigest !== "string" ||
359
+ !/^[0-9a-f]{64}$/u.test(value.contextDigest) ||
360
+ !count(value.contextRevision) ||
361
+ typeof value.pageId !== "string" ||
362
+ !value.pageId ||
363
+ value.pageId.length > 128 ||
364
+ /[\s\u0000-\u001f\u007f]/u.test(value.pageId) ||
365
+ !object(value.provider))
366
+ return false;
367
+ const provider = value.provider;
368
+ return provider.kind === "live"
369
+ ? Object.keys(provider).length === 3 &&
370
+ commerceUuid(provider.taskId) &&
371
+ count(provider.inputEpoch)
372
+ : provider.kind === "realtime" &&
373
+ Object.keys(provider).length === 2 &&
374
+ typeof provider.generationDigest === "string" &&
375
+ /^[0-9a-f]{64}$/u.test(provider.generationDigest);
376
+ }
377
+ /** Explicit projection prevents an upstream grant/token field hitchhiking into browser storage. */
378
+ function publicPrepared(value) {
379
+ const { operationId, operationMarker, guideId, productRef, variantRef, shopifyVariantId, quantity, productUrl, expiresAt, requiresSellingPlan, requiresComponents, } = value;
380
+ return {
381
+ operationId,
382
+ operationMarker,
383
+ guideId,
384
+ productRef,
385
+ variantRef,
386
+ shopifyVariantId,
387
+ quantity,
388
+ productUrl,
389
+ expiresAt,
390
+ requiresSellingPlan,
391
+ requiresComponents,
392
+ store: {
393
+ provider: value.store.provider,
394
+ storeRef: value.store.storeRef,
395
+ origin: value.store.origin,
396
+ policyRevision: value.store.policyRevision,
397
+ },
398
+ market: {
399
+ country: value.market.country,
400
+ locale: value.market.locale,
401
+ currency: value.market.currency,
402
+ },
403
+ selectedOptions: value.selectedOptions.map(({ name, value: option }) => ({
404
+ name,
405
+ value: option,
406
+ })),
407
+ unitPrice: {
408
+ amount: value.unitPrice.amount,
409
+ currency: value.unitPrice.currency,
410
+ },
411
+ quantityRule: {
412
+ minimum: value.quantityRule.minimum,
413
+ maximum: value.quantityRule.maximum,
414
+ increment: value.quantityRule.increment,
415
+ },
416
+ ...(value.reportSessionId
417
+ ? { reportSessionId: value.reportSessionId }
418
+ : {}),
419
+ ...(value.reportScope
420
+ ? {
421
+ reportScope: JSON.parse(JSON.stringify(value.reportScope)),
422
+ }
423
+ : {}),
424
+ };
425
+ }
426
+ const ledgerKey = (scope) => `__oxvo_guide_cart_v1:${encodeURIComponent(scope.store.storeRef)}:${scope.guideId}`;
427
+ const validLedgerScope = (scope) => commerceUuid(scope.guideId) &&
428
+ isCommerceStore(scope.store) &&
429
+ window.location.protocol === "https:" &&
430
+ window.location.origin === scope.store.origin &&
431
+ (scope.sessionId === undefined || validSessionId(scope.sessionId));
432
+ function validSavedPrepared(value, operationId) {
433
+ try {
434
+ return (object(value) &&
435
+ value.operationId === operationId &&
436
+ JSON.stringify(value).length <= PREPARED_BYTES &&
437
+ validPrepared(value));
438
+ }
439
+ catch {
440
+ return false;
441
+ }
442
+ }
443
+ function validSavedObservation(value, prepared) {
444
+ return (object(value) &&
445
+ Object.keys(value).length === 7 &&
446
+ !!prepared &&
447
+ value.source === "browser_cart" &&
448
+ typeof value.observedAt === "string" &&
449
+ Number.isFinite(Date.parse(value.observedAt)) &&
450
+ value.currency === prepared.market.currency &&
451
+ value.shopifyVariantId === prepared.shopifyVariantId &&
452
+ value.operationMarker === prepared.operationMarker &&
453
+ positive(value.quantity) &&
454
+ value.quantity <= prepared.quantity &&
455
+ typeof value.lineKeyDigest === "string" &&
456
+ /^[0-9a-f]{64}$/u.test(value.lineKeyDigest));
457
+ }
458
+ function readLedger(key) {
459
+ const raw = localStorage.getItem(key);
460
+ if (raw === null)
461
+ return [];
462
+ if (raw.length > LEDGER_BYTES)
463
+ throw new Error("storage");
464
+ const value = JSON.parse(raw);
465
+ if (!Array.isArray(value) ||
466
+ value.length > LEDGER_LIMIT ||
467
+ !value.every((entry) => object(entry) &&
468
+ commerceUuid(entry.operationId) &&
469
+ commerceUuid(entry.executionId) &&
470
+ typeof entry.intentDigest === "string" &&
471
+ /^[0-9a-f]{64}$/u.test(entry.intentDigest) &&
472
+ typeof entry.cartDigest === "string" &&
473
+ /^[0-9a-f]{64}$/u.test(entry.cartDigest) &&
474
+ count(entry.expiresAt) &&
475
+ (entry.request == null || validRequestOutcome(entry.request)) &&
476
+ (entry.prepared == null ||
477
+ validSavedPrepared(entry.prepared, entry.operationId)) &&
478
+ (entry.observation == null ||
479
+ validSavedObservation(entry.observation, entry.prepared)) &&
480
+ (entry.reportAccepted === undefined ||
481
+ entry.reportAccepted === false ||
482
+ (entry.reportAccepted === true && entry.resolved === true)) &&
483
+ (entry.resolved === undefined ||
484
+ entry.resolved === false ||
485
+ (entry.resolved === true && entry.observation != null))) ||
486
+ new Set(value.map((entry) => entry.operationId)).size !== value.length)
487
+ throw new Error("storage");
488
+ return (value
489
+ // An ambiguous write never expires into permission to add again.
490
+ .filter((entry) => pendingEntry(entry) || entry.expiresAt + RETAIN_MS > Date.now())
491
+ .map((entry) => ({
492
+ ...entry,
493
+ request: entry.request ?? null,
494
+ prepared: entry.prepared ? publicPrepared(entry.prepared) : null,
495
+ observation: entry.observation ?? null,
496
+ resolved: entry.resolved === true,
497
+ reportAccepted: entry.reportAccepted === true,
498
+ })));
499
+ }
500
+ function saveLedger(key, entries) {
501
+ const value = JSON.stringify(entries);
502
+ if (entries.length > LEDGER_LIMIT || value.length > LEDGER_BYTES)
503
+ throw new Error("storage");
504
+ localStorage.setItem(key, value);
505
+ if (localStorage.getItem(key) !== value)
506
+ throw new Error("storage");
507
+ }
508
+ function saveStarted(key, entries, entry) {
509
+ saveLedger(key, [...entries, entry]);
510
+ }
511
+ const sameStarted = (left, right) => left.operationId === right.operationId &&
512
+ left.executionId === right.executionId &&
513
+ left.cartDigest === right.cartDigest &&
514
+ left.intentDigest === right.intentDigest;
515
+ function validRequestOutcome(value) {
516
+ return (object(value) &&
517
+ ((Object.keys(value).length === 2 &&
518
+ value.outcome === "response" &&
519
+ Number.isInteger(value.httpStatus) &&
520
+ Number(value.httpStatus) >= 200 &&
521
+ Number(value.httpStatus) <= 599) ||
522
+ (Object.keys(value).length === 1 &&
523
+ typeof value.outcome === "string" &&
524
+ ["timeout", "network_error", "aborted", "unknown"].includes(value.outcome))));
525
+ }
526
+ function validReady(value) {
527
+ return (object(value) &&
528
+ (value.state === "prepared" || value.state === "already_started") &&
529
+ commerceUuid(value.executionId) &&
530
+ typeof value.cartDigest === "string" &&
531
+ /^[0-9a-f]{64}$/u.test(value.cartDigest) &&
532
+ typeof value.expiresAt === "string" &&
533
+ Number.isFinite(Date.parse(value.expiresAt)));
534
+ }
535
+ function evidence(entry) {
536
+ return {
537
+ executionId: entry.executionId,
538
+ cartDigest: entry.cartDigest,
539
+ request: entry.request ?? { outcome: "unknown" },
540
+ observation: null,
541
+ };
542
+ }
543
+ function retainedOutcome(prepared, entry) {
544
+ const observation = entry.observation;
545
+ const complete = observation.quantity === prepared.quantity;
546
+ return {
547
+ ...result(complete ? "confirmed" : "partial", complete ? "matched" : "partial_quantity"),
548
+ execution: { ...evidence(entry), observation },
549
+ receipt: {
550
+ schemaVersion: 1,
551
+ operationId: prepared.operationId,
552
+ executionId: entry.executionId,
553
+ guideId: prepared.guideId,
554
+ storeRef: prepared.store.storeRef,
555
+ productRef: prepared.productRef,
556
+ variantRef: prepared.variantRef,
557
+ cartDigest: entry.cartDigest,
558
+ lineDigest: observation.lineKeyDigest,
559
+ observedQuantity: observation.quantity,
560
+ currency: observation.currency,
561
+ unitPrice: prepared.unitPrice.amount,
562
+ observedAt: observation.observedAt,
563
+ },
564
+ };
565
+ }
566
+ function rememberRequest(key, original, request) {
567
+ try {
568
+ const entries = readLedger(key);
569
+ const entry = entries.find((candidate) => candidate.operationId === original.operationId);
570
+ if (!entry ||
571
+ entry.executionId !== original.executionId ||
572
+ entry.intentDigest !== original.intentDigest ||
573
+ entry.cartDigest !== original.cartDigest)
574
+ return;
575
+ // Preserve the first actual request fact through every read-only recovery.
576
+ if (entry.request === null || entry.request.outcome === "unknown")
577
+ entry.request = request;
578
+ saveLedger(key, entries);
579
+ }
580
+ catch {
581
+ /* The current caller retains exact evidence; reload recovery is unknown, never a retry. */
582
+ }
583
+ }
584
+ /** Isolated effect executor. No calls occur until execute/reconcile is explicitly invoked. */
585
+ export class ShopifyCartExecutor {
586
+ constructor(authority) {
587
+ this.authority = authority;
588
+ }
589
+ /** Synchronous gate used before even requesting another quote/grant. Fail closed on lost storage. */
590
+ hasPending(scope) {
591
+ try {
592
+ return (!validLedgerScope(scope) ||
593
+ readLedger(ledgerKey(scope)).some((entry) => pendingEntry(entry, scope.sessionId)));
594
+ }
595
+ catch {
596
+ return true;
597
+ }
598
+ }
599
+ /** Retained browser facts for immediate UI restoration; never network or mutation authority. */
600
+ peekPending(scope) {
601
+ try {
602
+ if (!validLedgerScope(scope))
603
+ return {
604
+ state: "unresolved",
605
+ prepared: null,
606
+ outcome: result("uncertain", "context_changed"),
607
+ };
608
+ const entry = readLedger(ledgerKey(scope)).find((candidate) => pendingEntry(candidate, scope.sessionId));
609
+ if (!entry)
610
+ return null;
611
+ const prepared = entry.prepared;
612
+ if (!prepared ||
613
+ prepared.guideId !== scope.guideId ||
614
+ prepared.store.storeRef !== scope.store.storeRef ||
615
+ prepared.store.origin !== scope.store.origin)
616
+ return {
617
+ state: "unresolved",
618
+ prepared: null,
619
+ outcome: result("uncertain", "execution_unverified"),
620
+ };
621
+ return {
622
+ state: "unresolved",
623
+ prepared,
624
+ outcome: entry.resolved && entry.observation
625
+ ? retainedOutcome(prepared, entry)
626
+ : {
627
+ ...result("uncertain", "not_observed"),
628
+ execution: evidence(entry),
629
+ },
630
+ };
631
+ }
632
+ catch {
633
+ return {
634
+ state: "unresolved",
635
+ prepared: null,
636
+ outcome: result("uncertain", "storage_unavailable"),
637
+ };
638
+ }
639
+ }
640
+ /** Call only after native accepted this exact report. Browser observation alone is not delivery. */
641
+ acknowledgeReport(scope, report) {
642
+ try {
643
+ if (!validLedgerScope(scope) || !object(report))
644
+ return false;
645
+ const key = ledgerKey(scope);
646
+ const entries = readLedger(key);
647
+ const entry = entries.find((candidate) => candidate.operationId === report.operationId);
648
+ if (!entry?.prepared?.reportScope ||
649
+ !entry.resolved ||
650
+ !entry.observation ||
651
+ !entry.request ||
652
+ entry.prepared.guideId !== scope.guideId ||
653
+ entry.prepared.store.origin !== scope.store.origin ||
654
+ entry.prepared.store.storeRef !== scope.store.storeRef ||
655
+ (!!entry.prepared.reportSessionId &&
656
+ entry.prepared.reportSessionId !== scope.sessionId) ||
657
+ entry.executionId !== report.executionId ||
658
+ entry.cartDigest !== report.cartDigest ||
659
+ !validSavedObservation(report.observation, entry.prepared) ||
660
+ !validRequestOutcome(report.request))
661
+ return false;
662
+ const originalScope = entry.prepared.reportScope;
663
+ const receivedScope = {
664
+ schemaVersion: report.schemaVersion,
665
+ requestId: report.requestId,
666
+ operationId: report.operationId,
667
+ proposalChecksum: report.proposalChecksum,
668
+ contextDigest: report.contextDigest,
669
+ contextRevision: report.contextRevision,
670
+ pageId: report.pageId,
671
+ provider: report.provider,
672
+ };
673
+ if (!validReportScope(receivedScope, entry.operationId) ||
674
+ reportScopeIdentity(receivedScope) !==
675
+ reportScopeIdentity(originalScope) ||
676
+ report.request.outcome !== entry.request.outcome ||
677
+ (report.request.outcome === "response" &&
678
+ (entry.request.outcome !== "response" ||
679
+ report.request.httpStatus !== entry.request.httpStatus)) ||
680
+ Object.keys(entry.observation).some((key) => entry.observation[key] !==
681
+ report.observation[key]))
682
+ return false;
683
+ entry.reportAccepted = true;
684
+ saveLedger(key, entries);
685
+ return true;
686
+ }
687
+ catch {
688
+ return false;
689
+ }
690
+ }
691
+ /** Restores only public intent and original evidence. Never consumes a grant or performs a POST. */
692
+ async reconcilePending(scope) {
693
+ const failure = (reason, prepared = null) => ({
694
+ state: "unresolved",
695
+ prepared,
696
+ outcome: result("uncertain", reason),
697
+ });
698
+ try {
699
+ if (!validLedgerScope(scope) || !isCommerceMarket(scope.market))
700
+ return failure("context_changed");
701
+ const key = ledgerKey(scope);
702
+ const original = readLedger(key).find((entry) => pendingEntry(entry, scope.sessionId));
703
+ if (!original)
704
+ return { state: "none", prepared: null, outcome: null };
705
+ const prepared = original.prepared;
706
+ if (!prepared ||
707
+ prepared.guideId !== scope.guideId ||
708
+ prepared.store.storeRef !== scope.store.storeRef ||
709
+ prepared.store.origin !== scope.store.origin ||
710
+ (await sha(intent(prepared))) !== original.intentDigest)
711
+ return failure("execution_unverified");
712
+ if (!sameCommerceMarket(prepared.market, scope.market) ||
713
+ !route(prepared) ||
714
+ !(await this.current(prepared)))
715
+ return failure("context_changed", prepared);
716
+ const outcome = original.resolved && original.observation
717
+ ? retainedOutcome(prepared, original)
718
+ : await this.observe(prepared, evidence(original));
719
+ return {
720
+ state: this.hasPending(scope) ? "unresolved" : "resolved",
721
+ prepared,
722
+ outcome,
723
+ };
724
+ }
725
+ catch {
726
+ return failure("storage_unavailable");
727
+ }
728
+ }
729
+ async execute(input, executionId) {
730
+ let prepared;
731
+ let digest;
732
+ try {
733
+ const text = JSON.stringify(input);
734
+ if (text.length > PREPARED_BYTES || !commerceUuid(executionId))
735
+ return result("unavailable", "invalid_request");
736
+ prepared = JSON.parse(text);
737
+ if (!validPrepared(prepared))
738
+ return result("unavailable", "invalid_request");
739
+ digest = await sha(intent(prepared));
740
+ }
741
+ catch {
742
+ return result("unavailable", "invalid_request");
743
+ }
744
+ const paths = route(prepared, false);
745
+ if (!paths)
746
+ return result("unavailable", "context_changed");
747
+ const key = ledgerKey(prepared);
748
+ let entries;
749
+ try {
750
+ entries = readLedger(key);
751
+ }
752
+ catch {
753
+ return result("unavailable", "storage_unavailable");
754
+ }
755
+ const existing = entries.find((entry) => entry.operationId === prepared.operationId);
756
+ if (existing)
757
+ return existing.intentDigest === digest
758
+ ? existing.resolved && existing.prepared?.reportScope
759
+ ? retainedOutcome(prepared, existing)
760
+ : this.observe(prepared, evidence(existing))
761
+ : result("conflict", "invalid_request");
762
+ if (entries.some((entry) => pendingEntry(entry, prepared.reportSessionId))) {
763
+ const recovery = await this.reconcilePending({
764
+ ...prepared,
765
+ ...(prepared.reportSessionId
766
+ ? { sessionId: prepared.reportSessionId }
767
+ : {}),
768
+ });
769
+ return result("uncertain", recovery.state === "resolved"
770
+ ? "previous_operation_reconciled"
771
+ : "previous_operation_unresolved");
772
+ }
773
+ if (!route(prepared) || !(await this.current(prepared)))
774
+ return result("unavailable", "context_changed");
775
+ if (Date.parse(prepared.expiresAt) <= Date.now() ||
776
+ Date.parse(prepared.expiresAt) > Date.now() + 300000)
777
+ return result("unavailable", "expired");
778
+ const price = ajaxPrice(prepared.unitPrice.amount, prepared.unitPrice.currency);
779
+ if (price === null)
780
+ return result("unavailable", "unsupported_currency");
781
+ if (BigInt(price) * BigInt(prepared.quantity) >
782
+ BigInt(Number.MAX_SAFE_INTEGER))
783
+ return result("unavailable", "invalid_request");
784
+ let cartDigest;
785
+ let operationAlreadyVisible = false;
786
+ try {
787
+ const cart = await readCart(paths.root);
788
+ if (cart.currency !== prepared.market.currency)
789
+ return result("conflict", "cart_changed");
790
+ cartDigest = await sha(cart.token);
791
+ operationAlreadyVisible = cart.items.some((line) => object(line.properties) &&
792
+ line.properties[PROPERTY] === prepared.operationMarker);
793
+ // An existing marker is reconciliation-only. Native must identify the original admission.
794
+ if (!operationAlreadyVisible) {
795
+ const product = await request(paths.product);
796
+ if (product.status !== 200 ||
797
+ !preflightProduct(product.value, prepared, price))
798
+ return result("unavailable", "product_changed");
799
+ }
800
+ }
801
+ catch {
802
+ return result("unavailable", "transport");
803
+ }
804
+ if (!(await this.current(prepared)) ||
805
+ route(prepared)?.root !== paths.root ||
806
+ Date.parse(prepared.expiresAt) <= Date.now())
807
+ return result("unavailable", "context_changed");
808
+ let claim;
809
+ try {
810
+ claim = await this.authority.beginExecution({ executionId, cartDigest });
811
+ }
812
+ catch {
813
+ return result("uncertain", "grant_unavailable");
814
+ }
815
+ if (!validReady(claim))
816
+ return result("uncertain", "grant_unavailable");
817
+ if (claim.state === "already_started") {
818
+ // Only the server's original identity can recover a missing browser ledger.
819
+ return this.reconcile(prepared, executionId, claim);
820
+ }
821
+ if (claim.executionId !== executionId || claim.cartDigest !== cartDigest)
822
+ return result("uncertain", "grant_unavailable");
823
+ const original = {
824
+ operationId: prepared.operationId,
825
+ executionId,
826
+ intentDigest: digest,
827
+ cartDigest,
828
+ expiresAt: Date.parse(prepared.expiresAt),
829
+ request: null,
830
+ prepared: publicPrepared(prepared),
831
+ observation: null,
832
+ resolved: false,
833
+ reportAccepted: false,
834
+ };
835
+ const abort = (status, reason) => ({
836
+ ...result(status, reason),
837
+ execution: evidence({ ...original, request: { outcome: "aborted" } }),
838
+ });
839
+ if (!(await this.current(prepared)) || route(prepared)?.root !== paths.root)
840
+ return abort("uncertain", "context_changed");
841
+ if (Date.parse(claim.expiresAt) <= Date.now() ||
842
+ Date.parse(prepared.expiresAt) <= Date.now())
843
+ return abort("uncertain", "expired");
844
+ try {
845
+ // Product/native reads take time. Refuse a known cart switch; Ajax still has a cookie TOCTOU.
846
+ const finalCart = await readCart(paths.root);
847
+ if (finalCart.currency !== prepared.market.currency ||
848
+ (await sha(finalCart.token)) !== cartDigest)
849
+ return abort("conflict", "cart_changed");
850
+ operationAlreadyVisible || (operationAlreadyVisible = finalCart.items.some((line) => object(line.properties) &&
851
+ line.properties[PROPERTY] === prepared.operationMarker));
852
+ }
853
+ catch {
854
+ return abort("uncertain", "transport");
855
+ }
856
+ if (!(await this.current(prepared)) || route(prepared)?.root !== paths.root)
857
+ return abort("uncertain", "context_changed");
858
+ if (Date.parse(claim.expiresAt) <= Date.now() ||
859
+ Date.parse(prepared.expiresAt) <= Date.now())
860
+ return abort("uncertain", "expired");
861
+ // Re-read AFTER every await. Native provides cross-tab first-consume; localStorage is not CAS.
862
+ // No await separates persistence and the single POST.
863
+ try {
864
+ entries = readLedger(key);
865
+ const started = entries.find((entry) => entry.operationId === prepared.operationId);
866
+ if (started)
867
+ return started.intentDigest === digest
868
+ ? started.resolved && started.prepared?.reportScope
869
+ ? retainedOutcome(prepared, started)
870
+ : this.observe(prepared, evidence(started))
871
+ : abort("conflict", "invalid_request");
872
+ if (entries.some((entry) => pendingEntry(entry, prepared.reportSessionId)))
873
+ return abort("uncertain", "previous_operation_unresolved");
874
+ if (operationAlreadyVisible)
875
+ return abort("uncertain", "execution_unverified");
876
+ saveStarted(key, entries, original);
877
+ }
878
+ catch {
879
+ return abort("unavailable", "storage_unavailable");
880
+ }
881
+ let requestOutcome = null;
882
+ try {
883
+ await request(`${paths.root}cart/add.js`, JSON.stringify({
884
+ items: [
885
+ {
886
+ id: prepared.shopifyVariantId,
887
+ quantity: prepared.quantity,
888
+ properties: { [PROPERTY]: prepared.operationMarker },
889
+ },
890
+ ],
891
+ }), (httpStatus) => {
892
+ requestOutcome = { outcome: "response", httpStatus };
893
+ rememberRequest(key, original, requestOutcome);
894
+ });
895
+ }
896
+ catch (error) {
897
+ // A received HTTP status remains true even if JSON/body streaming later fails.
898
+ requestOutcome ?? (requestOutcome = {
899
+ outcome: error instanceof AjaxTransportError ? error.outcome : "network_error",
900
+ });
901
+ }
902
+ requestOutcome ?? (requestOutcome = { outcome: "network_error" });
903
+ rememberRequest(key, original, requestOutcome);
904
+ return this.observe(prepared, evidence({ ...original, request: requestOutcome }));
905
+ }
906
+ /** Read-only even after expiry/cut. recoveredReady must come from the trusted native ACK/ready path. */
907
+ async reconcile(input, executionId, recoveredReady) {
908
+ let prepared;
909
+ try {
910
+ const text = JSON.stringify(input);
911
+ if (text.length > PREPARED_BYTES)
912
+ return result("unavailable", "invalid_request");
913
+ prepared = JSON.parse(text);
914
+ if (!commerceUuid(executionId) || !validPrepared(prepared))
915
+ return result("unavailable", "invalid_request");
916
+ if (recoveredReady &&
917
+ (!validReady(recoveredReady) ||
918
+ recoveredReady.state !== "already_started"))
919
+ return result("uncertain", "grant_unavailable");
920
+ const digest = await sha(intent(prepared));
921
+ let started;
922
+ try {
923
+ started = readLedger(ledgerKey(prepared)).find((entry) => entry.operationId === prepared.operationId);
924
+ }
925
+ catch {
926
+ if (!recoveredReady)
927
+ return result("uncertain", "storage_unavailable");
928
+ }
929
+ if (started &&
930
+ (started.intentDigest !== digest ||
931
+ (recoveredReady &&
932
+ (recoveredReady.executionId !== started.executionId ||
933
+ recoveredReady.cartDigest !== started.cartDigest))))
934
+ return result("conflict", "invalid_request");
935
+ if (!started && recoveredReady) {
936
+ started = {
937
+ operationId: prepared.operationId,
938
+ executionId: recoveredReady.executionId,
939
+ cartDigest: recoveredReady.cartDigest,
940
+ intentDigest: digest,
941
+ expiresAt: Date.parse(prepared.expiresAt),
942
+ request: { outcome: "unknown" },
943
+ prepared: publicPrepared(prepared),
944
+ observation: null,
945
+ resolved: false,
946
+ reportAccepted: false,
947
+ };
948
+ try {
949
+ saveStarted(ledgerKey(prepared), readLedger(ledgerKey(prepared)), started);
950
+ }
951
+ catch {
952
+ /* Read-only recovery remains valid; unavailable storage still disables new effects. */
953
+ }
954
+ }
955
+ if (started?.resolved && started.prepared?.reportScope)
956
+ return retainedOutcome(prepared, started);
957
+ const execution = started
958
+ ? evidence(started)
959
+ : recoveredReady
960
+ ? evidence({
961
+ executionId: recoveredReady.executionId,
962
+ cartDigest: recoveredReady.cartDigest,
963
+ request: null,
964
+ })
965
+ : null;
966
+ return this.observe(prepared, execution);
967
+ }
968
+ catch {
969
+ return result("uncertain", "invalid_request");
970
+ }
971
+ }
972
+ /** Ajax change.js sets an absolute quantity and offers no conditional delta/CAS.
973
+ * A read then change can overwrite the shopper's concurrent edit even by line key.
974
+ * https://shopify.dev/docs/api/ajax/reference/cart#post-locale-cart-change-js
975
+ */
976
+ undo() {
977
+ return {
978
+ status: "unsupported_conflict",
979
+ canUndo: false,
980
+ reason: "ajax_has_no_conditional_delta",
981
+ };
982
+ }
983
+ async current(prepared) {
984
+ try {
985
+ return (await this.authority.assertCurrent(prepared)) === true;
986
+ }
987
+ catch {
988
+ return false;
989
+ }
990
+ }
991
+ async observe(prepared, execution) {
992
+ const paths = route(prepared, false);
993
+ if (!paths)
994
+ return { ...result("uncertain", "context_changed"), execution };
995
+ try {
996
+ const cart = await readCart(paths.root);
997
+ const cartDigest = await sha(cart.token);
998
+ const lines = cart.items.filter((line) => object(line.properties) &&
999
+ line.properties[PROPERTY] === prepared.operationMarker);
1000
+ const line = lines.length === 1 ? lines[0] : undefined;
1001
+ const observedPrice = line && count(line.final_price) ? line.final_price : null;
1002
+ const receipt = {
1003
+ schemaVersion: 1,
1004
+ operationId: prepared.operationId,
1005
+ executionId: execution?.executionId ?? "",
1006
+ guideId: prepared.guideId,
1007
+ storeRef: prepared.store.storeRef,
1008
+ productRef: prepared.productRef,
1009
+ variantRef: prepared.variantRef,
1010
+ cartDigest,
1011
+ lineDigest: line &&
1012
+ typeof line.key === "string" &&
1013
+ line.key.length > 0 &&
1014
+ line.key.length <= 512
1015
+ ? await sha(line.key)
1016
+ : null,
1017
+ observedQuantity: lines.reduce((sum, entry) => sum + Number(entry.quantity), 0),
1018
+ currency: cart.currency,
1019
+ unitPrice: observedPrice === null ? null : decimal(observedPrice),
1020
+ observedAt: new Date().toISOString(),
1021
+ };
1022
+ let status = "uncertain";
1023
+ let reason = "not_observed";
1024
+ const expected = ajaxPrice(prepared.unitPrice.amount, prepared.unitPrice.currency);
1025
+ if ((execution && execution.cartDigest !== cartDigest) ||
1026
+ cart.currency !== prepared.market.currency) {
1027
+ status = "conflict";
1028
+ reason = "cart_changed";
1029
+ }
1030
+ else if (lines.length) {
1031
+ const matches = expected !== null &&
1032
+ line &&
1033
+ id(line.variant_id) === prepared.shopifyVariantId &&
1034
+ `gid://shopify/Product/${id(line.product_id)}` ===
1035
+ prepared.productRef &&
1036
+ sameOptions(line.options_with_values, prepared.selectedOptions) &&
1037
+ sameRule(line.quantity_rule, prepared.quantityRule) &&
1038
+ line.selling_plan_allocation == null &&
1039
+ line.parent_relationship == null &&
1040
+ (line.has_components === undefined ||
1041
+ line.has_components === false) &&
1042
+ (line.item_components == null ||
1043
+ (Array.isArray(line.item_components) &&
1044
+ line.item_components.length === 0)) &&
1045
+ line.price === expected &&
1046
+ line.final_price === expected &&
1047
+ line.final_line_price === Number(line.quantity) * Number(expected) &&
1048
+ receipt.lineDigest !== null;
1049
+ if (!matches) {
1050
+ status = "conflict";
1051
+ reason = "line_changed";
1052
+ }
1053
+ else if (line.quantity === prepared.quantity) {
1054
+ status = "confirmed";
1055
+ reason = "matched";
1056
+ }
1057
+ else if (Number(line.quantity) < prepared.quantity) {
1058
+ status = "partial";
1059
+ reason = "partial_quantity";
1060
+ }
1061
+ else {
1062
+ status = "conflict";
1063
+ reason = "line_changed";
1064
+ }
1065
+ }
1066
+ // Missing retained state cannot be replaced by today's token or a caller's
1067
+ // new execution ID. Native recovery must provide the original bound values.
1068
+ // Wire observations are facts about the original cart, never inferred from a mismatched line.
1069
+ const observation = execution &&
1070
+ (status === "confirmed" ||
1071
+ status === "partial" ||
1072
+ (reason === "not_observed" && lines.length === 0))
1073
+ ? {
1074
+ source: "browser_cart",
1075
+ observedAt: receipt.observedAt,
1076
+ currency: cart.currency,
1077
+ shopifyVariantId: prepared.shopifyVariantId,
1078
+ operationMarker: prepared.operationMarker,
1079
+ quantity: receipt.observedQuantity,
1080
+ lineKeyDigest: receipt.lineDigest,
1081
+ }
1082
+ : null;
1083
+ if (execution && observation && observation.quantity > 0) {
1084
+ try {
1085
+ const key = ledgerKey(prepared);
1086
+ const digest = await sha(intent(prepared));
1087
+ const entries = readLedger(key);
1088
+ const entry = entries.find((candidate) => sameStarted(candidate, {
1089
+ operationId: prepared.operationId,
1090
+ executionId: execution.executionId,
1091
+ cartDigest: execution.cartDigest,
1092
+ intentDigest: digest,
1093
+ }));
1094
+ if (entry && !entry.resolved) {
1095
+ entry.prepared ?? (entry.prepared = publicPrepared(prepared));
1096
+ entry.request ?? (entry.request = execution.request);
1097
+ entry.observation = observation;
1098
+ entry.resolved = true;
1099
+ saveLedger(key, entries);
1100
+ }
1101
+ }
1102
+ catch {
1103
+ /* A failed persistence keeps hasPending closed; no retry of the effect. */
1104
+ }
1105
+ }
1106
+ if (!execution) {
1107
+ status = "uncertain";
1108
+ reason = "execution_unverified";
1109
+ }
1110
+ // A context cut revokes future authority, not an already observed original effect.
1111
+ // Only the strict positive observation above can preserve confirmed/partial truth.
1112
+ if ((!(await this.current(prepared)) || !route(prepared)) &&
1113
+ (!observation || observation.quantity === 0)) {
1114
+ status = "uncertain";
1115
+ reason = "context_changed";
1116
+ }
1117
+ return {
1118
+ status,
1119
+ reason,
1120
+ canUndo: false,
1121
+ receipt: execution ? receipt : null,
1122
+ execution: execution ? { ...execution, observation } : null,
1123
+ local: { itemCount: cart.itemCount },
1124
+ };
1125
+ }
1126
+ catch {
1127
+ return { ...result("uncertain", "transport"), execution };
1128
+ }
1129
+ }
1130
+ }