@oxvo/ai-live-assist 7.5.20 → 7.5.22

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 (101) 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 +345 -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/context.js +17 -5
  26. package/cjs/control.d.ts +9 -1
  27. package/cjs/control.js +51 -1
  28. package/cjs/guideAdmission.d.ts +6 -2
  29. package/cjs/guideAdmission.js +39 -2
  30. package/cjs/guideInstaller.js +1 -1
  31. package/cjs/guideMeasurement.d.ts +7 -0
  32. package/cjs/guideMeasurement.js +59 -0
  33. package/cjs/guideSubjectStore.js +2 -0
  34. package/cjs/guideTypes.d.ts +19 -0
  35. package/cjs/liveControlChannel.d.ts +43 -1
  36. package/cjs/liveControlChannel.js +166 -14
  37. package/cjs/liveGuideAdmission.d.ts +3 -2
  38. package/cjs/liveGuideAdmission.js +14 -2
  39. package/cjs/liveGuideWidget.d.ts +18 -0
  40. package/cjs/liveGuideWidget.js +228 -23
  41. package/cjs/locales/resources.js +2240 -0
  42. package/cjs/messages.js +56 -0
  43. package/cjs/tabLock.d.ts +2 -0
  44. package/cjs/tabLock.js +11 -1
  45. package/cjs/types.d.ts +6 -2
  46. package/cjs/types.js +56 -0
  47. package/cjs/ui.d.ts +37 -0
  48. package/cjs/ui.js +259 -9
  49. package/cjs/version.d.ts +1 -1
  50. package/cjs/version.js +1 -1
  51. package/lib/AiLiveAssist.d.ts +8 -1
  52. package/lib/AiLiveAssist.js +113 -8
  53. package/lib/client.d.ts +5 -3
  54. package/lib/client.js +44 -5
  55. package/lib/commerce/cartContracts.d.ts +158 -0
  56. package/lib/commerce/cartContracts.js +221 -0
  57. package/lib/commerce/cartSession.d.ts +86 -0
  58. package/lib/commerce/cartSession.js +471 -0
  59. package/lib/commerce/contracts.d.ts +152 -0
  60. package/lib/commerce/contracts.js +300 -0
  61. package/lib/commerce/pageContext.d.ts +50 -0
  62. package/lib/commerce/pageContext.js +168 -0
  63. package/lib/commerce/productPanel.d.ts +65 -0
  64. package/lib/commerce/productPanel.js +657 -0
  65. package/lib/commerce/realtimeCommerce.d.ts +73 -0
  66. package/lib/commerce/realtimeCommerce.js +340 -0
  67. package/lib/commerce/shopifyCart.d.ts +130 -0
  68. package/lib/commerce/shopifyCart.js +1130 -0
  69. package/lib/commerce/shopifyCartPresentation.d.ts +12 -0
  70. package/lib/commerce/shopifyCartPresentation.js +376 -0
  71. package/lib/commerce/shoppingNotes.d.ts +61 -0
  72. package/lib/commerce/shoppingNotes.js +307 -0
  73. package/lib/commerce/shoppingNotesView.d.ts +46 -0
  74. package/lib/commerce/shoppingNotesView.js +265 -0
  75. package/lib/context.js +17 -5
  76. package/lib/control.d.ts +9 -1
  77. package/lib/control.js +51 -1
  78. package/lib/guideAdmission.d.ts +6 -2
  79. package/lib/guideAdmission.js +39 -2
  80. package/lib/guideInstaller.js +1 -1
  81. package/lib/guideMeasurement.d.ts +7 -0
  82. package/lib/guideMeasurement.js +53 -0
  83. package/lib/guideSubjectStore.js +2 -0
  84. package/lib/guideTypes.d.ts +19 -0
  85. package/lib/liveControlChannel.d.ts +43 -1
  86. package/lib/liveControlChannel.js +166 -14
  87. package/lib/liveGuideAdmission.d.ts +3 -2
  88. package/lib/liveGuideAdmission.js +14 -2
  89. package/lib/liveGuideWidget.d.ts +18 -0
  90. package/lib/liveGuideWidget.js +228 -23
  91. package/lib/locales/resources.js +2240 -0
  92. package/lib/messages.js +56 -0
  93. package/lib/tabLock.d.ts +2 -0
  94. package/lib/tabLock.js +11 -1
  95. package/lib/types.d.ts +6 -2
  96. package/lib/types.js +56 -0
  97. package/lib/ui.d.ts +37 -0
  98. package/lib/ui.js +259 -9
  99. package/lib/version.d.ts +1 -1
  100. package/lib/version.js +1 -1
  101. package/package.json +1 -1
