@oxvo/ai-live-assist 7.5.26 → 7.5.28

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 (73) hide show
  1. package/cjs/AiLiveAssist.d.ts +3 -1
  2. package/cjs/AiLiveAssist.js +24 -0
  3. package/cjs/client.d.ts +12 -0
  4. package/cjs/client.js +18 -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 +3 -1
  18. package/cjs/liveControlChannel.js +4 -1
  19. package/cjs/liveGuideWidget.d.ts +22 -2
  20. package/cjs/liveGuideWidget.js +45 -8
  21. package/cjs/merchantPreview.d.ts +5 -0
  22. package/cjs/merchantPreview.js +148 -0
  23. package/cjs/merchantPreviewAdmission.d.ts +33 -0
  24. package/cjs/merchantPreviewAdmission.js +186 -0
  25. package/cjs/merchantPreviewOrigins.d.ts +6 -0
  26. package/cjs/merchantPreviewOrigins.js +24 -0
  27. package/cjs/merchantPreviewStorage.d.ts +9 -0
  28. package/cjs/merchantPreviewStorage.js +68 -0
  29. package/cjs/merchantPreviewTypes.d.ts +57 -0
  30. package/cjs/merchantPreviewTypes.js +2 -0
  31. package/cjs/standalone.d.ts +2 -0
  32. package/cjs/standalone.js +3 -1
  33. package/cjs/ui.d.ts +4 -1
  34. package/cjs/ui.js +13 -4
  35. package/cjs/version.d.ts +1 -1
  36. package/cjs/version.js +1 -1
  37. package/lib/AiLiveAssist.d.ts +3 -1
  38. package/lib/AiLiveAssist.js +24 -0
  39. package/lib/client.d.ts +12 -0
  40. package/lib/client.js +18 -0
  41. package/lib/commerce/cartRecovery.d.ts +26 -0
  42. package/lib/commerce/cartRecovery.js +93 -0
  43. package/lib/commerce/cartSession.d.ts +7 -1
  44. package/lib/commerce/cartSession.js +61 -5
  45. package/lib/commerce/realtimeCommerce.d.ts +1 -0
  46. package/lib/commerce/realtimeCommerce.js +1 -0
  47. package/lib/commerce/shopifyCart.d.ts +3 -0
  48. package/lib/commerce/shopifyCart.js +26 -0
  49. package/lib/guideAdmission.d.ts +1 -0
  50. package/lib/guideAdmission.js +3 -0
  51. package/lib/guideMeasurement.d.ts +1 -1
  52. package/lib/guideMeasurement.js +1 -1
  53. package/lib/liveControlChannel.d.ts +3 -1
  54. package/lib/liveControlChannel.js +4 -1
  55. package/lib/liveGuideWidget.d.ts +22 -2
  56. package/lib/liveGuideWidget.js +45 -8
  57. package/lib/merchantPreview.d.ts +5 -0
  58. package/lib/merchantPreview.js +144 -0
  59. package/lib/merchantPreviewAdmission.d.ts +33 -0
  60. package/lib/merchantPreviewAdmission.js +181 -0
  61. package/lib/merchantPreviewOrigins.d.ts +6 -0
  62. package/lib/merchantPreviewOrigins.js +18 -0
  63. package/lib/merchantPreviewStorage.d.ts +9 -0
  64. package/lib/merchantPreviewStorage.js +62 -0
  65. package/lib/merchantPreviewTypes.d.ts +57 -0
  66. package/lib/merchantPreviewTypes.js +1 -0
  67. package/lib/standalone.d.ts +2 -0
  68. package/lib/standalone.js +1 -0
  69. package/lib/ui.d.ts +4 -1
  70. package/lib/ui.js +13 -4
  71. package/lib/version.d.ts +1 -1
  72. package/lib/version.js +1 -1
  73. package/package.json +1 -1
