@alytegen/sdk 0.7.0 → 0.9.0-next.1

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.
package/dist/browser.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { DiscoveredEvent, Scheme } from './types.js';
1
+ import type { DiscoveredEvent, PaymentResult, Scheme } from './types.js';
2
+ import type { BasketLineOutcome, SeatDecision, SeatRequest } from './baskets.js';
2
3
  export { AlyteApiError } from './http.js';
3
4
  export interface BuyerConnection {
4
5
  bearer: string;
@@ -49,16 +50,89 @@ export interface BuyerAgent {
49
50
  mandates: BuyerMandate[];
50
51
  }
51
52
  export interface BuyerWatch {
53
+ /** On a basket watch, `tierId` and `quantity` are those of its first required line; read `lines` for the basket. */
52
54
  id: string;
53
55
  agentId: string;
54
56
  merchantId: string;
55
57
  tierId: string;
56
58
  quantity: number;
57
- status: 'queued' | 'paused' | 'firing' | 'fired' | 'failed' | 'cancelled' | 'expired';
58
- result?: Record<string, unknown>;
59
+ lines?: BuyerBasketLine[];
60
+ status: 'queued' | 'paused' | 'firing' | 'awaiting_sca' | 'fired' | 'failed' | 'cancelled' | 'expired';
61
+ result?: BuyerWatchResult;
59
62
  expiresAt?: string;
60
63
  createdAt: string;
61
64
  firedAt?: string;
65
+ /** Absent on legacy watches and older servers: treat as availability. */
66
+ conditionSpec?: WatchCondition;
67
+ /** Server-computed place in line. Absent on older servers = unavailable, never position zero. */
68
+ queue?: WatchQueueSnapshot;
69
+ }
70
+ /** A pending purchase keeps its original identity; openChallenge never buys or requeues it. */
71
+ export type BuyerWatchResult = Record<string, unknown> & {
72
+ status?: string;
73
+ purchaseId?: string;
74
+ challenge?: {
75
+ expiresAt: string;
76
+ };
77
+ code?: string;
78
+ };
79
+ export type WatchCondition = {
80
+ kind: 'available';
81
+ } | {
82
+ kind: 'price_at_or_below';
83
+ maxChargeMinor: number;
84
+ currency: 'EUR' | 'GBP' | 'USD';
85
+ };
86
+ /** Unknown future values must render as a generic waiting state. */
87
+ export type WatchWaitingReason = 'access_window' | 'price_target' | 'stock' | 'whole_party' | (string & {});
88
+ export type QueuePlace = {
89
+ kind: 'assigned' | 'provisional';
90
+ position: number;
91
+ requestsAhead: number;
92
+ } | {
93
+ kind: 'unassigned';
94
+ reason: 'condition_not_met' | 'paused' | (string & {});
95
+ } | {
96
+ kind: 'not_waiting';
97
+ reason: 'processing' | 'reconciling' | 'terminal' | (string & {});
98
+ } | {
99
+ kind: 'unavailable';
100
+ };
101
+ export interface WatchQueueSnapshot {
102
+ schemaVersion: 1;
103
+ /** Decimal monotonic sequence — compare with BigInt, never Number. */
104
+ revision: string;
105
+ observedAt: string;
106
+ refreshAfterMs: number;
107
+ /** `phaseId` 'general' or 'rule:<id>' (an access window, labelled by the merchant); a place counts within its phase. */
108
+ queue: {
109
+ id: string;
110
+ label: string;
111
+ phaseId?: string;
112
+ phaseLabel?: string;
113
+ };
114
+ policyVersion: string;
115
+ place: QueuePlace;
116
+ waitingReason?: WatchWaitingReason;
117
+ nextEligibleAt?: string;
118
+ observedChargeMinor?: number;
119
+ }
120
+ export interface WatchInstruction {
121
+ /** Save the whole instruction (not the bearer) BEFORE sending; reuse this UUID after an uncertain response. */
122
+ requestId: string;
123
+ agentId: string;
124
+ /** One ticket type, or `lines` for a basket (never both). */
125
+ request: {
126
+ kind: 'ticketing';
127
+ tierId: string;
128
+ quantity: number;
129
+ } | {
130
+ kind: 'ticketing';
131
+ lines: BuyerBasketLine[];
132
+ };
133
+ condition: WatchCondition;
134
+ /** ISO-8601 with an explicit offset, e.g. 2026-11-01T12:00:00Z. */
135
+ expiresAt: string;
62
136
  }
63
137
  export type BuyerPurchase = {
64
138
  status: 'settled' | 'pending';
@@ -67,12 +141,63 @@ export type BuyerPurchase = {
67
141
  currency: string;
68
142
  paymentState?: string;
69
143
  agentName?: string;
70
- } | {
144
+ /** Set on a basket buy: its reservation and the priced lines (integer minor units). */
145
+ reservationId?: string;
146
+ lines?: BasketPurchaseLine[];
147
+ } & BasketPurchaseDetail | {
148
+ status: 'sca_required';
149
+ purchaseId: string;
150
+ challenge: {
151
+ expiresAt: string;
152
+ };
153
+ } & BasketPurchaseDetail | {
71
154
  status: 'sca_required';
155
+ purchaseId?: never;
156
+ challenge?: never;
157
+ } & BasketPurchaseDetail | {
158
+ status: 'pending';
159
+ purchaseId: string;
72
160
  } | {
73
161
  status: 'refused' | 'error';
74
162
  outcome: unknown;
75
- };
163
+ } & BasketPurchaseDetail;
164
+ /** Extra detail on a basket buy. `lineOutcomes` lists every requested line when the basket allowed a
165
+ * smaller result; `seatDecision` records how Alyte's agent chose between seat offers. */
166
+ export interface BasketPurchaseDetail {
167
+ lineOutcomes?: BasketLineOutcome[];
168
+ seatDecision?: SeatDecision;
169
+ }
170
+ /** One basket line the buyer asks for. `quantity` is the most wanted; `minQuantity`, `required: false`
171
+ * and `step` say how far it may shrink. `seats` (exact ids) and `seatRequest` are mutually exclusive. */
172
+ export interface BuyerBasketLine {
173
+ tierId: string;
174
+ quantity: number;
175
+ minQuantity?: number;
176
+ required?: boolean;
177
+ step?: number;
178
+ seats?: string[];
179
+ seatRequest?: SeatRequest;
180
+ }
181
+ export interface BasketPurchaseLine {
182
+ lineNo: number;
183
+ tierId: string;
184
+ quantity: number;
185
+ unitPriceMinor: number;
186
+ subtotalMinor: number;
187
+ }
188
+ export type BuyerPurchaseStatus = 'pending' | 'sca_required' | 'settled' | 'refused' | 'cancelled' | 'expired';
189
+ export interface BuyerPurchaseState {
190
+ authenticationRetry?: boolean;
191
+ provider?: 'stripe' | 'adyen';
192
+ purchaseId: string;
193
+ status: BuyerPurchaseStatus;
194
+ chargeMinor?: number;
195
+ currency?: string;
196
+ challenge?: {
197
+ expiresAt: string;
198
+ };
199
+ result?: PaymentResult;
200
+ }
76
201
  export interface BuyerReceipt {
77
202
  intentId: string;
78
203
  status: 'settled' | 'pending' | 'refused';
@@ -126,18 +251,62 @@ export declare function createBuyerClient(opts: BuyerClientOptions): {
126
251
  quantity: number;
127
252
  attemptId: string;
128
253
  }) => Promise<BuyerPurchase>;
254
+ /**
255
+ * Several ticket types (ticket + add-ons) reserved together and paid as ONE charge. All-or-nothing
256
+ * unless a line says how far it may shrink (`minQuantity`, `required: false`, `step`); the result's
257
+ * `lineOutcomes` then lists what each line got. Same attempt rule as buy(): save attemptId first and
258
+ * reuse it after an uncertain response. A retry buys the SAME resolved basket or is refused with
259
+ * `basket_result_unavailable`; a reused attemptId with other lines is refused.
260
+ */
261
+ buyBasket: (input: {
262
+ agentId: string;
263
+ lines: BuyerBasketLine[];
264
+ attemptId: string;
265
+ }) => Promise<BuyerPurchase>;
266
+ /** Recover this purchase; never start a new buy after an uncertain response or a challenge. */
267
+ purchase: (purchaseId: string) => Promise<BuyerPurchaseState>;
268
+ resumePurchase: (purchaseId: string) => Promise<BuyerPurchaseState>;
269
+ cancelPurchase: (purchaseId: string) => Promise<BuyerPurchaseState>;
129
270
  payment: (intentId: string) => Promise<BuyerReceipt>;
271
+ /** Queue one ticket type, or a basket with `lines` (never both). Ask `watchCapabilities()` for `basketLines` first. */
130
272
  watch: (input: {
131
273
  agentId: string;
274
+ expiresInDays?: number;
275
+ } & ({
132
276
  tierId: string;
133
277
  quantity: number;
134
- expiresInDays?: number;
135
- }) => Promise<{
278
+ lines?: never;
279
+ } | {
280
+ lines: BuyerBasketLine[];
281
+ tierId?: never;
282
+ quantity?: never;
283
+ })) => Promise<{
136
284
  watch: BuyerWatch;
137
285
  }>;
