@oxvo/ai-live-assist 7.5.27 → 7.5.29

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 (53) hide show
  1. package/cjs/AiLiveAssist.d.ts +3 -1
  2. package/cjs/AiLiveAssist.js +24 -0
  3. package/cjs/client.d.ts +5 -0
  4. package/cjs/client.js +6 -0
  5. package/cjs/commerce/cartRecovery.d.ts +26 -0
  6. package/cjs/commerce/cartRecovery.js +96 -0
  7. package/cjs/commerce/cartSession.d.ts +7 -1
  8. package/cjs/commerce/cartSession.js +61 -5
  9. package/cjs/commerce/realtimeCommerce.d.ts +1 -0
  10. package/cjs/commerce/realtimeCommerce.js +1 -0
  11. package/cjs/commerce/shopifyCart.d.ts +3 -0
  12. package/cjs/commerce/shopifyCart.js +26 -0
  13. package/cjs/guideAdmission.d.ts +1 -0
  14. package/cjs/guideAdmission.js +3 -0
  15. package/cjs/guideMeasurement.d.ts +1 -1
  16. package/cjs/guideMeasurement.js +1 -1
  17. package/cjs/liveControlChannel.d.ts +1 -1
  18. package/cjs/liveGuideWidget.d.ts +2 -0
  19. package/cjs/liveGuideWidget.js +6 -0
  20. package/cjs/merchantPreviewAdmission.d.ts +1 -0
  21. package/cjs/merchantPreviewAdmission.js +2 -0
  22. package/cjs/merchantPreviewStorage.js +12 -0
  23. package/cjs/ui.d.ts +3 -1
  24. package/cjs/ui.js +7 -5
  25. package/cjs/version.d.ts +1 -1
  26. package/cjs/version.js +1 -1
  27. package/lib/AiLiveAssist.d.ts +3 -1
  28. package/lib/AiLiveAssist.js +24 -0
  29. package/lib/client.d.ts +5 -0
  30. package/lib/client.js +6 -0
  31. package/lib/commerce/cartRecovery.d.ts +26 -0
  32. package/lib/commerce/cartRecovery.js +93 -0
  33. package/lib/commerce/cartSession.d.ts +7 -1
  34. package/lib/commerce/cartSession.js +61 -5
  35. package/lib/commerce/realtimeCommerce.d.ts +1 -0
  36. package/lib/commerce/realtimeCommerce.js +1 -0
  37. package/lib/commerce/shopifyCart.d.ts +3 -0
  38. package/lib/commerce/shopifyCart.js +26 -0
  39. package/lib/guideAdmission.d.ts +1 -0
  40. package/lib/guideAdmission.js +3 -0
  41. package/lib/guideMeasurement.d.ts +1 -1
  42. package/lib/guideMeasurement.js +1 -1
  43. package/lib/liveControlChannel.d.ts +1 -1
  44. package/lib/liveGuideWidget.d.ts +2 -0
  45. package/lib/liveGuideWidget.js +6 -0
  46. package/lib/merchantPreviewAdmission.d.ts +1 -0
  47. package/lib/merchantPreviewAdmission.js +2 -0
  48. package/lib/merchantPreviewStorage.js +12 -0
  49. package/lib/ui.d.ts +3 -1
  50. package/lib/ui.js +7 -5
  51. package/lib/version.d.ts +1 -1
  52. package/lib/version.js +1 -1
  53. package/package.json +1 -1
@@ -5,6 +5,7 @@ exports.merchantPreviewStorageKeys = merchantPreviewStorageKeys;
5
5
  exports.saveMerchantPreviewRecovery = saveMerchantPreviewRecovery;
6
6
  exports.readMerchantPreviewRecovery = readMerchantPreviewRecovery;
7
7
  const guideTypes_js_1 = require("./guideTypes.js");
8
+ const contracts_js_1 = require("./commerce/contracts.js");
8
9
  const invalid = () => new Error('The previous preview could not be recovered. Return to the original Console tab to check its status or wait for it to expire.');
9
10
  const PREVIEW_FIELDS = ['previewId', 'projectId', 'guideId', 'configurationVersionId', 'configurationRevision',
10
11
  'configurationChecksum', 'targetOrigin', 'targetPath', 'launchExpiresAt', 'expiresAt', 'runtimeUrl', 'widgetVersion'];