@@ -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.26";
2
+ export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.28";
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.26';
1
+ export const GUIDE_MEASUREMENT_CLIENT_VERSION = '7.5.28';
2
2
  export function isGuideMeasurementIntent(value) {
3
3
  if (!value || typeof value !== 'object' || Array.isArray(value))
4
4
  return false;
@@ -1,6 +1,7 @@
1
+ import { type MerchantPreviewRuntimePolicy } from './merchantPreviewOrigins.js';
1
2
  import { type LiveDuplexMediaOptions, type LiveDuplexMediaDependencies } from './liveDuplexMedia.js';
2
3
  import { type CommerceBootstrap, type CommerceContext, type CommerceCartSelection, type CommerceProduct, type CommerceContextClear, type LiveCommerceCatalog, type LiveCommerceDisplayed } from './commerce/contracts.js';
3
- export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.26";
4
+ export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.28";
4
5
  export declare const LIVE_CONTROL_CLIENT_CAPABILITIES: readonly ["live_duplex_v1", "live_local_wake_v1", "live_fragment_captions_v1"];
5
6
  declare const phases: readonly ["voice_off", "local_listening", "wake_buffering", "starting", "active", "tentative_idle", "closing", "uncertain", "muted", "suspended", "budget_blocked", "ended"];
6
7
  export type LiveControlState = {
@@ -41,6 +42,7 @@ export interface LiveControlChannelOptions {
41
42
  tabId: string;
42
43
  media: MediaOptions;
43
44
  clock?: LiveControlClock;
45
+ previewRuntimePolicy?: MerchantPreviewRuntimePolicy;
44
46
  createWebSocket?: (url: string, protocols: string[]) => WebSocket;
45
47
  randomUUID?: () => string;
46
48
  onState(state: LiveControlState): void;
@@ -1,3 +1,4 @@
1
+ import { isPreviewRuntimeOrigin } from './merchantPreviewOrigins.js';
1
2
  import { LiveDuplexMedia } from './liveDuplexMedia.js';
2
3
  import { VERSION } from './version.js';
3
4
  import { parseLiveCommerceCatalog, displayedCommerceProducts, isDisplayedCommerceProducts, commerceCartSelection, liveCommerceDisplayedReceipt } from './commerce/contracts.js';
@@ -91,7 +92,9 @@ export class LiveControlChannel {
91
92
  if (!['https:', 'http:'].includes(trusted.protocol) || trusted.origin !== options.trustedRuntimeOrigin ||
92
93
  trusted.username || trusted.password || target.username || target.password || target.search || target.hash || target.pathname !== path ||
93
94
  target.protocol !== (trusted.protocol === 'https:' ? 'wss:' : 'ws:') || target.host !== trusted.host ||
94
- (trusted.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(trusted.hostname)))
95
+ (trusted.protocol === 'http:' && !(options.previewRuntimePolicy
96
+ ? isPreviewRuntimeOrigin(trusted, options.previewRuntimePolicy)
97
+ : ['localhost', '127.0.0.1', '[::1]'].includes(trusted.hostname))))
95
98
  throw unavailable();
96
99
  target.searchParams.set('session', String(value.sessionId));
97
100
  this.url = target.href;
@@ -2,19 +2,39 @@ import { WidgetView, type WidgetViewOptions } from './ui.js';
2
2
  import type { AiGuideControllerState, AiGuideOpenInput, BootstrapConfig, PluginOptions } from './types.js';
3
3
  import type { GuideAdmission } from './guideAdmission.js';
4
4
  import { RuntimeClient } from './client.js';
5
+ import { type LiveGuideLaunchIntent } from './liveGuideAdmission.js';
6
+ import { type LiveControlChannelOptions, type LiveControlAuthorization } from './liveControlChannel.js';
7
+ import type { CartRecovery } from './commerce/cartRecovery.js';
8
+ export type LiveGuideStartIntent = Omit<LiveGuideLaunchIntent, 'installKey' | 'guideMeasurement'>;
9
+ export type LiveGuideSessionAdmission = {
10
+ readonly recoveryOnly?: boolean;
11
+ readonly endMessage?: string;
12
+ cartRecovery?(): CartRecovery;
13
+ canStart?(): boolean;
14
+ hasPendingLaunch(): boolean;
15
+ pendingLaunchId(): string | null;
16
+ launch(intent: LiveGuideStartIntent, signal: AbortSignal): Promise<LiveControlAuthorization>;
17
+ end(signal?: AbortSignal, expectedLaunchRequestId?: string): Promise<void>;
18
+ };
5
19
  type Options = {
6
20
  bootstrap: BootstrapConfig;
7
- admission: GuideAdmission;
8
21
  runtime: RuntimeClient;
9
22
  tabId: string;
10
23
  locale: string;
24
+ previewRuntimePolicy?: LiveControlChannelOptions['previewRuntimePolicy'];
11
25
  messages: PluginOptions['messages'];
12
26
  viewOptions: WidgetViewOptions;
13
27
  acquire(): boolean;
14
28
  ownsActivity?(): boolean;
15
29
  release(): void;
16
30
  onState(): void;
17
- };
31
+ } & ({
32
+ admission: GuideAdmission;
33
+ sessionAdmission?: never;
34
+ } | {
35
+ sessionAdmission: LiveGuideSessionAdmission;
36
+ admission?: never;
37
+ });
18
38
  /** Actual widget protocol branch. Reuses WidgetView, visitor possession storage,
19
39
  * local detector/media and authenticated runtime; never constructs a Realtime
20
40
  * transport or grants model/provider authority on the browser's behalf. */
@@ -1,4 +1,5 @@
1
1
  import { WidgetView } from './ui.js';
2
+ import { RuntimeClientError } from './client.js';
2
3
  import { LiveGuideAdmission } from './liveGuideAdmission.js';
3
4
  import { LiveControlChannel, LIVE_CONTROL_CLIENT_VERSION, LIVE_CONTROL_CLIENT_CAPABILITIES } from './liveControlChannel.js';
4
5
  import { createLiveBrowserDetector, validateLiveBrowserAssets } from './liveBrowserDetector.js';
@@ -59,10 +60,22 @@ export class LiveGuideWidget {
59
60
  JSON.stringify(config.liveCapabilities) !== JSON.stringify(LIVE_CONTROL_CLIENT_CAPABILITIES))
60
61
  throw new Error('AI Guide Live is unavailable.');
61
62
  validateLiveBrowserAssets(config.liveAssets);
62
- this.admission = new LiveGuideAdmission(options.admission.identity, options.admission.store, options.runtime, options.admission);
63
+ if (options.sessionAdmission)
64
+ this.admission = options.sessionAdmission;
65
+ else {
66
+ const publicAdmission = options.admission;
67
+ const live = new LiveGuideAdmission(publicAdmission.identity, publicAdmission.store, options.runtime, publicAdmission);
68
+ this.admission = {
69
+ cartRecovery: () => publicAdmission.cartRecovery(),
70
+ hasPendingLaunch: () => live.hasPendingLaunch(),
71
+ pendingLaunchId: () => live.pendingLaunchId(),
72
+ launch: (intent, signal) => live.launch({ ...intent, installKey: publicAdmission.identity.installKey }, signal),
73
+ end: (signal, expectedLaunchRequestId) => live.end(signal, expectedLaunchRequestId),
74
+ };
75
+ }
63
76
  const callbacks = {
64
77
  onStart: (mode, scopes, question) => this.start(mode, scopes, question),
65
- onRestart: () => !this.active && !this.starting && !this.ending && !this.admission.hasPendingLaunch(),
78
+ onRestart: () => !this.active && !this.starting && !this.ending && !this.admission.hasPendingLaunch() && this.admission.canStart?.() !== false,
66
79
  onEnd: () => { void this.end().catch(() => undefined); },
67
80
  onMute: muted => { if (muted)
68
81
  this.privacy('mute');
@@ -103,6 +116,7 @@ export class LiveGuideWidget {
103
116
  this.commerceCart = this.commerce?.cartEnabled && config.capabilities?.commerceCart === true ? new CartSession({
104
117
  bootstrap: this.commerce, view: () => this.destroyed ? null : this.view,
105
118
  current: () => this.currentCartSnapshot(),
119
+ ...(this.admission.cartRecovery ? { recovery: this.admission.cartRecovery() } : {}),
106
120
  transportSessionId: () => this.channel?.sessionId ?? null,
107
121
  selection: (productRef, variantRef) => {
108
122
  this.commerceContext?.refresh();
@@ -119,12 +133,17 @@ export class LiveGuideWidget {
119
133
  },
120
134
  }) : null;
121
135
  this.commerceContext?.start();
136
+ this.commerceCart?.refreshControls();
122
137
  if (this.admission.hasPendingLaunch()) {
123
138
  if (this.acquireLock()) {
124
139
  this.ownedLaunchId = this.admission.pendingLaunchId();
125
140
  void this.end().catch(() => undefined);
126
141
  }
127
142
  }
143
+ else if (this.admission.recoveryOnly) {
144
+ this.phase = 'ended';
145
+ this.view.showLaunchUnavailable(this.admission.endMessage ?? this.view.message('ended'));
146
+ }
128
147
  // Capture runs before TabActivityLock releases cross-tab ownership.
129
148
  window.addEventListener('pagehide', this.pagehide, true);
130
149
  window.addEventListener('focus', this.refreshOwnership);
@@ -142,6 +161,7 @@ export class LiveGuideWidget {
142
161
  this.requestIds.delete(this.requestIds.values().next().value);
143
162
  }
144
163
  this.view.open(input.mode ?? this.mode);
164
+ this.commerceCart?.refreshControls();
145
165
  if (input.question) {
146
166
  if (this.active)
147
167
  this.submitText(input.question, true);
@@ -157,7 +177,7 @@ export class LiveGuideWidget {
157
177
  companion: false, pendingQuestion: this.pendingQuestions.length > 0 };
158
178
  }
159
179
  start(mode, scopes, question) {
160
- if (this.destroyed || this.starting || this.active || this.ending ||
180
+ if (this.destroyed || this.starting || this.active || this.ending || this.admission.canStart?.() === false ||
161
181
  (question && (!question.trim() || question.length > 4000)) || !this.acquireLock())
162
182
  return false;
163
183
  // Recover abandoned intent only after acquiring the actual activity lock;
@@ -175,7 +195,7 @@ export class LiveGuideWidget {
175
195
  this.operation = operation;
176
196
  const timeout = setTimeout(() => operation.abort(), 20000);
177
197
  const config = this.options.bootstrap;
178
- const intent = { schemaVersion: 3, protocolVersion: 2, installKey: this.options.admission.identity.installKey,
198
+ const intent = { schemaVersion: 3, protocolVersion: 2,
179
199
  launchRequestId: crypto.randomUUID(), clientVersion: LIVE_CONTROL_CLIENT_VERSION, liveCapabilities: LIVE_CONTROL_CLIENT_CAPABILITIES,
180
200
  configRevision: config.configRevision, path: location.pathname, tabId: this.options.tabId, mode, experienceMode: 'standard',
181
201
  consent: { disclosureChecksum: config.consent.disclosureChecksum, scopes: [...scopes], locale: this.options.locale },
@@ -195,6 +215,7 @@ export class LiveGuideWidget {
195
215
  throw new Error('Cancelled.');
196
216
  const audio = this.view.livePlaybackElement();
197
217
  const channel = new LiveControlChannel({ authorization, trustedRuntimeOrigin: new URL(this.options.runtime.baseUrl).origin,
218
+ ...(this.options.previewRuntimePolicy ? { previewRuntimePolicy: this.options.previewRuntimePolicy } : {}),
198
219
  tabId: this.options.tabId, onState: state => this.onControlState(state),
199
220
  onClose: reason => {
200
221
  if (this.channel === channel && !this.ending && !this.destroyed) {
@@ -577,11 +598,26 @@ export class LiveGuideWidget {
577
598
  this.ownedLaunchId = null;
578
599
  this.phase = 'ended';
579
600
  this.releaseLock();
580
- if (!this.destroyed)
581
- this.view.showResumeStopped();
601
+ if (!this.destroyed) {
602
+ if (this.admission.endMessage)
603
+ this.view.showLaunchUnavailable(this.admission.endMessage);
604
+ else
605
+ this.view.showResumeStopped();
606
+ this.commerceCart?.refreshControls();
607
+ }
582
608
  this.options.onState();
583
- }).catch(error => { this.phase = 'error'; if (!this.destroyed)
584
- this.view.showError(this.view.message('error'), true); throw error; })
609
+ }).catch(error => {
610
+ this.phase = 'error';
611
+ if (!this.destroyed) {
612
+ if (this.admission.recoveryOnly && error instanceof RuntimeClientError && error.code === 'MERCHANT_PREVIEW_END_UNRESOLVED') {
613
+ this.view.showLaunchUnavailable(error.message);
614
+ }
615
+ else
616
+ this.view.showError(this.view.message('error'), true);
617
+ }
618
+ this.options.onState();
619
+ throw error;
620
+ })
585
621
  .finally(() => { if (this.ending === pending)
586
622
  this.ending = null; });
587
623
  this.ending = pending;
@@ -636,6 +672,7 @@ export class LiveGuideWidget {
636
672
  channel?.end();
637
673
  this.operation?.abort();
638
674
  this.operation = null;
675
+ this.commerceCart?.refreshControls();
639
676
  }
640
677
  destroy() {
641
678
  if (this.destroyed)
@@ -0,0 +1,5 @@
1
+ import { type AiGuideController } from './guideTypes.js';
2
+ import type { MerchantPreviewBootstrap, MerchantPreviewOptions } from './merchantPreviewTypes.js';
3
+ export type { MerchantPreviewOptions } from './merchantPreviewTypes.js';
4
+ export declare function validateMerchantPreviewBootstrap(value: MerchantPreviewBootstrap, preview: MerchantPreviewOptions): MerchantPreviewBootstrap;
5
+ export declare function installMerchantGuidePreview(input: MerchantPreviewOptions): Promise<AiGuideController>;
@@ -0,0 +1,144 @@
1
+ import { RuntimeClient, RuntimeClientError } from './client.js';
2
+ import { isLocalConsoleOrigin, isPreviewRuntimeOrigin } from './merchantPreviewOrigins.js';
3
+ import { validateGuideBootstrap } from './guideAdmission.js';
4
+ import { GUIDE_INSTALL_KEY_PATTERN, GUIDE_UUID_PATTERN } from './guideTypes.js';
5
+ import { mountedGuide, PendingGuideMount } from './guideMount.js';
6
+ import { LiveGuideWidget } from './liveGuideWidget.js';
7
+ import { MerchantPreviewAdmission, merchantPreviewNamespace } from './merchantPreviewAdmission.js';
8
+ import { readMerchantPreviewRecovery } from './merchantPreviewStorage.js';
9
+ import { TabActivityLock } from './tabLock.js';
10
+ import { VERSION } from './version.js';
11
+ const invalid = () => new RuntimeClientError('MERCHANT_PREVIEW_INVALID', 'This preview could not be opened. Open it again from OXVO.', false, null, 409);
12
+ const positive = (value) => Number.isSafeInteger(value) && value > 0;
13
+ const timestamp = (value) => typeof value === 'string' ? Date.parse(value) : NaN;
14
+ function captureOptions(input) {
15
+ if (!input || !GUIDE_UUID_PATTERN.test(input.previewId) || !GUIDE_UUID_PATTERN.test(input.guideId) ||
16
+ !positive(input.projectId) || !positive(input.configurationVersionId) || !positive(input.configurationRevision) ||
17
+ !/^[a-f0-9]{64}$/.test(input.configurationChecksum) || input.targetOrigin !== location.origin ||
18
+ input.targetPath !== location.pathname || !/^\/(?!\/)[^\x00-\x20\\?#]*$/.test(input.targetPath) || input.targetPath.length > 2048 ||
19
+ input.widgetVersion !== VERSION || typeof input.previewGrant !== 'string' ||
20
+ input.previewGrant.length > 4096 || !/^[\x21-\x7e]*$/.test(input.previewGrant) ||
21
+ !Number.isFinite(timestamp(input.launchExpiresAt)) ||
22
+ !Number.isFinite(timestamp(input.expiresAt)) || timestamp(input.expiresAt) < timestamp(input.launchExpiresAt))
23
+ throw invalid();
24
+ if (input.developmentConsoleOrigin !== undefined && !isLocalConsoleOrigin(input.developmentConsoleOrigin))
25
+ throw invalid();
26
+ const runtime = new URL(input.runtimeUrl);
27
+ if (runtime.username || runtime.password || runtime.search || runtime.hash || runtime.pathname !== '/' ||
28
+ !isPreviewRuntimeOrigin(runtime, input))
29
+ throw invalid();
30
+ return { previewId: input.previewId, projectId: input.projectId, guideId: input.guideId,
31
+ configurationVersionId: input.configurationVersionId, configurationRevision: input.configurationRevision,
32
+ configurationChecksum: input.configurationChecksum, targetOrigin: input.targetOrigin, targetPath: input.targetPath,
33
+ launchExpiresAt: input.launchExpiresAt, expiresAt: input.expiresAt, runtimeUrl: runtime.href,
34
+ widgetVersion: input.widgetVersion, previewGrant: input.previewGrant,
35
+ ...(input.developmentConsoleOrigin ? { developmentConsoleOrigin: input.developmentConsoleOrigin } : {}),
36
+ ...(typeof input.onState === 'function' ? { onState: input.onState } : {}),
37
+ ...(typeof input.onError === 'function' ? { onError: input.onError } : {}) };
38
+ }
39
+ export function validateMerchantPreviewBootstrap(value, preview) {
40
+ const config = validateGuideBootstrap(value, value?.installKey);
41
+ const metadata = value?.merchantPreview;
42
+ if (!GUIDE_INSTALL_KEY_PATTERN.test(config.installKey) || config.projectId !== preview.projectId || config.guideId !== preview.guideId ||
43
+ config.configRevision !== preview.configurationRevision || config.configChecksum !== `sha256:${preview.configurationChecksum}` ||
44
+ value.providerProtocol !== 'live' || value.widgetVersion !== preview.widgetVersion || value.experienceMode !== 'standard' ||
45
+ value.capabilities?.guideMeasurementV1 === true || value.replayRecordingEnabled === true ||
46
+ !metadata || metadata.previewId !== preview.previewId || metadata.configurationVersionId !== preview.configurationVersionId ||
47
+ metadata.targetOrigin !== preview.targetOrigin || metadata.targetPath !== preview.targetPath ||
48
+ timestamp(metadata.expiresAt) !== timestamp(preview.expiresAt))
49
+ throw invalid();
50
+ return value;
51
+ }
52
+ export function installMerchantGuidePreview(input) {
53
+ try {
54
+ if (window.self !== window.top || window.location.origin === 'null')
55
+ throw invalid();
56
+ const preview = captureOptions(input);
57
+ const recovery = readMerchantPreviewRecovery(preview, sessionStorage);
58
+ if (!recovery && (!preview.previewGrant || timestamp(preview.launchExpiresAt) <= Date.now()))
59
+ throw invalid();
60
+ const namespace = merchantPreviewNamespace(preview.targetOrigin, preview.previewId);
61
+ const mountIdentity = `merchant-preview:${namespace}`;
62
+ const current = mountedGuide(document, mountIdentity);
63
+ if (current)
64
+ return Promise.resolve(current);
65
+ const mount = new PendingGuideMount(document, mountIdentity);
66
+ void (async () => {
67
+ let lock;
68
+ let widget;
69
+ let admission;
70
+ const operation = new AbortController();
71
+ const timeout = window.setTimeout(() => operation.abort(), 15000);
72
+ try {
73
+ const runtime = new RuntimeClient(preview.runtimeUrl, VERSION);
74
+ const locale = (navigator.language || 'en').slice(0, 32);
75
+ const bootstrap = validateMerchantPreviewBootstrap(recovery ?? await runtime.bootstrapMerchantPreview({ schemaVersion: 1,
76
+ previewId: preview.previewId, previewGrant: preview.previewGrant, path: preview.targetPath, requestedLocale: locale }, operation.signal), preview);
77
+ if (operation.signal.aborted || location.origin !== preview.targetOrigin || location.pathname !== preview.targetPath)
78
+ throw invalid();
79
+ admission = new MerchantPreviewAdmission(preview, bootstrap, runtime, sessionStorage, recovery !== null);
80
+ const ownerId = `preview:${crypto.randomUUID()}`;
81
+ const tabKey = `__oxvo_ai_guide_preview_tab_${namespace}`;
82
+ let tabId = sessionStorage.getItem(tabKey);
83
+ if (!tabId || !/^[A-Za-z0-9_.:/-]{1,128}$/.test(tabId)) {
84
+ tabId = `preview:${crypto.randomUUID()}`;
85
+ sessionStorage.setItem(tabKey, tabId);
86
+ if (sessionStorage.getItem(tabKey) !== tabId)
87
+ throw invalid();
88
+ }
89
+ const reportState = () => {
90
+ if (!widget)
91
+ return;
92
+ const state = widget.getState();
93
+ try {
94
+ preview.onState?.(state);
95
+ }
96
+ catch { /* A host observer cannot interrupt session cleanup. */ }
97
+ window.dispatchEvent(new CustomEvent('oxvo-ai-guide:state', { detail: state }));
98
+ };
99
+ lock = new TabActivityLock(namespace, ownerId, active => widget?.onTabActivityChange(active), undefined, undefined, {
100
+ onBeforePageHideRelease: () => { void widget?.end().catch(() => undefined); },
101
+ });
102
+ const activity = lock;
103
+ widget = new LiveGuideWidget({ bootstrap, sessionAdmission: admission, runtime, tabId, locale, messages: {},
104
+ previewRuntimePolicy: preview.developmentConsoleOrigin ? { developmentConsoleOrigin: preview.developmentConsoleOrigin } : {},
105
+ viewOptions: { storageNamespace: namespace, initialPanelView: 'expanded',
106
+ contextNotice: recovery ? 'Finishing your previous preview. If it cannot finish here, check its status in the original Console tab or wait for it to expire.'
107
+ : `Saved draft · Revision ${preview.configurationRevision}. This preview uses OXVO Credits.` },
108
+ acquire: () => activity.acquire(), ownsActivity: () => activity.ownsActivity(), release: () => activity.release(), onState: reportState });
109
+ const live = widget;
110
+ const session = admission;
111
+ let destroyed = false;
112
+ const controller = {
113
+ version: VERSION,
114
+ open: value => live.open(value), close: () => live.close(), getState: () => live.getState(), end: () => live.end(),
115
+ destroy: () => {
116
+ if (destroyed)
117
+ return;
118
+ destroyed = true;
119
+ const ended = live.end();
120
+ live.destroy();
121
+ void ended.catch(() => undefined).finally(() => { session.destroy(); activity.destroy(); mount.release(); });
122
+ },
123
+ };
124
+ mount.promote(document, mountIdentity, controller);
125
+ mount.resolve(controller);
126
+ reportState();
127
+ }
128
+ catch (error) {
129
+ widget?.destroy();
130
+ admission?.destroy();
131
+ lock?.destroy();
132
+ mount.release();
133
+ mount.reject(error);
134
+ }
135
+ finally {
136
+ window.clearTimeout(timeout);
137
+ }
138
+ })();
139
+ return mount.promise;
140
+ }
141
+ catch (error) {
142
+ return Promise.reject(error);
143
+ }
144
+ }
@@ -0,0 +1,33 @@
1
+ import { RuntimeClient } from './client.js';
2
+ import type { LiveControlAuthorization } from './liveControlChannel.js';
3
+ import type { LiveGuideSessionAdmission, LiveGuideStartIntent } from './liveGuideWidget.js';
4
+ import type { MerchantPreviewBootstrap, MerchantPreviewOptions } from './merchantPreviewTypes.js';
5
+ export { merchantPreviewNamespace } from './merchantPreviewStorage.js';
6
+ export declare class MerchantPreviewAdmission implements LiveGuideSessionAdmission {
7
+ private readonly preview;
8
+ private readonly bootstrap;
9
+ private readonly runtime;
10
+ private readonly storage;
11
+ readonly recoveryOnly: boolean;
12
+ cartRecovery(): import("./commerce/cartRecovery.js").CartRecovery;
13
+ readonly endMessage = "Preview ended. Return to Console to open another preview.";
14
+ private readonly store;
15
+ private readonly originalKey;
16
+ private admission;
17
+ private admitting;
18
+ private ending;
19
+ private grant;
20
+ constructor(preview: MerchantPreviewOptions, bootstrap: MerchantPreviewBootstrap, runtime: RuntimeClient, storage?: Storage, recoveryOnly?: boolean);
21
+ canStart(): boolean;
22
+ hasPendingLaunch(): boolean;
23
+ pendingLaunchId(): string | null;
24
+ destroy(): void;
25
+ launch(input: LiveGuideStartIntent, signal: AbortSignal): Promise<LiveControlAuthorization>;
26
+ private reportError;
27
+ private start;
28
+ end(signal?: AbortSignal, expectedLaunchRequestId?: string): Promise<void>;
29
+ private finish;
30
+ private admit;
31
+ private original;
32
+ private writeOriginal;
33
+ }