138
286
  cancelWatch: (watchId: string) => Promise<{
139
287
  watch: BuyerWatch;
140
288
  }>;
289
+ /** What this deployment enforces. Discovery only — the server still refuses anything unsupported. */
290
+ watchCapabilities: () => Promise<{
291
+ schemaVersion: 1;
292
+ requestKinds: string[];
293
+ conditions: string[]; /** True when watches take basket `lines`. Absent on older servers. */
294
+ basketLines?: boolean;
295
+ queuePolicy: string;
296
+ }>;
297
+ /**
298
+ * Conditional watch on its own strict route. Never falls back to `watch()` (which would drop the
299
+ * condition) and never retries by itself: after an uncertain response, resend the SAME instruction.
300
+ */
301
+ createWatch: (input: WatchInstruction) => Promise<{
302
+ watch: BuyerWatch;
303
+ replayed: boolean;
304
+ }>;
305
+ getWatch: (watchId: string, init?: {
306
+ signal?: AbortSignal;
307
+ }) => Promise<{
308
+ watch: BuyerWatch;
309
+ }>;
141
310
  revokeMandate: (mandateId: string) => Promise<{
142
311
  ok: true;
143
312
  id: string;
@@ -145,6 +314,21 @@ export declare function createBuyerClient(opts: BuyerClientOptions): {
145
314
  }>;
146
315
  };