@@ -0,0 +1,475 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CartSession = void 0;
4
+ const cartContracts_js_1 = require("./cartContracts.js");
5
+ const shopifyCart_js_1 = require("./shopifyCart.js");
6
+ const shopifyCartPresentation_js_1 = require("./shopifyCartPresentation.js");
7
+ const copy = (value) => JSON.parse(JSON.stringify(value));
8
+ const stable = (value) => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item)
9
+ ? Object.fromEntries(Object.entries(item).sort(([left], [right]) => left.localeCompare(right))) : item);
10
+ const decimal = (amount) => {
11
+ const [whole, fraction = ''] = amount.split('.');
12
+ const trimmed = fraction.replace(/0+$/u, '');
13
+ return trimmed ? `${whole}.${trimmed}` : whole;
14
+ };
15
+ const semanticQuote = (value) => ({
16
+ store: value.store, market: value.market, item: { ...value.item,
17
+ unitPrice: { ...value.item.unitPrice, amount: decimal(value.item.unitPrice.amount) },
18
+ selectedOptions: [...value.item.selectedOptions].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0),
19
+ },
20
+ });
21
+ const scopeOf = (value) => ({
22
+ schemaVersion: 1, requestId: value.requestId, operationId: value.operationId,
23
+ proposalChecksum: value.proposalChecksum, contextDigest: value.contextDigest,
24
+ contextRevision: value.contextRevision, pageId: value.pageId, provider: copy(value.provider),
25
+ });
26
+ const failure = (reason, uncertain = false) => ({
27
+ status: uncertain ? 'uncertain' : 'unavailable', reason, canUndo: false, receipt: null,
28
+ execution: null, local: { itemCount: null },
29
+ });
30
+ /** One explicit shopper operation at a time. Catalog evidence can request a
31
+ * quote; only a separately approved, current grant can reach the Ajax executor. */
32
+ class CartSession {
33
+ constructor(options) {
34
+ this.options = options;
35
+ this.pending = null;
36
+ this.destroyed = false;
37
+ this.retired = new Set();
38
+ this.retiredRequests = new Set();
39
+ this.recoveryOutcome = null;
40
+ this.recoveryInFlight = null;
41
+ this.canAdd = (productRef, variantRef, quantity) => {
42
+ if (this.destroyed || this.pending || this.recoveryInFlight || !this.options.bootstrap.cartEnabled ||
43
+ !this.options.current() || this.hasUnresolved())
44
+ return false;
45
+ const selection = this.options.selection(productRef, variantRef);
46
+ const variant = selection?.product.variant;
47
+ if (!selection || !variant || selection.selection.productRef !== productRef || selection.selection.variantRef !== variantRef ||
48
+ selection.product.productRef !== productRef || variant.variantRef !== variantRef ||
49
+ Date.parse(selection.expiresAt) <= Date.now() || !variant.available || variant.requiresSellingPlan ||
50
+ !Number.isSafeInteger(quantity) || quantity < 1)
51
+ return false;
52
+ const rule = variant.quantityRule;
53
+ return quantity >= rule.minimum && (rule.maximum === null || quantity <= rule.maximum) && quantity % rule.increment === 0;
54
+ };
55
+ this.add = (productRef, variantRef, quantity) => {
56
+ if (!this.canAdd(productRef, variantRef, quantity))
57
+ return;
58
+ const snapshot = this.options.current();
59
+ const selection = this.options.selection(productRef, variantRef);
60
+ if (!snapshot || !selection)
61
+ return;
62
+ const pending = this.createPending('explicit_add', crypto.randomUUID(), snapshot, selection, quantity);
63
+ this.pending = pending;
64
+ this.options.view()?.clearCommerceCartStatus();
65
+ this.options.view()?.setCommerceBusy(true);
66
+ const request = { ...copy(selection.displayReceipt), requestId: pending.requestId,
67
+ productRef, variantRef, quantity, selectionDigest: selection.selection.selectionDigest };
68
+ delete request.products;
69
+ this.arm(pending, 20000);
70
+ this.send('commerce.cart.request', request).then(accepted => {
71
+ if (!accepted && this.pending === pending && !pending.started)
72
+ this.fail(pending, 'transport');
73
+ });
74
+ };
75
+ this.checkCart = () => {
76
+ if (this.recoveryInFlight)
77
+ return this.recoveryInFlight;
78
+ const current = this.options.current();
79
+ if (this.destroyed || this.pending || !current)
80
+ return Promise.resolve();
81
+ const snapshot = copy(current);
82
+ const stillCurrent = () => !this.destroyed && !this.pending && stable(this.options.current()) === stable(snapshot);
83
+ const work = async () => {
84
+ try {
85
+ const executor = this.recoveryExecutor();
86
+ const recovered = await executor.reconcilePending({ ...this.recoveryScope(snapshot.sessionId), market: snapshot.context.market });
87
+ const outcome = recovered.outcome;
88
+ const prepared = recovered.prepared;
89
+ if (outcome)
90
+ this.recoveryOutcome = outcome;
91
+ // Only an original public scope stored with the original executor
92
+ // record can report recovery. It confers no permission to POST.
93
+ if (prepared && outcome && !this.destroyed && this.options.current()?.sessionId === snapshot.sessionId) {
94
+ if (prepared.reportSessionId === snapshot.sessionId)
95
+ await this.report(prepared, outcome, executor);
96
+ }
97
+ if (prepared && outcome)
98
+ await (0, shopifyCartPresentation_js_1.refreshShopifyCartPresentation)(prepared, outcome, { assertCurrent: stillCurrent }).catch(() => undefined);
99
+ if (this.destroyed)
100
+ return;
101
+ if (this.hasUnresolved())
102
+ this.showRecovery();
103
+ else {
104
+ this.recoveryOutcome = null;
105
+ if (outcome)
106
+ this.options.view()?.setCommerceCartStatus(outcome, this.cartUrl());
107
+ else
108
+ this.options.view()?.clearCommerceCartStatus();
109
+ }
110
+ }
111
+ catch {
112
+ this.showRecovery();
113
+ }
114
+ finally {
115
+ this.recoveryInFlight = null;
116
+ if (!this.destroyed)
117
+ this.refreshControls();
118
+ }
119
+ };
120
+ this.recoveryInFlight = work();
121
+ return this.recoveryInFlight;
122
+ };
123
+ }
124
+ /** A catalog replaces the panel; install again after its visible receipt. */
125
+ refreshControls() {
126
+ if (!this.destroyed && !this.pending && this.options.current() && this.hasUnresolved())
127
+ this.showRecovery();
128
+ this.options.view()?.setCommerceCartActionHandler(this.destroyed || !this.options.bootstrap.cartEnabled ||
129
+ !this.options.current() ? null : this.add, this.canAdd);
130
+ }
131
+ /** execution.ready must be delivered at authenticated ingress, before any
132
+ * queued handler waits for the executor's ACK-plus-ready barrier. */
133
+ onEvent(type, payload) {
134
+ if (type === 'commerce.cart.execution.ready') {
135
+ this.ready(payload);
136
+ return;
137
+ }
138
+ if (this.destroyed)
139
+ return;
140
+ if (type === 'commerce.cart.confirmation')
141
+ this.confirmation(payload);
142
+ else if (type === 'commerce.cart.grant')
143
+ this.grant(payload);
144
+ else if (type === 'commerce.cart.result')
145
+ this.result(payload);
146
+ }
147
+ cut() {
148
+ const pending = this.pending;
149
+ if (!pending)
150
+ return;
151
+ pending.cancelled = true;
152
+ this.options.view()?.clearCommerceCartConfirmation(pending.confirmation?.operationId);
153
+ this.options.view()?.setCommerceBusy(false);
154
+ if (!pending.started) {
155
+ this.decline(pending);
156
+ this.finish(pending);
157
+ }
158
+ // A dispatched begin may already have consumed the grant. Keep its exact
159
+ // ready/ACK wait and allow read-only reconciliation; never start another POST.
160
+ }
161
+ destroy() {
162
+ this.cut();
163
+ this.destroyed = true;
164
+ this.options.view()?.setCommerceCartActionHandler(null);
165
+ }
166
+ createPending(intentKind, requestId, snapshot, selection, quantity) {
167
+ return { intentKind, requestId, snapshot: copy(snapshot), selection: copy(selection), quantity, confirmation: null,
168
+ approved: false, decisionSent: false, grant: null, cancelled: false, started: false, executing: false,
169
+ timer: null, begin: null, localOutcome: null };
170
+ }
171
+ current(pending) {
172
+ const current = this.options.current();
173
+ return !this.destroyed && !pending.cancelled && this.pending === pending && current !== null &&
174
+ stable(current) === stable(pending.snapshot);
175
+ }
176
+ confirmation(payload) {
177
+ const current = this.options.current();
178
+ if (!current || !this.options.bootstrap.cartEnabled)
179
+ return;
180
+ const quote = (0, cartContracts_js_1.parseCommerceCartConfirmation)(payload, this.options.bootstrap, current.context, { provider: current.provider });
181
+ if (!quote || this.retired.has(quote.operationId) || this.retiredRequests.has(quote.requestId))
182
+ return;
183
+ let pending = this.pending;
184
+ if (pending?.executing || pending?.grant)
185
+ return;
186
+ if (!pending) {
187
+ // A model may propose a current, actually displayed item. The visitor
188
+ // must still approve this exact fresh quote in the dedicated dialog.
189
+ const selection = this.options.selection(quote.item.productRef, quote.item.variantRef);
190
+ if (!selection || !this.canAdd(quote.item.productRef, quote.item.variantRef, quote.item.quantity))
191
+ return;
192
+ pending = this.createPending('model_proposal', quote.requestId, current, selection, quote.item.quantity);
193
+ this.pending = pending;
194
+ }
195
+ if (!this.current(pending) || pending.requestId !== quote.requestId || pending.quantity !== quote.item.quantity ||
196
+ pending.selection.selection.productRef !== quote.item.productRef || pending.selection.selection.variantRef !== quote.item.variantRef)
197
+ return;
198
+ if (pending.confirmation)
199
+ return;
200
+ pending.confirmation = copy(quote);
201
+ this.arm(pending, Date.parse(quote.expiresAt) - Date.now());
202
+ this.options.view()?.setCommerceBusy(false);
203
+ const owner = pending;
204
+ if (owner.intentKind === 'explicit_add' && this.quoteMatchesDisplayed(owner, quote)) {
205
+ this.decide(owner, quote, true);
206
+ return;
207
+ }
208
+ this.options.view()?.showCommerceCartConfirmation({ operationId: quote.operationId, proposalChecksum: quote.proposalChecksum,
209
+ title: quote.item.title, selectedOptions: quote.item.selectedOptions, quantity: quote.item.quantity,
210
+ unitPrice: quote.item.unitPrice, market: quote.market, store: quote.store, expiresAt: quote.expiresAt }, approved => this.decide(owner, quote, approved));
211
+ }
212
+ quoteMatchesDisplayed(pending, quote) {
213
+ const product = pending.selection.product;
214
+ const variant = product.variant;
215
+ return variant !== null && quote.item.productRef === pending.selection.selection.productRef &&
216
+ quote.item.variantRef === pending.selection.selection.variantRef && quote.item.quantity === pending.quantity &&
217
+ quote.item.title === product.title && quote.item.productUrl === product.url &&
218
+ quote.item.unitPrice.currency === variant.price.currency && decimal(quote.item.unitPrice.amount) === decimal(variant.price.amount) &&
219
+ stable(quote.item.quantityRule) === stable(variant.quantityRule) &&
220
+ stable(quote.store) === stable(this.options.bootstrap.store) && stable(quote.market) === stable(pending.snapshot.context.market) &&
221
+ quote.item.selectedOptions.length === variant.selectedOptions.length && quote.item.selectedOptions.every(option => variant.selectedOptions.some(selected => selected.name === option.name && selected.value === option.value));
222
+ }
223
+ decide(owner, quote, approved) {
224
+ if (this.pending !== owner || owner.decisionSent)
225
+ return;
226
+ owner.approved = approved && this.current(owner) && Date.parse(quote.expiresAt) > Date.now();
227
+ owner.decisionSent = true;
228
+ this.options.view()?.setCommerceBusy(owner.approved);
229
+ void this.send('commerce.cart.confirmation.result', { schemaVersion: 1, operationId: quote.operationId,
230
+ proposalChecksum: quote.proposalChecksum, approved: owner.approved }).then(accepted => {
231
+ if (!accepted && this.pending === owner && !owner.started)
232
+ this.fail(owner, 'transport');
233
+ });
234
+ if (!owner.approved)
235
+ this.finish(owner);
236
+ }
237
+ grant(payload) {
238
+ const pending = this.pending;
239
+ if (!pending || pending.executing || !this.current(pending))
240
+ return;
241
+ const expected = pending.confirmation ? scopeOf(pending.confirmation) :
242
+ { requestId: pending.requestId, provider: pending.snapshot.provider };
243
+ const grant = (0, cartContracts_js_1.parseCommerceCartGrant)(payload, this.options.bootstrap, pending.snapshot.context, expected);
244
+ if (!grant || this.retired.has(grant.operationId))
245
+ return;
246
+ if (pending.confirmation) {
247
+ if (!pending.approved || !pending.decisionSent || stable(semanticQuote(grant)) !== stable(semanticQuote(pending.confirmation)) ||
248
+ Date.parse(grant.expiresAt) > Date.parse(pending.confirmation.expiresAt))
249
+ return;
250
+ }
251
+ else {
252
+ // Native can grant an unchanged explicit Add directly. The shopper's
253
+ // click authorizes that exact displayed intent, never an unsolicited or
254
+ // materially changed item. This does not fabricate a confirmation ACK.
255
+ if (pending.intentKind !== 'explicit_add' || !this.quoteMatchesDisplayed(pending, grant))
256
+ return;
257
+ pending.approved = true;
258
+ }
259
+ pending.grant = copy(grant);
260
+ pending.executing = true;
261
+ if (pending.timer)
262
+ clearTimeout(pending.timer);
263
+ pending.timer = null;
264
+ void this.execute(pending).catch(() => this.fail(pending, 'transport', pending.started));
265
+ }
266
+ async execute(pending) {
267
+ const grant = pending.grant;
268
+ const prepared = { operationId: grant.operationId, operationMarker: grant.operationMarker,
269
+ guideId: this.options.bootstrap.guideId, store: grant.store, market: grant.market,
270
+ productRef: grant.item.productRef, variantRef: grant.item.variantRef, shopifyVariantId: grant.item.shopifyVariantId,
271
+ selectedOptions: grant.item.selectedOptions, quantity: grant.item.quantity, unitPrice: grant.item.unitPrice,
272
+ quantityRule: grant.item.quantityRule, productUrl: grant.item.productUrl, expiresAt: grant.expiresAt,
273
+ requiresSellingPlan: false, requiresComponents: false, reportScope: scopeOf(grant), reportSessionId: pending.snapshot.sessionId };
274
+ const executor = new shopifyCart_js_1.ShopifyCartExecutor({ assertCurrent: () => this.current(pending) && Date.parse(grant.expiresAt) > Date.now(),
275
+ beginExecution: input => this.begin(pending, input.executionId, input.cartDigest) });
276
+ const outcome = await executor.execute(prepared, crypto.randomUUID());
277
+ pending.localOutcome = outcome;
278
+ if (this.pending !== pending)
279
+ return;
280
+ this.options.view()?.setCommerceBusy(false);
281
+ const previous = outcome.reason === 'previous_operation_unresolved' || outcome.reason === 'previous_operation_reconciled';
282
+ if (this.hasUnresolved()) {
283
+ this.recoveryOutcome = outcome;
284
+ if (!this.destroyed)
285
+ this.showRecovery();
286
+ }
287
+ else if (!this.destroyed)
288
+ this.options.view()?.setCommerceCartStatus(outcome, this.cartUrl());
289
+ if (!previous && outcome.execution) {
290
+ await this.report(prepared, outcome, executor);
291
+ if (!this.destroyed && this.pending === pending) {
292
+ if (this.hasUnresolved())
293
+ this.showRecovery();
294
+ else
295
+ this.options.view()?.setCommerceCartStatus(outcome, this.cartUrl());
296
+ }
297
+ }
298
+ // Theme presentation is a bounded read/DOM refresh. It cannot alter the
299
+ // actual cart outcome, and it never opens the drawer or retries a write.
300
+ if (!previous)
301
+ await (0, shopifyCartPresentation_js_1.refreshShopifyCartPresentation)(prepared, outcome, { assertCurrent: () => this.current(pending) }).catch(() => undefined);
302
+ this.finish(pending);
303
+ }
304
+ recoveryExecutor() {
305
+ return new shopifyCart_js_1.ShopifyCartExecutor({ assertCurrent: () => !this.destroyed && this.options.current() !== null,
306
+ beginExecution: async () => { throw new Error('Cart recovery cannot admit a new write.'); } });
307
+ }
308
+ hasUnresolved() {
309
+ try {
310
+ return this.recoveryExecutor().hasPending(this.recoveryScope());
311
+ }
312
+ catch {
313
+ return true;
314
+ }
315
+ }
316
+ recoveryScope(sessionId = this.options.current()?.sessionId) {
317
+ return { guideId: this.options.bootstrap.guideId, store: this.options.bootstrap.store,
318
+ ...(sessionId ? { sessionId } : {}) };
319
+ }
320
+ async report(prepared, outcome, executor) {
321
+ if (!prepared.reportScope || !prepared.reportSessionId || !outcome.execution ||
322
+ prepared.reportScope.operationId !== prepared.operationId || prepared.guideId !== this.options.bootstrap.guideId ||
323
+ stable(prepared.store) !== stable(this.options.bootstrap.store))
324
+ return;
325
+ const transportSessionId = this.options.transportSessionId ? this.options.transportSessionId() :
326
+ this.options.current()?.sessionId ?? prepared.reportSessionId;
327
+ if (transportSessionId !== prepared.reportSessionId)
328
+ return;
329
+ const report = { ...scopeOf(prepared.reportScope), ...outcome.execution };
330
+ if (await this.send('commerce.cart.execution.result', report)) {
331
+ executor.acknowledgeReport(this.recoveryScope(prepared.reportSessionId), report);
332
+ }
333
+ }
334
+ showRecovery() {
335
+ if (this.destroyed)
336
+ return;
337
+ const retained = this.recoveryExecutor().peekPending(this.recoveryScope());
338
+ if (retained?.outcome) {
339
+ const local = this.recoveryOutcome;
340
+ // The public ledger retains evidence, not a live cart count. Keep a
341
+ // count observed in this instance only for that exact same evidence.
342
+ this.recoveryOutcome = local?.execution && stable(local.execution) === stable(retained.outcome.execution)
343
+ ? { ...retained.outcome, local: local.local } : retained.outcome;
344
+ }
345
+ const outcome = this.recoveryOutcome ?? failure('transport', true);
346
+ // An unresolved conflict/zero observation still needs a read-only check;
347
+ // retain its receipt and evidence rather than claiming that no effect ran.
348
+ const observed = outcome.receipt && (outcome.status === 'confirmed' || outcome.status === 'partial');
349
+ this.options.view()?.setCommerceCartStatus(observed ? outcome : { ...outcome, status: 'uncertain' }, this.cartUrl(), this.checkCart);
350
+ }
351
+ async begin(pending, executionId, cartDigest) {
352
+ if (!pending.grant || !this.current(pending))
353
+ throw new Error('The cart approval is no longer current.');
354
+ let resolve;
355
+ const ready = new Promise(done => { resolve = done; });
356
+ pending.begin = { messageId: null, executionId, cartDigest, ready: null, resolve };
357
+ pending.started = true;
358
+ let delivery;
359
+ try {
360
+ delivery = this.options.send('commerce.cart.execution.begin', { schemaVersion: 1,
361
+ operationId: pending.grant.operationId, grant: pending.grant.grant, executionId, cartDigest });
362
+ pending.begin.messageId = delivery.messageId;
363
+ }
364
+ catch {
365
+ pending.begin.resolve(null);
366
+ throw new Error('The cart admission could not be sent.');
367
+ }
368
+ // Admission can race expiry. A fresh already_started reply has its own
369
+ // short recovery window and can only lead to read-only reconciliation.
370
+ const timeout = setTimeout(() => resolve(null), 10000);
371
+ try {
372
+ const [accepted, observed] = await Promise.all([this.boundedAccepted(delivery.accepted, 10000), ready]);
373
+ if (!accepted || !observed)
374
+ throw new Error('The cart admission was not confirmed.');
375
+ return observed;
376
+ }
377
+ finally {
378
+ clearTimeout(timeout);
379
+ }
380
+ }
381
+ ready(payload) {
382
+ const pending = this.pending;
383
+ const begin = pending?.begin;
384
+ if (!pending?.grant || !begin?.messageId || begin.ready)
385
+ return;
386
+ const ready = (0, cartContracts_js_1.parseCommerceCartExecutionReady)(payload, { operationId: pending.grant.operationId, requestMessageId: begin.messageId });
387
+ if (!ready || (ready.state === 'prepared' && (Date.parse(ready.expiresAt) > Date.parse(pending.grant.expiresAt) ||
388
+ ready.executionId !== begin.executionId || ready.cartDigest !== begin.cartDigest)))
389
+ return;
390
+ begin.ready = copy(ready);
391
+ begin.resolve(ready);
392
+ }
393
+ result(payload) {
394
+ const pending = this.pending;
395
+ if (!pending)
396
+ return;
397
+ const result = (0, cartContracts_js_1.parseCommerceCartResult)(payload, { requestId: pending.requestId,
398
+ operationId: pending.confirmation?.operationId ?? pending.grant?.operationId ?? null, executionId: pending.begin?.ready?.executionId ?? null });
399
+ if (!result)
400
+ return;
401
+ // A server "observed" response describes browser evidence. It cannot
402
+ // manufacture local success or replace a stricter local conflict outcome.
403
+ if (pending.executing)
404
+ return;
405
+ if (!pending.localOutcome)
406
+ this.fail(pending, result.status === 'expired' ? 'expired' : 'grant_unavailable', result.status === 'unconfirmed');
407
+ }
408
+ decline(pending) {
409
+ if (!pending.confirmation || pending.decisionSent)
410
+ return;
411
+ pending.decisionSent = true;
412
+ void this.send('commerce.cart.confirmation.result', { schemaVersion: 1, operationId: pending.confirmation.operationId,
413
+ proposalChecksum: pending.confirmation.proposalChecksum, approved: false });
414
+ }
415
+ arm(pending, milliseconds) {
416
+ if (pending.timer)
417
+ clearTimeout(pending.timer);
418
+ pending.timer = setTimeout(() => {
419
+ if (this.pending !== pending || pending.started)
420
+ return;
421
+ this.decline(pending);
422
+ this.fail(pending, 'expired');
423
+ }, Math.max(1, milliseconds));
424
+ }
425
+ fail(pending, reason, uncertain = false) {
426
+ if (this.pending !== pending)
427
+ return;
428
+ if (this.hasUnresolved()) {
429
+ this.recoveryOutcome = failure(reason, true);
430
+ this.showRecovery();
431
+ }
432
+ else if (!this.destroyed)
433
+ this.options.view()?.setCommerceCartStatus(failure(reason, uncertain), this.cartUrl());
434
+ this.finish(pending);
435
+ }
436
+ finish(pending) {
437
+ if (pending.timer)
438
+ clearTimeout(pending.timer);
439
+ pending.timer = null;
440
+ if (this.pending !== pending)
441
+ return;
442
+ this.pending = null;
443
+ this.retiredRequests.add(pending.requestId);
444
+ while (this.retiredRequests.size > 32)
445
+ this.retiredRequests.delete(this.retiredRequests.values().next().value);
446
+ const operationId = pending.confirmation?.operationId ?? pending.grant?.operationId;
447
+ if (operationId) {
448
+ this.retired.add(operationId);
449
+ while (this.retired.size > 32)
450
+ this.retired.delete(this.retired.values().next().value);
451
+ }
452
+ this.options.view()?.clearCommerceCartConfirmation(pending.confirmation?.operationId);
453
+ this.options.view()?.setCommerceBusy(false);
454
+ }
455
+ cartUrl() {
456
+ const root = window.Shopify?.routes?.root;
457
+ const path = typeof root === 'string' && /^\/(?:[a-z]{2,3}(?:-[a-z0-9]{2,8})*\/)?$/iu.test(root) ? root : '/';
458
+ return new URL(`${path}cart`, this.options.bootstrap.store.origin).href;
459
+ }
460
+ async send(type, payload) {
461
+ try {
462
+ return await this.boundedAccepted(this.options.send(type, payload).accepted, 10000);
463
+ }
464
+ catch {
465
+ return false;
466
+ }
467
+ }
468
+ boundedAccepted(value, timeoutMs) {
469
+ return new Promise(resolve => {
470
+ const timeout = setTimeout(() => resolve(false), timeoutMs);
471
+ void value.then(accepted => { clearTimeout(timeout); resolve(accepted === true); }, () => { clearTimeout(timeout); resolve(false); });
472
+ });
473
+ }
474
+ }
475
+ exports.CartSession = CartSession;
@@ -0,0 +1,152 @@
1
+ export type CommerceStore = {
2
+ provider: 'shopify';
3
+ storeRef: string;
4
+ origin: string;
5
+ policyRevision: string;
6
+ };
7
+ export type CommerceMarket = {
8
+ country: string;
9
+ locale: string;
10
+ currency: string;
11
+ };
12
+ export type CommerceOption = {
13
+ name: string;
14
+ value: string;
15
+ };
16
+ export type CommerceBootstrap = {
17
+ schemaVersion: 1;
18
+ enabled: true;
19
+ guideId: string;
20
+ store: CommerceStore;
21
+ cartEnabled: boolean;
22
+ };
23
+ export type CommerceContext = {
24
+ schemaVersion: 1;
25
+ contextRevision: number;
26
+ pageId: string;
27
+ origin: string;
28
+ path: string;
29
+ pageType: 'product' | 'listing' | 'search' | 'cart' | 'help' | 'unknown';
30
+ market: CommerceMarket;
31
+ productRef: string | null;
32
+ selectedOptions: CommerceOption[];
33
+ };
34
+ export type CommerceContextClear = Pick<CommerceContext, 'schemaVersion' | 'contextRevision' | 'pageId'>;
35
+ export type CommerceVariant = {
36
+ variantRef: string;
37
+ title: string;
38
+ selectedOptions: CommerceOption[];
39
+ price: {
40
+ amount: string;
41
+ currency: string;
42
+ };
43
+ available: boolean;
44
+ requiresSellingPlan: boolean;
45
+ quantityRule: {
46
+ minimum: number;
47
+ maximum: number | null;
48
+ increment: number;
49
+ };
50
+ };
51
+ export type CommerceProduct = {
52
+ productRef: string;
53
+ title: string;
54
+ url: string;
55
+ image: {
56
+ url: string;
57
+ alt: string;
58
+ } | null;
59
+ description: string;
60
+ options: {
61
+ name: string;
62
+ values: string[];
63
+ complete: boolean;
64
+ }[];
65
+ variant: CommerceVariant | null;
66
+ };
67
+ export type CommerceCatalog = {
68
+ schemaVersion: 1;
69
+ type: 'commerce.catalog';
70
+ resultSetId: string;
71
+ guideId: string;
72
+ store: CommerceStore;
73
+ market: CommerceMarket;
74
+ fetchedAt: string;
75
+ expiresAt: string;
76
+ ranking: {
77
+ basis: 'shopify_best_selling' | 'relevance' | 'price_ascending' | 'catalog';
78
+ period: null;
79
+ };
80
+ products: CommerceProduct[];
81
+ };
82
+ export type CommerceCartSelection = {
83
+ productRef: string;
84
+ variantRef: string;
85
+ selectionDigest: string;
86
+ };
87
+ export type LiveCommerceCatalog = {
88
+ schemaVersion: 1;
89
+ taskId: string;
90
+ inputEpoch: number;
91
+ contextRevision: number;
92
+ pageId: string;
93
+ catalog: CommerceCatalog;
94
+ cartSelections?: CommerceCartSelection[];
95
+ };
96
+ export type RealtimeCommerceCatalog = {
97
+ schemaVersion: 1;
98
+ executionId: string;
99
+ functionCallId: string;
100
+ providerGenerationDigest: string;
101
+ contextRevision: number;
102
+ pageId: string;
103
+ catalog: CommerceCatalog;
104
+ cartSelections?: CommerceCartSelection[];
105
+ };
106
+ export type CommerceDisplayedProducts = {
107
+ productRef: string;
108
+ variantRef: string | null;
109
+ }[];
110
+ export type LiveCommerceDisplayed = Omit<LiveCommerceCatalog, 'catalog' | 'cartSelections'> & {
111
+ resultSetId: string;
112
+ products: CommerceDisplayedProducts;
113
+ };
114
+ export type RealtimeCommerceDisplayed = Omit<RealtimeCommerceCatalog, 'catalog' | 'cartSelections'> & {
115
+ resultSetId: string;
116
+ products: CommerceDisplayedProducts;
117
+ };
118
+ export type CommerceCatalogParseOptions = {
119
+ cartNegotiated: boolean;
120
+ };
121
+ type ObjectValue = Record<string, unknown>;
122
+ export declare const commerceUuid: (value: unknown) => value is string;
123
+ export declare const commerceCount: (value: unknown) => value is number;
124
+ export declare const commerceObject: (value: unknown, keys: readonly string[]) => value is ObjectValue;
125
+ export declare const isCommerceStore: (value: unknown) => value is CommerceStore;
126
+ export declare function isCommerceMarket(value: unknown): value is CommerceMarket;
127
+ export declare const isCommerceOptions: (value: unknown) => value is CommerceOption[];
128
+ export declare function parseCommerceBootstrap(value: unknown, guideId: string | undefined, origin: string): CommerceBootstrap | null;
129
+ export declare function sameCommerceStore(left: CommerceStore, right: CommerceStore): boolean;
130
+ export declare function sameCommerceMarket(left: CommerceMarket, right: CommerceMarket): boolean;
131
+ /** Match the runtime's public path; queries and fragments stay private. */
132
+ export declare function isCommercePath(value: unknown): value is string;
133
+ export declare function isCommerceContext(value: unknown): value is CommerceContext;
134
+ /** Browser reads are presentation only. Their store/market must still match the
135
+ * authenticated bootstrap and current page; a displayed card is never a cart grant. */
136
+ export declare function parseCommerceCatalog(value: unknown, authority: CommerceBootstrap, context: CommerceContext | null, now?: number): CommerceCatalog | null;
137
+ export declare function displayedCommerceProducts(catalog: CommerceCatalog): CommerceDisplayedProducts;
138
+ /** Visible cards may be a subset; receipts preserve the issued order and exact pairs. */
139
+ export declare function isDisplayedCommerceProducts(catalog: CommerceCatalog, value: unknown): value is CommerceDisplayedProducts;
140
+ /** Copy only presentation fields; cart selections never become display receipts. */
141
+ export declare function liveCommerceDisplayedReceipt(event: LiveCommerceCatalog): LiveCommerceDisplayed;
142
+ export declare function realtimeCommerceDisplayedReceipt(event: RealtimeCommerceCatalog): RealtimeCommerceDisplayed;
143
+ /** Use only after parsing the event against current context and negotiation.
144
+ * A selection identifies a displayed variant; it is not a cart operation grant. */
145
+ export declare function commerceCartSelection(event: LiveCommerceCatalog | RealtimeCommerceCatalog, productRef: string, variantRef: string): CommerceCartSelection | null;
146
+ export type LiveCommerceCorrelation = Pick<LiveCommerceCatalog, 'taskId' | 'inputEpoch'>;
147
+ export type RealtimeCommerceCorrelation = Pick<RealtimeCommerceCatalog, 'executionId' | 'functionCallId' | 'providerGenerationDigest'>;
148
+ /** The transport must first attest the current authenticated control connection.
149
+ * Optional expected IDs must come from independent task/provider state. */
150
+ export declare function parseLiveCommerceCatalog(value: unknown, authority: CommerceBootstrap, context: CommerceContext | null, expected?: LiveCommerceCorrelation, now?: number, options?: CommerceCatalogParseOptions): LiveCommerceCatalog | null;
151
+ export declare function parseRealtimeCommerceCatalog(value: unknown, authority: CommerceBootstrap, context: CommerceContext | null, expected?: RealtimeCommerceCorrelation, now?: number, options?: CommerceCatalogParseOptions): RealtimeCommerceCatalog | null;
152
+ export {};