@@ -25,7 +26,15 @@ function merchantPreviewStorageKeys(preview) {
25
26
  const pick = (value, fields) => Object.fromEntries(fields.filter(key => key in value)
26
27
  .map(key => [key, value[key]]));
27
28
  function saveMerchantPreviewRecovery(preview, bootstrap, storage) {
29
+ const commerce = bootstrap.commerce === undefined ? null
30
+ : (0, contracts_js_1.parseCommerceBootstrap)(bootstrap.commerce, preview.guideId, preview.targetOrigin);
31
+ if (bootstrap.commerce !== undefined && !commerce)
32
+ throw invalid();
28
33
  const presentation = { ...pick(bootstrap, BOOTSTRAP_FIELDS),
34
+ ...(commerce ? { commerce: { schemaVersion: commerce.schemaVersion, enabled: commerce.enabled,
35
+ guideId: commerce.guideId, cartEnabled: commerce.cartEnabled,
36
+ store: { provider: commerce.store.provider, storeRef: commerce.store.storeRef,
37
+ origin: commerce.store.origin, policyRevision: commerce.store.policyRevision } } } : {}),
29
38
  ...(bootstrap.appearance ? { appearance: pick(bootstrap.appearance, APPEARANCE_FIELDS) } : {}) };
30
39
  const raw = JSON.stringify({ v: 1, preview: pick(preview, PREVIEW_FIELDS), bootstrap: presentation });
31
40
  if (raw.length > 65536 || /"(?:previewGrant|admissionGrant|controlCredential|subjectCredential)"\s*:/.test(raw))
@@ -52,5 +61,8 @@ function readMerchantPreviewRecovery(preview, storage) {
52
61
  if (value?.v !== 1 || !value.preview || !value.bootstrap ||
53
62
  JSON.stringify(value.preview) !== JSON.stringify(pick(preview, PREVIEW_FIELDS)))
54
63
  throw invalid();
64
+ if (value.bootstrap.commerce !== undefined &&
65
+ !(0, contracts_js_1.parseCommerceBootstrap)(value.bootstrap.commerce, preview.guideId, preview.targetOrigin))
66
+ throw invalid();
55
67
  return value.bootstrap;
56
68
  }
package/cjs/ui.d.ts CHANGED
@@ -284,7 +284,9 @@ export declare class WidgetView {
284
284
  setCommerceCartActionHandler(handler: CommerceAddHandler | null, canAdd?: CommerceCanAdd): void;
285
285
  showCommerceCartConfirmation(value: CommerceCartConfirmationView, onDecision: (approved: boolean) => void): void;
286
286
  clearCommerceCartConfirmation(operationId?: string): void;
287
- setCommerceCartStatus(outcome: ShopifyCartOutcome, cartUrl: string, onCheck?: () => void | Promise<void>): void;
287
+ setCommerceCartStatus(outcome: ShopifyCartOutcome, cartUrl: string, onCheck?: () => void | Promise<void>, options?: {
288
+ readOnlyRecovery?: boolean;
289
+ }): void;
288
290
  clearCommerceCartStatus(): void;
289
291
  setAdvancedSessionControlsVisible(visible: boolean): void;
290
292
  open(mode?: AssistMode): void;
package/cjs/ui.js CHANGED
@@ -4510,7 +4510,8 @@ class WidgetView {
4510
4510
  this.currentHandoffContextRequest !== null ||
4511
4511
  this.currentPageAssistanceRequest !== null ||
4512
4512
  this.panel.classList.contains("feedback-state") ||
4513
- Math.abs(event.deltaY) < Math.abs(event.deltaX)) {
4513
+ Math.abs(event.deltaY) < Math.abs(event.deltaX) ||
4514
+ event.composedPath().some((target) => target instanceof Element && target.classList.contains("commerce-slot"))) {
4514
4515
  return;
4515
4516
  }
4516
4517
  const maximum = Math.max(0, this.captions.scrollHeight - this.captions.clientHeight);
@@ -5781,9 +5782,10 @@ class WidgetView {
5781
5782
  if (current?.onDecision && (!operationId || current.actionId === operationId))
5782
5783
  this.resolveConfirmation(false);
5783
5784
  }
5784
- setCommerceCartStatus(outcome, cartUrl, onCheck) {
5785
+ setCommerceCartStatus(outcome, cartUrl, onCheck, options = {}) {
5785
5786
  this.clearCommerceCartStatus();
5786
- if (this.destroyed || !this.active)
5787
+ const available = () => !this.destroyed && (this.active || options.readOnlyRecovery === true);
5788
+ if (!available())
5787
5789
  return;
5788
5790
  if (this.semanticStatus === this.messages.commerceCartChecking && !this.currentConfirmation &&
5789
5791
  !this.currentVisualRequest && !this.currentHandoffContextRequest && !this.currentPageAssistanceRequest) {
@@ -5815,7 +5817,7 @@ class WidgetView {
5815
5817
  check.type = "button";
5816
5818
  check.textContent = this.messages.commerceCartRecheck;
5817
5819
  check.addEventListener("click", async () => {
5818
- if (check.disabled || this.destroyed || !this.active || this.commerceCartStatus !== status)
5820
+ if (check.disabled || !available() || this.commerceCartStatus !== status)
5819
5821
  return;
5820
5822
  check.disabled = true;
5821
5823
  check.setAttribute("aria-busy", "true");
@@ -5824,7 +5826,7 @@ class WidgetView {
5824
5826
  }
5825
5827
  catch { /* Keep the uncertain result available for another read-only check. */ }
5826
5828
  finally {
5827
- if (this.commerceCartStatus === status && check.isConnected && !this.destroyed && this.active) {
5829
+ if (this.commerceCartStatus === status && check.isConnected && available()) {
5828
5830
  check.disabled = false;
5829
5831
  check.removeAttribute("aria-busy");
5830
5832
  }
package/cjs/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "7.5.27";
1
+ export declare const VERSION = "7.5.29";
package/cjs/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
- exports.VERSION = '7.5.27';
4
+ exports.VERSION = '7.5.29';
@@ -34,7 +34,7 @@ export declare const normalizeAiGuideOpenInput: (input?: AiGuideOpenInput) => Re
34
34
  export declare const resolveAiGuideProtocolVersion: (bootstrap: Pick<BootstrapConfig, "experienceMode" | "minimumProtocolVersion" | "protocol">) => 1 | 2;
35
35
  export default class AiLiveAssist {
36
36
  private readonly options;
37
- readonly version = "7.5.27";
37
+ readonly version = "7.5.29";
38
38
  private readonly host;
39
39
  private readonly guideAdmission;
40
40
  private readonly standaloneAdmissionPending;
@@ -128,6 +128,7 @@ export default class AiLiveAssist {
128
128
  private media;
129
129
  private context;
130
130
  private commerce;
131
+ private idleCartRecovery;
131
132
  private commerceReadyChannel;
132
133
  private pendingCommerceGeneration;
133
134
  private presentation;
@@ -453,6 +454,7 @@ export default class AiLiveAssist {
453
454
  private waitForPendingContextNavigationAcknowledgements;
454
455
  private commerceBootstrap;
455
456
  private commerceCartEnabled;
457
+ private refreshIdleCartRecovery;
456
458
  private startRealtimeCommerce;
457
459
  private startContext;
458
460
  private startPresentation;
@@ -1,3 +1,4 @@
1
+ import { CartSession } from './commerce/cartSession.js';
1
2
  import { guideMountIdentity, guideStorageNamespace, resolveGuideHost, } from "./guideHost.js";
2
3
  import { claimGuideMount } from "./guideMount.js";
3
4
  import { RuntimeClient, RuntimeClientError, idempotencyKey, isValidAssistSessionGrant, isValidReplaySessionId, } from "./client.js";
@@ -1419,6 +1420,7 @@ export default class AiLiveAssist {
1419
1420
  this.media = null;
1420
1421
  this.context = null;
1421
1422
  this.commerce = null;
1423
+ this.idleCartRecovery = null;
1422
1424
  this.commerceReadyChannel = null;
1423
1425
  this.pendingCommerceGeneration = null;
1424
1426
  this.presentation = null;
@@ -2052,6 +2054,8 @@ export default class AiLiveAssist {
2052
2054
  this.clearReconnectTimer();
2053
2055
  if (this.destroyed)
2054
2056
  return;
2057
+ this.idleCartRecovery?.destroy();
2058
+ this.idleCartRecovery = null;
2055
2059
  this.commerce?.destroy();
2056
2060
  this.commerce = null;
2057
2061
  this.liveWidget?.destroy();
@@ -2242,6 +2246,7 @@ export default class AiLiveAssist {
2242
2246
  this.view = voicePresenceView
2243
2247
  ? new VoicePresenceView(effectiveBootstrap, this.options.messages ?? {}, callbacks, this.tabId, (fallback) => void this.activateFallback(fallback), this.options.visualTestMode === true)
2244
2248
  : new WidgetView(effectiveBootstrap, this.options.messages ?? {}, callbacks, this.standardWidgetViewOptions(effectiveBootstrap));
2249
+ this.refreshIdleCartRecovery();
2245
2250
  this.syncCompanionView();
2246
2251
  this.initializePageAssistancePreference(effectiveBootstrap);
2247
2252
  this.startMessengerIntegration(effectiveBootstrap);
@@ -8343,6 +8348,19 @@ export default class AiLiveAssist {
8343
8348
  commerceCartEnabled(bootstrap = this.bootstrap) {
8344
8349
  return bootstrap?.capabilities?.commerceCart === true && parseCommerceBootstrap(bootstrap.commerce, bootstrap.guideId, window.location.origin)?.cartEnabled === true;
8345
8350
  }
8351
+ refreshIdleCartRecovery() {
8352
+ this.idleCartRecovery?.destroy();
8353
+ this.idleCartRecovery = null;
8354
+ const bootstrap = this.commerceBootstrap();
8355
+ if (this.destroyed || this.liveWidget || this.commerce || !this.guideAdmission || !bootstrap?.cartEnabled || !(this.view instanceof WidgetView))
8356
+ return;
8357
+ this.idleCartRecovery = new CartSession({ bootstrap, recovery: this.guideAdmission.cartRecovery(),
8358
+ view: () => !this.destroyed && this.view instanceof WidgetView ? this.view : null,
8359
+ current: () => null, selection: () => null,
8360
+ send: () => { throw new Error('Cart recovery has no mutation transport.'); },
8361
+ });
8362
+ this.idleCartRecovery.refreshControls();
8363
+ }
8346
8364
  startRealtimeCommerce(preserveProvider = false) {
8347
8365
  const authority = this.commerceBootstrap();
8348
8366
  const sessionId = this.result?.sessionId;
@@ -8353,7 +8371,10 @@ export default class AiLiveAssist {
8353
8371
  }
8354
8372
  if (this.commerce?.sessionId !== sessionId) {
8355
8373
  this.commerce?.destroy();
8374
+ this.idleCartRecovery?.destroy();
8375
+ this.idleCartRecovery = null;
8356
8376
  this.commerce = new RealtimeCommerce(sessionId, authority, {
8377
+ ...(this.guideAdmission ? { recovery: this.guideAdmission.cartRecovery() } : {}),
8357
8378
  channel: () => this.channel,
8358
8379
  view: () => this.view instanceof WidgetView ? this.view : null,
8359
8380
  isCurrent: () => this.result?.sessionId === sessionId && !this.ended && !this.destroyed &&
@@ -15449,6 +15470,7 @@ export default class AiLiveAssist {
15449
15470
  else {
15450
15471
  this.view?.showResumeStopped?.();
15451
15472
  }
15473
+ this.refreshIdleCartRecovery();
15452
15474
  this.state("ended");
15453
15475
  }
15454
15476
  captureTerminalAuthorizedResult(result, sourceRecord = null) {
@@ -15747,6 +15769,7 @@ export default class AiLiveAssist {
15747
15769
  else {
15748
15770
  this.view?.showResumeStopped?.();
15749
15771
  }
15772
+ this.refreshIdleCartRecovery();
15750
15773
  this.state("ended");
15751
15774
  }
15752
15775
  presentTerminalEnding(error) {
@@ -15968,6 +15991,7 @@ export default class AiLiveAssist {
15968
15991
  quiesceLocalEffectsForTerminalRequest() {
15969
15992
  this.commerce?.destroy();
15970
15993
  this.commerce = null;
15994
+ this.refreshIdleCartRecovery();
15971
15995
  this.clearCtaAuthority();
15972
15996
  this.queuedLaunchToken = null;
15973
15997
  this.launchGeneration += 1;
package/lib/client.d.ts CHANGED
@@ -98,6 +98,11 @@ export declare class RuntimeClient {
98
98
  providerProtocol: "live";
99
99
  }>;
100
100
  launchLiveGuide(intent: LiveGuideLaunchIntent, admissionGrant: string, signal: AbortSignal, measurementBridge?: GuideMeasurementBridge): Promise<LiveControlAuthorization>;
101
+ inspectCartRecovery(input: import('./commerce/cartRecovery.js').CartRecoveryInput, signal: AbortSignal): Promise<unknown>;
102
+ reportCartRecovery(input: import('./commerce/cartRecovery.js').CartRecoveryInput & {
103
+ recoveryReceipt: string;
104
+ result: import('./commerce/cartContracts.js').CommerceCartExecutionResult;
105
+ }, signal: AbortSignal): Promise<unknown>;
101
106
  endLiveGuide(input: GuideLaunchRecoveryInput, signal?: AbortSignal): Promise<{
102
107
  schemaVersion: 3;
103
108
  protocolVersion: 2;
package/lib/client.js CHANGED
@@ -186,6 +186,12 @@ export class RuntimeClient {
186
186
  async launchLiveGuide(intent, admissionGrant, signal, measurementBridge) {
187
187
  return this.postGuideLaunch("/ai-live-assist/v1/public/live/launch", intent, admissionGrant, signal, measurementBridge);
188
188
  }
189
+ async inspectCartRecovery(input, signal) {
190
+ return this.postRawJson('/ai-live-assist/v1/public/cart/recovery/inspect', JSON.stringify(input), {}, signal, false, false, true);
191
+ }
192
+ async reportCartRecovery(input, signal) {
193
+ return this.postRawJson('/ai-live-assist/v1/public/cart/recovery/report', JSON.stringify(input), {}, signal, false, false, true);
194
+ }
189
195
  async endLiveGuide(input, signal) {
190
196
  return this.postJson("/ai-live-assist/v1/public/live/launches/end", input, {}, signal, true);
191
197
  }
@@ -0,0 +1,26 @@
1
+ import type { RuntimeClient } from '../client.js';
2
+ import type { GuideSubjectStore } from '../guideSubjectStore.js';
3
+ import { type CommerceCartExecutionResult } from './cartContracts.js';
4
+ import type { PreparedShopifyCartAddition, ShopifyCartExecutionEvidence } from './shopifyCart.js';
5
+ export type CartRecoveryInput = {
6
+ schemaVersion: 1;
7
+ installKey: string;
8
+ subjectCredential: string;
9
+ originalSessionId: string;
10
+ operationId: string;
11
+ executionId: string;
12
+ cartDigest: string;
13
+ };
14
+ export type CartRecoveryInspection = {
15
+ recoveryReceipt: string;
16
+ expiresAt: string;
17
+ executionResult: CommerceCartExecutionResult | null;
18
+ };
19
+ export type CartRecovery = {
20
+ available(): boolean;
21
+ inspect(prepared: PreparedShopifyCartAddition, execution: ShopifyCartExecutionEvidence): Promise<CartRecoveryInspection>;
22
+ report(prepared: PreparedShopifyCartAddition, inspection: CartRecoveryInspection, result: CommerceCartExecutionResult): Promise<boolean>;
23
+ };
24
+ /** One possession adapter for Live, Realtime and the isolated preview store.
25
+ * It cannot create a visitor, launch, grant, provider or paid session. */
26
+ export declare function createCartRecovery(runtime: RuntimeClient, installKey: string, store: GuideSubjectStore): CartRecovery;
@@ -0,0 +1,93 @@
1
+ import { commerceUuid } from './contracts.js';
2
+ import { parseCommerceCartResult } from './cartContracts.js';
3
+ const commerceObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ const stable = (value) => JSON.stringify(value, (_key, item) => commerceObject(item)
5
+ ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
6
+ const same = (a, b) => stable(a) === stable(b);
7
+ const unavailable = () => new Error('The original cart addition could not be checked.');
8
+ async function bounded(work, ms = 5000) {
9
+ const controller = new AbortController();
10
+ const timer = setTimeout(() => controller.abort(), ms);
11
+ try {
12
+ return await work(controller.signal);
13
+ }
14
+ finally {
15
+ clearTimeout(timer);
16
+ }
17
+ }
18
+ /** One possession adapter for Live, Realtime and the isolated preview store.
19
+ * It cannot create a visitor, launch, grant, provider or paid session. */
20
+ export function createCartRecovery(runtime, installKey, store) {
21
+ const subject = () => {
22
+ const value = store.readSubject();
23
+ return value && value.origin === location.origin && Date.parse(value.expiresAt) > Date.now() ? value : null;
24
+ };
25
+ const input = (prepared, execution) => {
26
+ const owner = subject();
27
+ if (!owner || !prepared.reportScope || !commerceUuid(prepared.reportSessionId) || prepared.guideId !== owner.guideId ||
28
+ prepared.store.origin !== location.origin)
29
+ throw unavailable();
30
+ return { schemaVersion: 1, installKey, subjectCredential: owner.credential, originalSessionId: prepared.reportSessionId,
31
+ operationId: prepared.operationId, executionId: execution.executionId, cartDigest: execution.cartDigest };
32
+ };
33
+ const possessions = new WeakMap();
34
+ return {
35
+ available: () => subject() !== null,
36
+ async inspect(prepared, execution) {
37
+ const body = input(prepared, execution);
38
+ const value = await bounded(signal => runtime.inspectCartRecovery(body, signal));
39
+ if (!commerceObject(value) || Object.keys(value).length !== 5 || value.schemaVersion !== 1 ||
40
+ !commerceObject(value.descriptor) || typeof value.recoveryReceipt !== 'string' ||
41
+ !/^\d{13}\.\d{13}\.[A-Za-z0-9_-]{32,86}$/u.test(value.recoveryReceipt) || typeof value.expiresAt !== 'string' ||
42
+ !Number.isFinite(Date.parse(value.expiresAt)) || Date.parse(value.expiresAt) <= Date.now() || Date.parse(value.expiresAt) > Date.now() + 8000 ||
43
+ input(prepared, execution).subjectCredential !== body.subjectCredential)
44
+ throw unavailable();
45
+ const descriptor = value.descriptor;
46
+ if (!commerceObject(descriptor.item) || typeof descriptor.item.title !== 'string' || descriptor.item.title.length > 1000)
47
+ throw unavailable();
48
+ const { title: _title, ...item } = descriptor.item;
49
+ void _title;
50
+ const expected = { schemaVersion: 1, originalSessionId: prepared.reportSessionId, guideId: prepared.guideId,
51
+ scope: prepared.reportScope, store: prepared.store, market: prepared.market, operationMarker: prepared.operationMarker,
52
+ executionId: execution.executionId, cartDigest: execution.cartDigest, expiresAt: prepared.expiresAt,
53
+ item: { productRef: prepared.productRef, variantRef: prepared.variantRef, shopifyVariantId: prepared.shopifyVariantId,
54
+ productUrl: prepared.productUrl, selectedOptions: prepared.selectedOptions, quantity: prepared.quantity,
55
+ unitPrice: prepared.unitPrice, quantityRule: prepared.quantityRule, requiresSellingPlan: false, requiresComponents: false } };
56
+ if (!same({ ...descriptor, item }, expected))
57
+ throw unavailable();
58
+ let known = null;
59
+ if (value.executionResult !== null) {
60
+ const result = value.executionResult;
61
+ if (!commerceObject(result))
62
+ throw unavailable();
63
+ const { request, observation, ...correlation } = result;
64
+ if (!same(correlation, { ...prepared.reportScope, executionId: execution.executionId, cartDigest: execution.cartDigest }) ||
65
+ !commerceObject(request) || (request.outcome === 'response'
66
+ ? Object.keys(request).length !== 2 || !Number.isInteger(request.httpStatus) || Number(request.httpStatus) < 100 || Number(request.httpStatus) > 599
67
+ : Object.keys(request).length !== 1 || !['unknown', 'timeout', 'aborted', 'network_error'].includes(String(request.outcome))))
68
+ throw unavailable();
69
+ if (observation !== null) {
70
+ if (!commerceObject(observation) || !parseCommerceCartResult({ schemaVersion: 1, requestId: prepared.reportScope.requestId,
71
+ operationId: prepared.operationId, executionId: execution.executionId, status: Number(observation.quantity) > 0 ? 'observed' : 'unconfirmed',
72
+ code: Number(observation.quantity) > 0 ? 'observed' : 'unconfirmed', observation }) || observation.operationMarker !== prepared.operationMarker ||
73
+ observation.shopifyVariantId !== prepared.shopifyVariantId || observation.currency !== prepared.unitPrice.currency ||
74
+ Number(observation.quantity) > prepared.quantity)
75
+ throw unavailable();
76
+ }
77
+ known = result;
78
+ }
79
+ const inspection = { recoveryReceipt: value.recoveryReceipt, expiresAt: value.expiresAt, executionResult: known };
80
+ possessions.set(inspection, body.subjectCredential);
81
+ return inspection;
82
+ },
83
+ async report(prepared, inspection, result) {
84
+ const body = input(prepared, result);
85
+ if (possessions.get(inspection) !== body.subjectCredential || Date.parse(inspection.expiresAt) <= Date.now())
86
+ return false;
87
+ const response = parseCommerceCartResult(await bounded(signal => runtime.reportCartRecovery({ ...body, recoveryReceipt: inspection.recoveryReceipt, result }, signal), Math.max(1, Math.min(5000, Date.parse(inspection.expiresAt) - Date.now()))));
88
+ return response !== null && response.requestId === result.requestId && response.operationId === result.operationId &&
89
+ response.executionId === result.executionId && ['observed', 'partial', 'unconfirmed'].includes(response.status) &&
90
+ (response.status === 'unconfirmed' || same(response.observation, result.observation)) && subject()?.credential === body.subjectCredential;
91
+ },
92
+ };
93
+ }
@@ -3,6 +3,7 @@ import type { CommerceAddHandler, CommerceCanAdd } from './productPanel.js';
3
3
  import type { CommerceBootstrap, CommerceCartSelection, CommerceContext, CommerceProduct, LiveCommerceDisplayed, RealtimeCommerceDisplayed } from './contracts.js';
4
4
  import { type CommerceCartProvider } from './cartContracts.js';
5
5
  import { type ShopifyCartOutcome } from './shopifyCart.js';
6
+ import type { CartRecovery } from './cartRecovery.js';
6
7
  export type CartSessionSnapshot = {
7
8
  sessionId: string;
8
9
  context: CommerceContext;
@@ -23,11 +24,14 @@ export type CommerceCartView = {
23
24
  setCommerceCartActionHandler(handler: CommerceAddHandler | null, canAdd?: CommerceCanAdd): void;
24
25
  showCommerceCartConfirmation(value: CommerceCartConfirmationView, onDecision: (approved: boolean) => void): void;
25
26
  clearCommerceCartConfirmation(operationId?: string): void;
26
- setCommerceCartStatus(outcome: ShopifyCartOutcome, cartUrl: string, onCheck?: () => void | Promise<void>): void;
27
+ setCommerceCartStatus(outcome: ShopifyCartOutcome, cartUrl: string, onCheck?: () => void | Promise<void>, options?: {
28
+ readOnlyRecovery?: boolean;
29
+ }): void;
27
30
  clearCommerceCartStatus(): void;
28
31
  };
29
32
  export type CartSessionOptions = {
30
33
  bootstrap: CommerceBootstrap;
34
+ recovery?: CartRecovery;
31
35
  view: () => CommerceCartView | null;
32
36
  /** Null unless disclosure, dedicated cart consent, cart negotiation and the
33
37
  * current session/provider fence are all effective. */
@@ -50,6 +54,7 @@ export declare class CartSession {
50
54
  private readonly retiredRequests;
51
55
  private recoveryOutcome;
52
56
  private recoveryInFlight;
57
+ private recoveryEpoch;
53
58
  private recoveryGrant;
54
59
  private recoveryBegin;
55
60
  private pendingReport;
@@ -76,6 +81,7 @@ export declare class CartSession {
76
81
  private report;
77
82
  private showRecovery;
78
83
  private checkCart;
84
+ private checkRetainedCart;
79
85
  private recoveryHandle;
80
86
  private beginRecovery;
81
87
  private begin;
@@ -35,6 +35,7 @@ export class CartSession {
35
35
  this.retiredRequests = new Set();
36
36
  this.recoveryOutcome = null;
37
37
  this.recoveryInFlight = null;
38
+ this.recoveryEpoch = 0;
38
39
  // At most one original grant, held only by this live instance. The public
39
40
  // recovery ledger deliberately contains no mutation credentials.
40
41
  this.recoveryGrant = null;
@@ -77,6 +78,16 @@ export class CartSession {
77
78
  this.checkCart = () => {
78
79
  if (this.recoveryInFlight)
79
80
  return this.recoveryInFlight;
81
+ if (this.options.recovery?.available() && !this.destroyed && !this.pending) {
82
+ // Assign before work begins, including synchronous early returns. Every
83
+ // simultaneous Check shares this promise and one inspect/read/report.
84
+ this.recoveryInFlight = Promise.resolve().then(() => this.checkRetainedCart()).catch(() => this.showRecovery()).finally(() => {
85
+ this.recoveryInFlight = null;
86
+ if (!this.destroyed)
87
+ this.refreshControls();
88
+ });
89
+ return this.recoveryInFlight;
90
+ }
80
91
  const current = this.options.current();
81
92
  if (this.destroyed || this.pending || !current)
82
93
  return Promise.resolve();
@@ -138,13 +149,13 @@ export class CartSession {
138
149
  this.refreshControls();
139
150
  }
140
151
  };
141
- this.recoveryInFlight = work();
152
+ this.recoveryInFlight = Promise.resolve().then(work);
142
153
  return this.recoveryInFlight;
143
154
  };
144
155
  }
145
156
  /** A catalog replaces the panel; install again after its visible receipt. */
146
157
  refreshControls() {
147
- if (!this.destroyed && !this.pending && this.options.current() && this.hasUnresolved())
158
+ if (!this.destroyed && !this.pending && (this.options.current() || this.options.recovery?.available()) && this.hasUnresolved())
148
159
  this.showRecovery();
149
160
  this.options.view()?.setCommerceCartActionHandler(this.destroyed || !this.options.bootstrap.cartEnabled ||
150
161
  !this.options.current() ? null : this.add, this.canAdd);
@@ -166,6 +177,7 @@ export class CartSession {
166
177
  this.result(payload);
167
178
  }
168
179
  cut() {
180
+ this.recoveryEpoch++;
169
181
  this.recoveryGrant = null;
170
182
  this.recoveryBegin?.resolve(null);
171
183
  this.pendingReport?.resolve(false);
@@ -394,9 +406,53 @@ export class CartSession {
394
406
  const observed = outcome.receipt && (outcome.status === 'confirmed' || outcome.status === 'partial');
395
407
  const current = this.options.current();
396
408
  const prepared = retained?.prepared;
397
- const canRecover = current && prepared && prepared.reportSessionId === current.sessionId &&
398
- (observed && prepared.reportScope || this.recoveryHandle(current, prepared));
399
- this.options.view()?.setCommerceCartStatus(observed ? outcome : { ...outcome, status: 'uncertain' }, this.cartUrl(), canRecover ? this.checkCart : undefined);
409
+ const canRecover = prepared && (this.options.recovery?.available() || current && prepared.reportSessionId === current.sessionId &&
410
+ (observed && prepared.reportScope || this.recoveryHandle(current, prepared)));
411
+ const readOnly = this.options.recovery?.available() ? [{ readOnlyRecovery: true }] : [];
412
+ this.options.view()?.setCommerceCartStatus(observed ? outcome : { ...outcome, status: 'uncertain' }, this.cartUrl(), canRecover ? this.checkCart : undefined, ...readOnly);
413
+ }
414
+ async checkRetainedCart() {
415
+ const recovery = this.options.recovery;
416
+ const epoch = this.recoveryEpoch;
417
+ const stillCurrent = () => !this.destroyed && !this.pending && this.recoveryEpoch === epoch && recovery?.available() === true;
418
+ const executor = this.recoveryExecutor(stillCurrent);
419
+ const retained = executor.peekPending(this.recoveryScope());
420
+ const prepared = retained?.prepared;
421
+ if (!recovery || !prepared?.reportScope || !prepared.reportSessionId || !retained?.outcome?.execution || !stillCurrent())
422
+ return;
423
+ const inspection = await recovery.inspect(prepared, retained.outcome.execution);
424
+ if (!stillCurrent() || Date.parse(inspection.expiresAt) <= Date.now())
425
+ return;
426
+ const known = inspection.executionResult;
427
+ let outcome = retained.outcome;
428
+ let report;
429
+ if (known?.observation && known.observation.quantity > 0) {
430
+ report = known;
431
+ }
432
+ else {
433
+ const read = this.recoveryExecutor(() => stillCurrent() && Date.now() < Date.parse(inspection.expiresAt));
434
+ outcome = await read.reconcile(prepared, retained.outcome.execution.executionId, { state: 'already_started',
435
+ executionId: retained.outcome.execution.executionId, cartDigest: retained.outcome.execution.cartDigest,
436
+ expiresAt: inspection.expiresAt }, { refreshObservation: true });
437
+ if (!outcome.execution || !stillCurrent())
438
+ return;
439
+ report = { ...scopeOf(prepared.reportScope), ...outcome.execution,
440
+ ...(known ? { request: known.request } : {}) };
441
+ }
442
+ if (!stillCurrent() || !await recovery.report(prepared, inspection, report) || !stillCurrent())
443
+ return;
444
+ const accepted = await executor.acceptRecoveryReport(prepared, report);
445
+ if (!stillCurrent())
446
+ return;
447
+ if (accepted)
448
+ outcome = { ...accepted, local: outcome.local };
449
+ this.recoveryOutcome = outcome;
450
+ if (this.hasUnresolved())
451
+ this.showRecovery();
452
+ else {
453
+ this.recoveryOutcome = null;
454
+ this.options.view()?.setCommerceCartStatus(outcome, this.cartUrl(), undefined, { readOnlyRecovery: true });
455
+ }
400
456
  }
401
457
  recoveryHandle(snapshot, prepared) {
402
458
  const retained = this.recoveryGrant;
@@ -47,6 +47,7 @@ export declare class RealtimeCommerce {
47
47
  isCurrent: () => boolean;
48
48
  sharePage: () => boolean;
49
49
  cartConsent?: () => boolean;
50
+ recovery?: import('./cartRecovery.js').CartRecovery;
50
51
  submit: (text: string) => boolean;
51
52
  });
52
53
  /** Called only after media.connect and the real provider's fence proof. */
@@ -35,6 +35,7 @@ export class RealtimeCommerce {
35
35
  this.publishContext();
36
36
  });
37
37
  this.cart = new CartSession({ bootstrap, view: options.view,
38
+ ...(options.recovery ? { recovery: options.recovery } : {}),
38
39
  transportSessionId: () => options.channel()?.sessionId ?? null,
39
40
  current: () => this.cartSnapshot(), selection: (productRef, variantRef) => this.currentCartSelection(productRef, variantRef),
40
41
  send: (type, payload) => {
@@ -110,6 +110,9 @@ export declare class ShopifyCartExecutor {
110
110
  peekPending(scope: LedgerScope): ShopifyCartRecovery | null;
111
111
  /** Call only after native accepted this exact report. Browser observation alone is not delivery. */
112
112
  acknowledgeReport(scope: LedgerScope, report: CommerceCartExecutionResult): boolean;
113
+ /** Called only after authenticated inspect/report of this exact original
114
+ * descriptor. Replays server-retained positive evidence without a new Add. */
115
+ acceptRecoveryReport(prepared: PreparedShopifyCartAddition, report: CommerceCartExecutionResult): Promise<ShopifyCartOutcome | null>;
113
116
  /** Restores only public intent and original evidence. Never consumes a grant or performs a POST. */
114
117
  reconcilePending(scope: ShopifyCartRecoveryScope): Promise<ShopifyCartRecovery>;
115
118
  execute(input: PreparedShopifyCartAddition, executionId: string): Promise<ShopifyCartOutcome>;
@@ -700,6 +700,32 @@ export class ShopifyCartExecutor {
700
700
  return false;
701
701
  }
702
702
  }
703
+ /** Called only after authenticated inspect/report of this exact original
704
+ * descriptor. Replays server-retained positive evidence without a new Add. */
705
+ async acceptRecoveryReport(prepared, report) {
706
+ try {
707
+ if (!validPrepared(prepared) || !prepared.reportScope || !validRequestOutcome(report.request) ||
708
+ !validSavedObservation(report.observation, prepared) || !await this.authority.assertCurrent(prepared))
709
+ return null;
710
+ const { executionId, cartDigest, request, observation, ...scope } = report;
711
+ if (reportScopeIdentity(scope) !== reportScopeIdentity(prepared.reportScope))
712
+ return null;
713
+ const key = ledgerKey(prepared), entries = readLedger(key);
714
+ const entry = entries.find(value => value.operationId === prepared.operationId);
715
+ if (!entry || entry.intentDigest !== await sha(intent(prepared)) || entry.executionId !== executionId || entry.cartDigest !== cartDigest ||
716
+ !await this.authority.assertCurrent(prepared))
717
+ return null;
718
+ entry.request = request;
719
+ entry.observation = observation;
720
+ entry.resolved = true;
721
+ entry.reportAccepted = true;
722
+ saveLedger(key, entries);
723
+ return retainedOutcome(prepared, entry);
724
+ }
725
+ catch {
726
+ return null;
727
+ }
728
+ }
703
729
  /** Restores only public intent and original evidence. Never consumes a grant or performs a POST. */
704
730
  async reconcilePending(scope) {
705
731
  const failure = (reason, prepared = null) => ({
@@ -15,6 +15,7 @@ export declare class GuideAdmission {
15
15
  readonly store: GuideSubjectStore;
16
16
  private readonly runtime;
17
17
  private guideMeasurementBridge?;
18
+ cartRecovery(): import("./commerce/cartRecovery.js").CartRecovery;
18
19
  private initialBootstrap;
19
20
  private currentBootstrap;
20
21
  private activeAdmission;
@@ -1,3 +1,4 @@
1
+ import { createCartRecovery } from './commerce/cartRecovery.js';
1
2
  import { RuntimeClientError, } from "./client.js";
2
3
  import { GUIDE_SUBJECT_CREDENTIAL_PATTERN, GUIDE_UUID_PATTERN, guideLaunchRequestId, } from "./guideTypes.js";
3
4
  import { currentGuideMeasurementBridge, prepareGuideMeasurementBridge, GUIDE_MEASUREMENT_CLIENT_VERSION } from './guideMeasurement.js';
@@ -26,6 +27,7 @@ export function validateGuideBootstrap(value, installKey) {
26
27
  }
27
28
  /** Server admission and local cancellation fences; no recorder or crypto substitute. */
28
29
  export class GuideAdmission {
30
+ cartRecovery() { return createCartRecovery(this.runtime, this.identity.installKey, this.store); }
29
31
  constructor(identity, store, runtime, bootstrap, recordingAdapter = null, guideMeasurementBridge) {
30
32
  this.identity = identity;
31
33
  this.store = store;
@@ -170,6 +172,7 @@ export class GuideAdmission {
170
172
  throw new RuntimeClientError("GUIDE_LAUNCH_PENDING", "Finish the previous AI Guide session before starting another.", true, null, 409);
171
173
  }
172
174
  const prior = previous.intent;
175
+ intent.clientVersion = prior.clientVersion;
173
176
  // Recovery keeps the original assignment even after consent/bridge expiry.
174
177
  if (prior.guideMeasurement)
175
178
  intent.guideMeasurement = { ...prior.guideMeasurement };
@@ -1,5 +1,5 @@
1
1
  import type { GuideMeasurementBridge, GuideMeasurementIntent } from './guideTypes.js';
2
- export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.27";
2
+ export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.29";
3
3
  export declare function isGuideMeasurementIntent(value: unknown): value is GuideMeasurementIntent;
4
4
  /** The managed analytics owner supplies possession; this check grants no authority. */
5
5
  export declare function currentGuideMeasurementBridge(value: unknown): value is GuideMeasurementBridge;
@@ -1,4 +1,4 @@
1
- export const GUIDE_MEASUREMENT_CLIENT_VERSION = '7.5.27';
1
+ export const GUIDE_MEASUREMENT_CLIENT_VERSION = '7.5.29';
2
2
  export function isGuideMeasurementIntent(value) {
3
3
  if (!value || typeof value !== 'object' || Array.isArray(value))
4
4
  return false;
@@ -1,7 +1,7 @@
1
1
  import { type MerchantPreviewRuntimePolicy } from './merchantPreviewOrigins.js';
2
2
  import { type LiveDuplexMediaOptions, type LiveDuplexMediaDependencies } from './liveDuplexMedia.js';
3
3
  import { type CommerceBootstrap, type CommerceContext, type CommerceCartSelection, type CommerceProduct, type CommerceContextClear, type LiveCommerceCatalog, type LiveCommerceDisplayed } from './commerce/contracts.js';
4
- export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.27";
4
+ export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.29";
5
5
  export declare const LIVE_CONTROL_CLIENT_CAPABILITIES: readonly ["live_duplex_v1", "live_local_wake_v1", "live_fragment_captions_v1"];
6
6
  declare const phases: readonly ["voice_off", "local_listening", "wake_buffering", "starting", "active", "tentative_idle", "closing", "uncertain", "muted", "suspended", "budget_blocked", "ended"];
7
7
  export type LiveControlState = {
@@ -4,10 +4,12 @@ import type { GuideAdmission } from './guideAdmission.js';
4
4
  import { RuntimeClient } from './client.js';
5
5
  import { type LiveGuideLaunchIntent } from './liveGuideAdmission.js';
6
6
  import { type LiveControlChannelOptions, type LiveControlAuthorization } from './liveControlChannel.js';
7
+ import type { CartRecovery } from './commerce/cartRecovery.js';
7
8
  export type LiveGuideStartIntent = Omit<LiveGuideLaunchIntent, 'installKey' | 'guideMeasurement'>;
8
9
  export type LiveGuideSessionAdmission = {
9
10
  readonly recoveryOnly?: boolean;
10
11
  readonly endMessage?: string;
12
+ cartRecovery?(): CartRecovery;
11
13
  canStart?(): boolean;
12
14
  hasPendingLaunch(): boolean;
13
15
  pendingLaunchId(): string | null;