147
316
  export type BuyerClient = ReturnType<typeof createBuyerClient>;
317
+ export interface ObserveWatchOptions {
318
+ client: Pick<BuyerClient, 'getWatch'>;
319
+ watchId: string;
320
+ signal: AbortSignal;
321
+ onUpdate: (watch: BuyerWatch) => void;
322
+ /** A read failed; `last` is the last snapshot, now stale. Polling continues with backoff unless `stopped`. */
323
+ onError?: (error: unknown, last: BuyerWatch | undefined, stopped: boolean) => void;
324
+ }
325
+ /**
326
+ * Read-only polling of one watch: one request in flight, server-directed interval (bounded),
327
+ * bounded backoff on read failures, older revisions discarded, paused while the page is hidden.
328
+ * Stops on a terminal state, an authorization/not-found refusal, or abort. It never creates,
329
+ * cancels, pays or consents.
330
+ */
331
+ export declare function observeWatch(opts: ObserveWatchOptions): void;
148
332
  export interface ConsentTheme {
149
333
  accent?: string;
150
334
  background?: string;
@@ -167,6 +351,8 @@ export interface ConsentOptions {
167
351
  tierId?: string;
168
352
  quantity?: number;
169
353
  lang?: string;
354
+ /** Accessible title for the hosted iframe (WCAG 4.1.2 / EN 301 549). Defaults to a localized title matching `lang`. */
355
+ title?: string;
170
356
  /** Optional back link. Restricted to this host origin; the callback decides navigation. */
171
357
  returnUrl?: string;
172
358
  onNavigate?: (url: string) => void;
@@ -181,3 +367,25 @@ export declare class AlyteConsentError extends Error {
181
367
  }
182
368
  /** Mount Alyte's isolated consent surface; the full verification credential never leaves it. */
183
369
  export declare function openConsent(opts: ConsentOptions): Promise<ConsentResult>;
370
+ export interface ChallengeStatus {
371
+ purchaseId: string;
372
+ status: BuyerPurchaseStatus;
373
+ }
374
+ export interface ChallengeResult extends ChallengeStatus {
375
+ status: 'settled' | 'refused' | 'cancelled' | 'expired';
376
+ }
377
+ export interface ChallengeOptions extends Omit<ConsentOptions, 'tierId' | 'quantity'> {
378
+ purchaseId: string;
379
+ /** Safe status only. Provider action material never leaves the Alyte frame. */
380
+ onStatus?: (state: ChallengeStatus) => void;
381
+ }
382
+ export declare class AlyteChallengeError extends Error {
383
+ readonly code: string;
384
+ constructor(code: string);
385
+ }
386
+ /**
387
+ * Complete an existing purchase in Alyte's isolated frame. No buy, purchase key,
388
+ * payment details or caller-supplied approval is sent. Aborting closes only the
389
+ * frame; the server purchase remains recoverable until its verified outcome.
390
+ */
391
+ export declare function openChallenge(opts: ChallengeOptions): Promise<ChallengeResult>;
package/dist/browser.js CHANGED
@@ -10,8 +10,8 @@ function baseOrigin(value) {
10
10
  return url.origin;
11
11
  }
12
12
  /** HTTP errors retain the server taxonomy; no request is automatically retried. */
13
- async function request(fetcher, base, path, method, bearer, body) {
14
- const res = await fetcher(base + path, { method, credentials: 'omit', redirect: 'error', cache: 'no-store',
13
+ async function request(fetcher, base, path, method, bearer, body, signal) {
14
+ const res = await fetcher(base + path, { method, credentials: 'omit', redirect: 'error', cache: 'no-store', signal,
15
15
  headers: { ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
16
16
  body: body === undefined ? undefined : JSON.stringify(body),
17
17
  });
@@ -33,7 +33,7 @@ export function createBuyerClient(opts) {
33
33
  const base = baseOrigin(opts.baseUrl), fetcher = opts.fetch ?? globalThis.fetch;
34
34
  if (typeof opts.bearer !== 'string' || !opts.bearer)
35
35
  throw new TypeError('bearer is required');
36
- const call = (method, path, body) => request(fetcher, base, '/v1/buyer' + path, method, opts.bearer, body);
36
+ const call = (method, path, body, signal) => request(fetcher, base, '/v1/buyer' + path, method, opts.bearer, body, signal);
37
37
  return {
38
38
  me: () => call('GET', '/me'),
39
39
  catalog: () => call('GET', '/catalog'),
@@ -47,12 +47,146 @@ export function createBuyerClient(opts) {
47
47
  throw new TypeError('A saved UUID attemptId is required');
48
48
  return call('POST', `/agents/${encodeURIComponent(input.agentId)}/buy`, { tierId: input.tierId, quantity: input.quantity, attemptId: input.attemptId });
49
49
  },
50
+ /**
51
+ * Several ticket types (ticket + add-ons) reserved together and paid as ONE charge. All-or-nothing
52
+ * unless a line says how far it may shrink (`minQuantity`, `required: false`, `step`); the result's
53
+ * `lineOutcomes` then lists what each line got. Same attempt rule as buy(): save attemptId first and
54
+ * reuse it after an uncertain response. A retry buys the SAME resolved basket or is refused with
55
+ * `basket_result_unavailable`; a reused attemptId with other lines is refused.
56
+ */
57
+ buyBasket: (input) => {
58
+ if (typeof input.attemptId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(input.attemptId))
59
+ throw new TypeError('A saved UUID attemptId is required');
60
+ return call('POST', `/agents/${encodeURIComponent(input.agentId)}/buy`, { lines: basketLines(input.lines), attemptId: input.attemptId });
61
+ },
62
+ /** Recover this purchase; never start a new buy after an uncertain response or a challenge. */
63
+ purchase: (purchaseId) => call('GET', `/purchases/${encodeURIComponent(purchaseId)}`),
64
+ resumePurchase: (purchaseId) => call('POST', `/purchases/${encodeURIComponent(purchaseId)}/resume`, {}),
65
+ cancelPurchase: (purchaseId) => call('POST', `/purchases/${encodeURIComponent(purchaseId)}/cancel`, {}),
50
66
  payment: (intentId) => call('GET', `/payments/${encodeURIComponent(intentId)}`),
51
- watch: (input) => call('POST', '/watches', input),
67
+ /** Queue one ticket type, or a basket with `lines` (never both). Ask `watchCapabilities()` for `basketLines` first. */
68
+ watch: (input) => {
69
+ if (input.lines === undefined)
70
+ return call('POST', '/watches', input);
71
+ if ('tierId' in input || 'quantity' in input)
72
+ throw new TypeError('A basket watch takes lines, not tierId or quantity');
73
+ return call('POST', '/watches', { agentId: input.agentId, lines: basketLines(input.lines), ...(input.expiresInDays !== undefined ? { expiresInDays: input.expiresInDays } : {}) });
74
+ },
52
75
  cancelWatch: (watchId) => call('DELETE', `/watches/${encodeURIComponent(watchId)}`),
76
+ /** What this deployment enforces. Discovery only — the server still refuses anything unsupported. */
77
+ watchCapabilities: () => call('GET', '/watch-capabilities'),
78
+ /**
79
+ * Conditional watch on its own strict route. Never falls back to `watch()` (which would drop the
80
+ * condition) and never retries by itself: after an uncertain response, resend the SAME instruction.
81
+ */
82
+ createWatch: (input) => {
83
+ if (typeof input.requestId !== 'string' || !UUID.test(input.requestId))
84
+ throw new TypeError('A saved UUID requestId is required');
85
+ if (input.condition?.kind === 'price_at_or_below' && !Number.isSafeInteger(input.condition.maxChargeMinor))
86
+ throw new TypeError('maxChargeMinor must be an integer in minor units');
87
+ if ('lines' in input.request) {
88
+ if ('tierId' in input.request || 'quantity' in input.request)
89
+ throw new TypeError('A basket watch takes lines, not tierId or quantity');
90
+ return call('POST', '/watch-requests', { ...input, request: { kind: input.request.kind, lines: basketLines(input.request.lines) } });
91
+ }
92
+ return call('POST', '/watch-requests', input);
93
+ },
94
+ getWatch: (watchId, init) => call('GET', `/watches/${encodeURIComponent(watchId)}`, undefined, init?.signal),
53
95
  revokeMandate: (mandateId) => call('DELETE', `/mandates/${encodeURIComponent(mandateId)}`),
54
96
  };
55
97
  }
98
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
99
+ const MIN_POLL_MS = 2000, MAX_POLL_MS = 60_000;
100
+ /**
101
+ * Read-only polling of one watch: one request in flight, server-directed interval (bounded),
102
+ * bounded backoff on read failures, older revisions discarded, paused while the page is hidden.
103
+ * Stops on a terminal state, an authorization/not-found refusal, or abort. It never creates,
104
+ * cancels, pays or consents.
105
+ */
106
+ export function observeWatch(opts) {
107
+ let last, failures = 0, timer, inFlight = false;
108
+ const doc = globalThis.document;
109
+ const stop = () => { if (timer)
110
+ clearTimeout(timer); doc?.removeEventListener('visibilitychange', onVisible); };
111
+ const schedule = (ms) => { if (timer)
112
+ clearTimeout(timer); if (!opts.signal.aborted)
113
+ timer = setTimeout(tick, Math.min(MAX_POLL_MS, Math.max(MIN_POLL_MS, ms))); };
114
+ const onVisible = () => {
115
+ if (doc?.visibilityState !== 'visible' || opts.signal.aborted || inFlight)
116
+ return; // one request in flight, ever
117
+ if (timer)
118
+ clearTimeout(timer);
119
+ timer = undefined;
120
+ void tick();
121
+ };
122
+ async function tick() {
123
+ timer = undefined;
124
+ if (opts.signal.aborted)
125
+ return stop();
126
+ if (inFlight)
127
+ return;
128
+ if (doc?.visibilityState === 'hidden')
129
+ return; // resumes on visibilitychange
130
+ inFlight = true;
131
+ try {
132
+ const { watch } = await opts.client.getWatch(opts.watchId, { signal: opts.signal });
133
+ failures = 0;
134
+ const older = last?.queue && watch.queue && BigInt(watch.queue.revision) < BigInt(last.queue.revision);
135
+ if (!older) {
136
+ last = watch;
137
+ opts.onUpdate(watch);
138
+ }
139
+ const current = last;
140
+ const finished = current.queue
141
+ ? current.queue.place.kind === 'not_waiting' && current.queue.place.reason === 'terminal'
142
+ : ['fired', 'failed', 'cancelled', 'expired'].includes(current.status); // older server: no snapshot
143
+ if (finished)
144
+ return stop();
145
+ schedule(current.queue?.refreshAfterMs ?? 5000);
146
+ }
147
+ catch (error) {
148
+ if (opts.signal.aborted)
149
+ return stop();
150
+ const status = error instanceof AlyteApiError ? error.status : 0;
151
+ const fatal = status === 401 || status === 403 || status === 404;
152
+ opts.onError?.(error, last, fatal);
153
+ if (fatal)
154
+ return stop();
155
+ failures++;
156
+ schedule(MIN_POLL_MS * 2 ** Math.min(failures, 5));
157
+ }
158
+ finally {
159
+ inFlight = false;
160
+ }
161
+ }
162
+ opts.signal.addEventListener('abort', stop, { once: true });
163
+ doc?.addEventListener('visibilitychange', onVisible);
164
+ void tick();
165
+ }
166
+ const CONSENT_IFRAME_TITLES = {
167
+ en: 'Alyte consent',
168
+ de: 'Alyte-Einwilligung',
169
+ es: 'Consentimiento de Alyte',
170
+ fr: 'Consentement Alyte',
171
+ hu: 'Alyte jóváhagyás',
172
+ pt: 'Consentimento Alyte',
173
+ };
174
+ const CHALLENGE_IFRAME_TITLES = {
175
+ en: 'Alyte bank authentication',
176
+ de: 'Alyte-Bankauthentifizierung',
177
+ es: 'Autenticación bancaria de Alyte',
178
+ fr: 'Authentification bancaire Alyte',
179
+ hu: 'Alyte banki hitelesítés',
180
+ pt: 'Autenticação bancária Alyte',
181
+ };
182
+ function iframeTitleFor(kind, lang, override) {
183
+ const custom = override?.trim();
184
+ if (custom)
185
+ return custom;
186
+ const primary = (lang || 'en').toLowerCase().split('-')[0] || 'en';
187
+ const map = kind === 'challenge' ? CHALLENGE_IFRAME_TITLES : CONSENT_IFRAME_TITLES;
188
+ return map[primary] ?? map.en;
189
+ }
56
190
  export class AlyteConsentError extends Error {
57
191
  code;
58
192
  constructor(code) {
@@ -96,7 +230,7 @@ export function openConsent(opts) {
96
230
  }
97
231
  return new Promise((resolve, reject) => {
98
232
  const iframe = doc.createElement('iframe');
99
- iframe.title = 'Alyte consent';
233
+ iframe.title = iframeTitleFor('consent', opts.lang, opts.title);
100
234
  iframe.src = url.href;
101
235
  iframe.referrerPolicy = 'no-referrer';
102
236
  iframe.style.width = '100%';
@@ -157,3 +291,134 @@ export function openConsent(opts) {
157
291
  opts.container.append(iframe);
158
292
  });
159
293
  }
294
+ export class AlyteChallengeError extends Error {
295
+ code;
296
+ constructor(code) {
297
+ super(`Alyte challenge: ${code}`);
298
+ this.code = code;
299
+ this.name = 'AlyteChallengeError';
300
+ }
301
+ }
302
+ /**
303
+ * Complete an existing purchase in Alyte's isolated frame. No buy, purchase key,
304
+ * payment details or caller-supplied approval is sent. Aborting closes only the
305
+ * frame; the server purchase remains recoverable until its verified outcome.
306
+ */
307
+ export function openChallenge(opts) {
308
+ const base = baseOrigin(opts.baseUrl);
309
+ if (!opts.merchantId || !opts.bearer)
310
+ throw new TypeError('merchantId and bearer are required');
311
+ if (typeof opts.purchaseId !== 'string' || !opts.purchaseId || opts.purchaseId.length > 512)
312
+ throw new TypeError('purchaseId is required');
313
+ const doc = opts.container.ownerDocument, host = doc.defaultView;
314
+ if (!host)
315
+ throw new TypeError('container must belong to a browser document');
316
+ if (opts.readyTimeoutMs !== undefined && (!Number.isFinite(opts.readyTimeoutMs) || opts.readyTimeoutMs <= 0))
317
+ throw new TypeError('readyTimeoutMs must be positive');
318
+ const url = new URL(`/shop/${encodeURIComponent(opts.merchantId)}/authorize`, base);
319
+ url.searchParams.set('view', 'challenge');
320
+ url.searchParams.set('embed', '1');
321
+ url.searchParams.set('purchase', opts.purchaseId);
322
+ if (opts.lang)
323
+ url.searchParams.set('lang', opts.lang);
324
+ if (opts.returnUrl) {
325
+ const back = new URL(opts.returnUrl);
326
+ if (back.origin !== host.location.origin)
327
+ throw new TypeError('returnUrl must belong to the host origin');
328
+ url.searchParams.set('return', back.href);
329
+ }
330
+ for (const key of ['accent', 'background', 'surface', 'text', 'font', 'radius', 'scheme']) {
331
+ const value = opts.theme?.[key];
332
+ if ((typeof value === 'string' || typeof value === 'number') && String(value).length <= 64)
333
+ url.searchParams.set(key, String(value));
334
+ }
335
+ const statuses = ['pending', 'sca_required', 'settled', 'refused', 'cancelled', 'expired'];
336
+ return new Promise((resolve, reject) => {
337
+ const iframe = doc.createElement('iframe');
338
+ iframe.title = iframeTitleFor('challenge', opts.lang, opts.title);
339
+ iframe.src = url.href;
340
+ iframe.referrerPolicy = 'no-referrer';
341
+ iframe.style.width = '100%';
342
+ iframe.style.height = '640px';
343
+ iframe.style.border = '0';
344
+ let done = false, ready = false;
345
+ let timer;
346
+ const cleanup = () => { clearTimeout(timer); host.removeEventListener('message', receive); opts.signal?.removeEventListener('abort', abort); iframe.remove(); };
347
+ const fail = (code) => { if (!done) {
348
+ done = true;
349
+ cleanup();
350
+ reject(new AlyteChallengeError(code));
351
+ } };
352
+ const abort = () => fail('challenge_closed');
353
+ const receive = (event) => {
354
+ if (done || event.origin !== base || event.source !== iframe.contentWindow)
355
+ return;
356
+ const data = event.data;
357
+ if (!data || data.type !== 'alyte:challenge' || data.merchantId !== opts.merchantId || data.purchaseId !== opts.purchaseId)
358
+ return;
359
+ if (data.event === 'ready') {
360
+ ready = true;
361
+ clearTimeout(timer);
362
+ iframe.contentWindow?.postMessage({ type: 'alyte:challenge', event: 'bootstrap', purchaseId: opts.purchaseId, bearer: opts.bearer }, base);
363
+ }
364
+ else if (data.event === 'status' && ready && statuses.includes(data.status)) {
365
+ // Copy only this allowlist. Neither unexpected fields nor result payloads
366
+ // from a future frame version become a merchant callback or receipt.
367
+ const state = { purchaseId: opts.purchaseId, status: data.status };
368
+ if (state.status !== 'pending' && state.status !== 'sca_required') {
369
+ done = true;
370
+ cleanup();
371
+ resolve(state);
372
+ }
373
+ opts.onStatus?.(state);
374
+ }
375
+ else if (data.event === 'error') {
376
+ fail(data.code === 'unauthorized' ? 'unauthorized' : 'challenge_unavailable');
377
+ }
378
+ else if (data.event === 'resize' && Number.isFinite(data.height)) {
379
+ iframe.style.height = `${Math.max(240, Math.min(1200, Math.ceil(data.height)))}px`;
380
+ }
381
+ else if (data.event === 'navigate' && typeof data.url === 'string') {
382
+ try {
383
+ const back = new URL(data.url);
384
+ if (back.origin === host.location.origin)
385
+ opts.onNavigate?.(back.href);
386
+ }
387
+ catch { /* Ignore malformed navigation messages. */ }
388
+ }
389
+ };
390
+ if (opts.signal?.aborted) {
391
+ abort();
392
+ return;
393
+ }
394
+ host.addEventListener('message', receive);
395
+ opts.signal?.addEventListener('abort', abort, { once: true });
396
+ timer = setTimeout(() => fail('challenge_unavailable'), opts.readyTimeoutMs ?? 15_000);
397
+ iframe.addEventListener('error', () => fail('challenge_unavailable'), { once: true });
398
+ opts.container.append(iframe);
399
+ });
400
+ }
401
+ const BASKET_LINE_KEYS = ['tierId', 'quantity', 'minQuantity', 'required', 'step', 'seats', 'seatRequest'];
402
+ /** Refused, never stripped: a mistyped field would otherwise be bought without the limit it meant to set. */
403
+ function basketLines(lines) {
404
+ if (!Array.isArray(lines) || !lines.length)
405
+ throw new TypeError('A basket needs at least one line');
406
+ return lines.map((line) => {
407
+ const extra = Object.keys(line).filter((k) => !BASKET_LINE_KEYS.includes(k));
408
+ if (extra.length)
409
+ throw new TypeError(`A basket line takes tierId, quantity, minQuantity, required, step, seats and seatRequest (got ${extra.join(', ')})`);
410
+ if (line.seats !== undefined && line.seatRequest !== undefined)
411
+ throw new TypeError('A basket line takes seats or seatRequest, not both');
412
+ for (const k of ['quantity', 'minQuantity', 'step']) {
413
+ if (line[k] !== undefined && !(Number.isSafeInteger(line[k]) && line[k] > 0))
414
+ throw new TypeError(`${k} must be a positive integer`);
415
+ }
416
+ if (line.minQuantity !== undefined && line.minQuantity > line.quantity)
417
+ throw new TypeError('minQuantity cannot exceed quantity');
418
+ const out = { tierId: line.tierId, quantity: line.quantity };
419
+ for (const k of ['minQuantity', 'required', 'step', 'seats', 'seatRequest'])
420
+ if (line[k] !== undefined)
421
+ out[k] = line[k];
422
+ return out;
423
+ });
424
+ }
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export { AlyteMerchant } from './merchant.js';
2
2
  export { AlyteAgent } from './agent.js';
3
3
  export { AlyteApiError, type ClientOptions } from './http.js';
4
4
  export { verifyWebhookSignature } from './webhookVerify.js';
5
- export { handleWebhook, createWebhookHandler, type AlyteEventEnvelope, type PaymentSettled, type WatchFailed, type WebhookTest, type PurchaseHandlers, type OnPurchaseOptions, type WebhookResult, } from './onPurchase.js';
5
+ export { handleWebhook, createWebhookHandler, type AlyteEventEnvelope, type PaymentSettled, type WatchFailed, type WatchActionRequired, type WebhookTest, type PurchaseHandlers, type OnPurchaseOptions, type WebhookResult, } from './onPurchase.js';
6
6
  export type * from './types.js';
7
+ export type * from './baskets.js';
7
8
  export type { AccessAudience, AccessDraftInput, AccessRule, AccessPreview, AccessCommitInput, MembershipProgram, MembershipEvidence } from './access.js';
@@ -5,6 +5,8 @@ export interface InventoryPool {
5
5
  tenantId: string;
6
6
  merchantId: string;
7
7
  eventId?: string;
8
+ /** The integrator's stable id (per tenant), when the pool was created with one. */
9
+ externalRef?: string;
8
10
  title: string;
9
11
  capacity: number;
10
12
  availableCount: number;