@alytegen/sdk 0.6.0 → 0.8.0
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/BROWSER.md +85 -4
- package/QUICKSTART.md +13 -0
- package/README.md +161 -3
- package/dist/access.d.ts +106 -0
- package/dist/access.js +27 -0
- package/dist/agent.d.ts +26 -2
- package/dist/agent.js +45 -3
- package/dist/baskets.d.ts +86 -0
- package/dist/baskets.js +13 -0
- package/dist/browser.d.ts +155 -3
- package/dist/browser.js +196 -3
- package/dist/index.d.ts +2 -1
- package/dist/inventoryTypes.d.ts +2 -0
- package/dist/merchant.d.ts +33 -1
- package/dist/merchant.js +30 -0
- package/dist/onPurchase.d.ts +16 -0
- package/dist/onPurchase.js +3 -0
- package/dist/types.d.ts +88 -0
- package/examples/agent-basket.ts +28 -0
- package/package.json +1 -1
package/dist/baskets.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** REST deliberately sends completed refusals and uncertain outcomes as HTTP 402.
|
|
2
|
+
* Only recognize that documented union; ordinary error envelopes still throw. */
|
|
3
|
+
export function isReservationRefusal(value) {
|
|
4
|
+
if (!value || typeof value !== 'object')
|
|
5
|
+
return false;
|
|
6
|
+
const body = value;
|
|
7
|
+
if (body.status === 'sca_failed')
|
|
8
|
+
return body.reservationStatus === 'released';
|
|
9
|
+
if (body.status !== 'settled' || typeof body.reservationStatus !== 'string' || !body.result || typeof body.result !== 'object')
|
|
10
|
+
return false;
|
|
11
|
+
const result = body.result;
|
|
12
|
+
return typeof result.intentId === 'string' && (result.status === 'declined' || result.status === 'error');
|
|
13
|
+
}
|
package/dist/browser.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DiscoveredEvent, Scheme } from './types.js';
|
|
1
|
+
import type { DiscoveredEvent, PaymentResult, Scheme } from './types.js';
|
|
2
2
|
export { AlyteApiError } from './http.js';
|
|
3
3
|
export interface BuyerConnection {
|
|
4
4
|
bearer: string;
|
|
@@ -54,11 +54,78 @@ export interface BuyerWatch {
|
|
|
54
54
|
merchantId: string;
|
|
55
55
|
tierId: string;
|
|
56
56
|
quantity: number;
|
|
57
|
-
status: 'queued' | 'paused' | 'firing' | 'fired' | 'failed' | 'cancelled' | 'expired';
|
|
58
|
-
result?:
|
|
57
|
+
status: 'queued' | 'paused' | 'firing' | 'awaiting_sca' | 'fired' | 'failed' | 'cancelled' | 'expired';
|
|
58
|
+
result?: BuyerWatchResult;
|
|
59
59
|
expiresAt?: string;
|
|
60
60
|
createdAt: string;
|
|
61
61
|
firedAt?: string;
|
|
62
|
+
/** Absent on legacy watches and older servers: treat as availability. */
|
|
63
|
+
conditionSpec?: WatchCondition;
|
|
64
|
+
/** Server-computed place in line. Absent on older servers = unavailable, never position zero. */
|
|
65
|
+
queue?: WatchQueueSnapshot;
|
|
66
|
+
}
|
|
67
|
+
/** A pending purchase keeps its original identity; openChallenge never buys or requeues it. */
|
|
68
|
+
export type BuyerWatchResult = Record<string, unknown> & {
|
|
69
|
+
status?: string;
|
|
70
|
+
purchaseId?: string;
|
|
71
|
+
challenge?: {
|
|
72
|
+
expiresAt: string;
|
|
73
|
+
};
|
|
74
|
+
code?: string;
|
|
75
|
+
};
|
|
76
|
+
export type WatchCondition = {
|
|
77
|
+
kind: 'available';
|
|
78
|
+
} | {
|
|
79
|
+
kind: 'price_at_or_below';
|
|
80
|
+
maxChargeMinor: number;
|
|
81
|
+
currency: 'EUR' | 'GBP' | 'USD';
|
|
82
|
+
};
|
|
83
|
+
/** Unknown future values must render as a generic waiting state. */
|
|
84
|
+
export type WatchWaitingReason = 'access_window' | 'price_target' | 'stock' | 'whole_party' | (string & {});
|
|
85
|
+
export type QueuePlace = {
|
|
86
|
+
kind: 'assigned' | 'provisional';
|
|
87
|
+
position: number;
|
|
88
|
+
requestsAhead: number;
|
|
89
|
+
} | {
|
|
90
|
+
kind: 'unassigned';
|
|
91
|
+
reason: 'condition_not_met' | 'paused' | (string & {});
|
|
92
|
+
} | {
|
|
93
|
+
kind: 'not_waiting';
|
|
94
|
+
reason: 'processing' | 'reconciling' | 'terminal' | (string & {});
|
|
95
|
+
} | {
|
|
96
|
+
kind: 'unavailable';
|
|
97
|
+
};
|
|
98
|
+
export interface WatchQueueSnapshot {
|
|
99
|
+
schemaVersion: 1;
|
|
100
|
+
/** Decimal monotonic sequence — compare with BigInt, never Number. */
|
|
101
|
+
revision: string;
|
|
102
|
+
observedAt: string;
|
|
103
|
+
refreshAfterMs: number;
|
|
104
|
+
/** `phaseId` 'general' or 'rule:<id>' (an access window, labelled by the merchant); a place counts within its phase. */
|
|
105
|
+
queue: {
|
|
106
|
+
id: string;
|
|
107
|
+
label: string;
|
|
108
|
+
phaseId?: string;
|
|
109
|
+
phaseLabel?: string;
|
|
110
|
+
};
|
|
111
|
+
policyVersion: string;
|
|
112
|
+
place: QueuePlace;
|
|
113
|
+
waitingReason?: WatchWaitingReason;
|
|
114
|
+
nextEligibleAt?: string;
|
|
115
|
+
observedChargeMinor?: number;
|
|
116
|
+
}
|
|
117
|
+
export interface WatchInstruction {
|
|
118
|
+
/** Save the whole instruction (not the bearer) BEFORE sending; reuse this UUID after an uncertain response. */
|
|
119
|
+
requestId: string;
|
|
120
|
+
agentId: string;
|
|
121
|
+
request: {
|
|
122
|
+
kind: 'ticketing';
|
|
123
|
+
tierId: string;
|
|
124
|
+
quantity: number;
|
|
125
|
+
};
|
|
126
|
+
condition: WatchCondition;
|
|
127
|
+
/** ISO-8601 with an explicit offset, e.g. 2026-11-01T12:00:00Z. */
|
|
128
|
+
expiresAt: string;
|
|
62
129
|
}
|
|
63
130
|
export type BuyerPurchase = {
|
|
64
131
|
status: 'settled' | 'pending';
|
|
@@ -69,10 +136,34 @@ export type BuyerPurchase = {
|
|
|
69
136
|
agentName?: string;
|
|
70
137
|
} | {
|
|
71
138
|
status: 'sca_required';
|
|
139
|
+
purchaseId: string;
|
|
140
|
+
challenge: {
|
|
141
|
+
expiresAt: string;
|
|
142
|
+
};
|
|
143
|
+
} | {
|
|
144
|
+
status: 'sca_required';
|
|
145
|
+
purchaseId?: never;
|
|
146
|
+
challenge?: never;
|
|
147
|
+
} | {
|
|
148
|
+
status: 'pending';
|
|
149
|
+
purchaseId: string;
|
|
72
150
|
} | {
|
|
73
151
|
status: 'refused' | 'error';
|
|
74
152
|
outcome: unknown;
|
|
75
153
|
};
|
|
154
|
+
export type BuyerPurchaseStatus = 'pending' | 'sca_required' | 'settled' | 'refused' | 'cancelled' | 'expired';
|
|
155
|
+
export interface BuyerPurchaseState {
|
|
156
|
+
authenticationRetry?: boolean;
|
|
157
|
+
provider?: 'stripe' | 'adyen';
|
|
158
|
+
purchaseId: string;
|
|
159
|
+
status: BuyerPurchaseStatus;
|
|
160
|
+
chargeMinor?: number;
|
|
161
|
+
currency?: string;
|
|
162
|
+
challenge?: {
|
|
163
|
+
expiresAt: string;
|
|
164
|
+
};
|
|
165
|
+
result?: PaymentResult;
|
|
166
|
+
}
|
|
76
167
|
export interface BuyerReceipt {
|
|
77
168
|
intentId: string;
|
|
78
169
|
status: 'settled' | 'pending' | 'refused';
|
|
@@ -126,6 +217,10 @@ export declare function createBuyerClient(opts: BuyerClientOptions): {
|
|
|
126
217
|
quantity: number;
|
|
127
218
|
attemptId: string;
|
|
128
219
|
}) => Promise<BuyerPurchase>;
|
|
220
|
+
/** Recover this purchase; never start a new buy after an uncertain response or a challenge. */
|
|
221
|
+
purchase: (purchaseId: string) => Promise<BuyerPurchaseState>;
|
|
222
|
+
resumePurchase: (purchaseId: string) => Promise<BuyerPurchaseState>;
|
|
223
|
+
cancelPurchase: (purchaseId: string) => Promise<BuyerPurchaseState>;
|
|
129
224
|
payment: (intentId: string) => Promise<BuyerReceipt>;
|
|
130
225
|
watch: (input: {
|
|
131
226
|
agentId: string;
|
|
@@ -138,6 +233,26 @@ export declare function createBuyerClient(opts: BuyerClientOptions): {
|
|
|
138
233
|
cancelWatch: (watchId: string) => Promise<{
|
|
139
234
|
watch: BuyerWatch;
|
|
140
235
|
}>;
|
|
236
|
+
/** What this deployment enforces. Discovery only — the server still refuses anything unsupported. */
|
|
237
|
+
watchCapabilities: () => Promise<{
|
|
238
|
+
schemaVersion: 1;
|
|
239
|
+
requestKinds: string[];
|
|
240
|
+
conditions: string[];
|
|
241
|
+
queuePolicy: string;
|
|
242
|
+
}>;
|
|
243
|
+
/**
|
|
244
|
+
* Conditional watch on its own strict route. Never falls back to `watch()` (which would drop the
|
|
245
|
+
* condition) and never retries by itself: after an uncertain response, resend the SAME instruction.
|
|
246
|
+
*/
|
|
247
|
+
createWatch: (input: WatchInstruction) => Promise<{
|
|
248
|
+
watch: BuyerWatch;
|
|
249
|
+
replayed: boolean;
|
|
250
|
+
}>;
|
|
251
|
+
getWatch: (watchId: string, init?: {
|
|
252
|
+
signal?: AbortSignal;
|
|
253
|
+
}) => Promise<{
|
|
254
|
+
watch: BuyerWatch;
|
|
255
|
+
}>;
|
|
141
256
|
revokeMandate: (mandateId: string) => Promise<{
|
|
142
257
|
ok: true;
|
|
143
258
|
id: string;
|
|
@@ -145,6 +260,21 @@ export declare function createBuyerClient(opts: BuyerClientOptions): {
|
|
|
145
260
|
}>;
|
|
146
261
|
};
|
|
147
262
|
export type BuyerClient = ReturnType<typeof createBuyerClient>;
|
|
263
|
+
export interface ObserveWatchOptions {
|
|
264
|
+
client: Pick<BuyerClient, 'getWatch'>;
|
|
265
|
+
watchId: string;
|
|
266
|
+
signal: AbortSignal;
|
|
267
|
+
onUpdate: (watch: BuyerWatch) => void;
|
|
268
|
+
/** A read failed; `last` is the last snapshot, now stale. Polling continues with backoff unless `stopped`. */
|
|
269
|
+
onError?: (error: unknown, last: BuyerWatch | undefined, stopped: boolean) => void;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Read-only polling of one watch: one request in flight, server-directed interval (bounded),
|
|
273
|
+
* bounded backoff on read failures, older revisions discarded, paused while the page is hidden.
|
|
274
|
+
* Stops on a terminal state, an authorization/not-found refusal, or abort. It never creates,
|
|
275
|
+
* cancels, pays or consents.
|
|
276
|
+
*/
|
|
277
|
+
export declare function observeWatch(opts: ObserveWatchOptions): void;
|
|
148
278
|
export interface ConsentTheme {
|
|
149
279
|
accent?: string;
|
|
150
280
|
background?: string;
|
|
@@ -181,3 +311,25 @@ export declare class AlyteConsentError extends Error {
|
|
|
181
311
|
}
|
|
182
312
|
/** Mount Alyte's isolated consent surface; the full verification credential never leaves it. */
|
|
183
313
|
export declare function openConsent(opts: ConsentOptions): Promise<ConsentResult>;
|
|
314
|
+
export interface ChallengeStatus {
|
|
315
|
+
purchaseId: string;
|
|
316
|
+
status: BuyerPurchaseStatus;
|
|
317
|
+
}
|
|
318
|
+
export interface ChallengeResult extends ChallengeStatus {
|
|
319
|
+
status: 'settled' | 'refused' | 'cancelled' | 'expired';
|
|
320
|
+
}
|
|
321
|
+
export interface ChallengeOptions extends Omit<ConsentOptions, 'tierId' | 'quantity'> {
|
|
322
|
+
purchaseId: string;
|
|
323
|
+
/** Safe status only. Provider action material never leaves the Alyte frame. */
|
|
324
|
+
onStatus?: (state: ChallengeStatus) => void;
|
|
325
|
+
}
|
|
326
|
+
export declare class AlyteChallengeError extends Error {
|
|
327
|
+
readonly code: string;
|
|
328
|
+
constructor(code: string);
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Complete an existing purchase in Alyte's isolated frame. No buy, purchase key,
|
|
332
|
+
* payment details or caller-supplied approval is sent. Aborting closes only the
|
|
333
|
+
* frame; the server purchase remains recoverable until its verified outcome.
|
|
334
|
+
*/
|
|
335
|
+
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,98 @@ 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
|
+
/** Recover this purchase; never start a new buy after an uncertain response or a challenge. */
|
|
51
|
+
purchase: (purchaseId) => call('GET', `/purchases/${encodeURIComponent(purchaseId)}`),
|
|
52
|
+
resumePurchase: (purchaseId) => call('POST', `/purchases/${encodeURIComponent(purchaseId)}/resume`, {}),
|
|
53
|
+
cancelPurchase: (purchaseId) => call('POST', `/purchases/${encodeURIComponent(purchaseId)}/cancel`, {}),
|
|
50
54
|
payment: (intentId) => call('GET', `/payments/${encodeURIComponent(intentId)}`),
|
|
51
55
|
watch: (input) => call('POST', '/watches', input),
|
|
52
56
|
cancelWatch: (watchId) => call('DELETE', `/watches/${encodeURIComponent(watchId)}`),
|
|
57
|
+
/** What this deployment enforces. Discovery only — the server still refuses anything unsupported. */
|
|
58
|
+
watchCapabilities: () => call('GET', '/watch-capabilities'),
|
|
59
|
+
/**
|
|
60
|
+
* Conditional watch on its own strict route. Never falls back to `watch()` (which would drop the
|
|
61
|
+
* condition) and never retries by itself: after an uncertain response, resend the SAME instruction.
|
|
62
|
+
*/
|
|
63
|
+
createWatch: (input) => {
|
|
64
|
+
if (typeof input.requestId !== 'string' || !UUID.test(input.requestId))
|
|
65
|
+
throw new TypeError('A saved UUID requestId is required');
|
|
66
|
+
if (input.condition?.kind === 'price_at_or_below' && !Number.isSafeInteger(input.condition.maxChargeMinor))
|
|
67
|
+
throw new TypeError('maxChargeMinor must be an integer in minor units');
|
|
68
|
+
return call('POST', '/watch-requests', input);
|
|
69
|
+
},
|
|
70
|
+
getWatch: (watchId, init) => call('GET', `/watches/${encodeURIComponent(watchId)}`, undefined, init?.signal),
|
|
53
71
|
revokeMandate: (mandateId) => call('DELETE', `/mandates/${encodeURIComponent(mandateId)}`),
|
|
54
72
|
};
|
|
55
73
|
}
|
|
74
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
75
|
+
const MIN_POLL_MS = 2000, MAX_POLL_MS = 60_000;
|
|
76
|
+
/**
|
|
77
|
+
* Read-only polling of one watch: one request in flight, server-directed interval (bounded),
|
|
78
|
+
* bounded backoff on read failures, older revisions discarded, paused while the page is hidden.
|
|
79
|
+
* Stops on a terminal state, an authorization/not-found refusal, or abort. It never creates,
|
|
80
|
+
* cancels, pays or consents.
|
|
81
|
+
*/
|
|
82
|
+
export function observeWatch(opts) {
|
|
83
|
+
let last, failures = 0, timer, inFlight = false;
|
|
84
|
+
const doc = globalThis.document;
|
|
85
|
+
const stop = () => { if (timer)
|
|
86
|
+
clearTimeout(timer); doc?.removeEventListener('visibilitychange', onVisible); };
|
|
87
|
+
const schedule = (ms) => { if (timer)
|
|
88
|
+
clearTimeout(timer); if (!opts.signal.aborted)
|
|
89
|
+
timer = setTimeout(tick, Math.min(MAX_POLL_MS, Math.max(MIN_POLL_MS, ms))); };
|
|
90
|
+
const onVisible = () => {
|
|
91
|
+
if (doc?.visibilityState !== 'visible' || opts.signal.aborted || inFlight)
|
|
92
|
+
return; // one request in flight, ever
|
|
93
|
+
if (timer)
|
|
94
|
+
clearTimeout(timer);
|
|
95
|
+
timer = undefined;
|
|
96
|
+
void tick();
|
|
97
|
+
};
|
|
98
|
+
async function tick() {
|
|
99
|
+
timer = undefined;
|
|
100
|
+
if (opts.signal.aborted)
|
|
101
|
+
return stop();
|
|
102
|
+
if (inFlight)
|
|
103
|
+
return;
|
|
104
|
+
if (doc?.visibilityState === 'hidden')
|
|
105
|
+
return; // resumes on visibilitychange
|
|
106
|
+
inFlight = true;
|
|
107
|
+
try {
|
|
108
|
+
const { watch } = await opts.client.getWatch(opts.watchId, { signal: opts.signal });
|
|
109
|
+
failures = 0;
|
|
110
|
+
const older = last?.queue && watch.queue && BigInt(watch.queue.revision) < BigInt(last.queue.revision);
|
|
111
|
+
if (!older) {
|
|
112
|
+
last = watch;
|
|
113
|
+
opts.onUpdate(watch);
|
|
114
|
+
}
|
|
115
|
+
const current = last;
|
|
116
|
+
const finished = current.queue
|
|
117
|
+
? current.queue.place.kind === 'not_waiting' && current.queue.place.reason === 'terminal'
|
|
118
|
+
: ['fired', 'failed', 'cancelled', 'expired'].includes(current.status); // older server: no snapshot
|
|
119
|
+
if (finished)
|
|
120
|
+
return stop();
|
|
121
|
+
schedule(current.queue?.refreshAfterMs ?? 5000);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (opts.signal.aborted)
|
|
125
|
+
return stop();
|
|
126
|
+
const status = error instanceof AlyteApiError ? error.status : 0;
|
|
127
|
+
const fatal = status === 401 || status === 403 || status === 404;
|
|
128
|
+
opts.onError?.(error, last, fatal);
|
|
129
|
+
if (fatal)
|
|
130
|
+
return stop();
|
|
131
|
+
failures++;
|
|
132
|
+
schedule(MIN_POLL_MS * 2 ** Math.min(failures, 5));
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
inFlight = false;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
opts.signal.addEventListener('abort', stop, { once: true });
|
|
139
|
+
doc?.addEventListener('visibilitychange', onVisible);
|
|
140
|
+
void tick();
|
|
141
|
+
}
|
|
56
142
|
export class AlyteConsentError extends Error {
|
|
57
143
|
code;
|
|
58
144
|
constructor(code) {
|
|
@@ -157,3 +243,110 @@ export function openConsent(opts) {
|
|
|
157
243
|
opts.container.append(iframe);
|
|
158
244
|
});
|
|
159
245
|
}
|
|
246
|
+
export class AlyteChallengeError extends Error {
|
|
247
|
+
code;
|
|
248
|
+
constructor(code) {
|
|
249
|
+
super(`Alyte challenge: ${code}`);
|
|
250
|
+
this.code = code;
|
|
251
|
+
this.name = 'AlyteChallengeError';
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Complete an existing purchase in Alyte's isolated frame. No buy, purchase key,
|
|
256
|
+
* payment details or caller-supplied approval is sent. Aborting closes only the
|
|
257
|
+
* frame; the server purchase remains recoverable until its verified outcome.
|
|
258
|
+
*/
|
|
259
|
+
export function openChallenge(opts) {
|
|
260
|
+
const base = baseOrigin(opts.baseUrl);
|
|
261
|
+
if (!opts.merchantId || !opts.bearer)
|
|
262
|
+
throw new TypeError('merchantId and bearer are required');
|
|
263
|
+
if (typeof opts.purchaseId !== 'string' || !opts.purchaseId || opts.purchaseId.length > 512)
|
|
264
|
+
throw new TypeError('purchaseId is required');
|
|
265
|
+
const doc = opts.container.ownerDocument, host = doc.defaultView;
|
|
266
|
+
if (!host)
|
|
267
|
+
throw new TypeError('container must belong to a browser document');
|
|
268
|
+
if (opts.readyTimeoutMs !== undefined && (!Number.isFinite(opts.readyTimeoutMs) || opts.readyTimeoutMs <= 0))
|
|
269
|
+
throw new TypeError('readyTimeoutMs must be positive');
|
|
270
|
+
const url = new URL(`/shop/${encodeURIComponent(opts.merchantId)}/authorize`, base);
|
|
271
|
+
url.searchParams.set('view', 'challenge');
|
|
272
|
+
url.searchParams.set('embed', '1');
|
|
273
|
+
url.searchParams.set('purchase', opts.purchaseId);
|
|
274
|
+
if (opts.lang)
|
|
275
|
+
url.searchParams.set('lang', opts.lang);
|
|
276
|
+
if (opts.returnUrl) {
|
|
277
|
+
const back = new URL(opts.returnUrl);
|
|
278
|
+
if (back.origin !== host.location.origin)
|
|
279
|
+
throw new TypeError('returnUrl must belong to the host origin');
|
|
280
|
+
url.searchParams.set('return', back.href);
|
|
281
|
+
}
|
|
282
|
+
for (const key of ['accent', 'background', 'surface', 'text', 'font', 'radius', 'scheme']) {
|
|
283
|
+
const value = opts.theme?.[key];
|
|
284
|
+
if ((typeof value === 'string' || typeof value === 'number') && String(value).length <= 64)
|
|
285
|
+
url.searchParams.set(key, String(value));
|
|
286
|
+
}
|
|
287
|
+
const statuses = ['pending', 'sca_required', 'settled', 'refused', 'cancelled', 'expired'];
|
|
288
|
+
return new Promise((resolve, reject) => {
|
|
289
|
+
const iframe = doc.createElement('iframe');
|
|
290
|
+
iframe.title = 'Alyte bank authentication';
|
|
291
|
+
iframe.src = url.href;
|
|
292
|
+
iframe.referrerPolicy = 'no-referrer';
|
|
293
|
+
iframe.style.width = '100%';
|
|
294
|
+
iframe.style.height = '640px';
|
|
295
|
+
iframe.style.border = '0';
|
|
296
|
+
let done = false, ready = false;
|
|
297
|
+
let timer;
|
|
298
|
+
const cleanup = () => { clearTimeout(timer); host.removeEventListener('message', receive); opts.signal?.removeEventListener('abort', abort); iframe.remove(); };
|
|
299
|
+
const fail = (code) => { if (!done) {
|
|
300
|
+
done = true;
|
|
301
|
+
cleanup();
|
|
302
|
+
reject(new AlyteChallengeError(code));
|
|
303
|
+
} };
|
|
304
|
+
const abort = () => fail('challenge_closed');
|
|
305
|
+
const receive = (event) => {
|
|
306
|
+
if (done || event.origin !== base || event.source !== iframe.contentWindow)
|
|
307
|
+
return;
|
|
308
|
+
const data = event.data;
|
|
309
|
+
if (!data || data.type !== 'alyte:challenge' || data.merchantId !== opts.merchantId || data.purchaseId !== opts.purchaseId)
|
|
310
|
+
return;
|
|
311
|
+
if (data.event === 'ready') {
|
|
312
|
+
ready = true;
|
|
313
|
+
clearTimeout(timer);
|
|
314
|
+
iframe.contentWindow?.postMessage({ type: 'alyte:challenge', event: 'bootstrap', purchaseId: opts.purchaseId, bearer: opts.bearer }, base);
|
|
315
|
+
}
|
|
316
|
+
else if (data.event === 'status' && ready && statuses.includes(data.status)) {
|
|
317
|
+
// Copy only this allowlist. Neither unexpected fields nor result payloads
|
|
318
|
+
// from a future frame version become a merchant callback or receipt.
|
|
319
|
+
const state = { purchaseId: opts.purchaseId, status: data.status };
|
|
320
|
+
if (state.status !== 'pending' && state.status !== 'sca_required') {
|
|
321
|
+
done = true;
|
|
322
|
+
cleanup();
|
|
323
|
+
resolve(state);
|
|
324
|
+
}
|
|
325
|
+
opts.onStatus?.(state);
|
|
326
|
+
}
|
|
327
|
+
else if (data.event === 'error') {
|
|
328
|
+
fail(data.code === 'unauthorized' ? 'unauthorized' : 'challenge_unavailable');
|
|
329
|
+
}
|
|
330
|
+
else if (data.event === 'resize' && Number.isFinite(data.height)) {
|
|
331
|
+
iframe.style.height = `${Math.max(240, Math.min(1200, Math.ceil(data.height)))}px`;
|
|
332
|
+
}
|
|
333
|
+
else if (data.event === 'navigate' && typeof data.url === 'string') {
|
|
334
|
+
try {
|
|
335
|
+
const back = new URL(data.url);
|
|
336
|
+
if (back.origin === host.location.origin)
|
|
337
|
+
opts.onNavigate?.(back.href);
|
|
338
|
+
}
|
|
339
|
+
catch { /* Ignore malformed navigation messages. */ }
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
if (opts.signal?.aborted) {
|
|
343
|
+
abort();
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
host.addEventListener('message', receive);
|
|
347
|
+
opts.signal?.addEventListener('abort', abort, { once: true });
|
|
348
|
+
timer = setTimeout(() => fail('challenge_unavailable'), opts.readyTimeoutMs ?? 15_000);
|
|
349
|
+
iframe.addEventListener('error', () => fail('challenge_unavailable'), { once: true });
|
|
350
|
+
opts.container.append(iframe);
|
|
351
|
+
});
|
|
352
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,5 +2,6 @@ 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 { AccessAudience, AccessDraftInput, AccessRule, AccessPreview, AccessCommitInput, MembershipProgram, MembershipEvidence } from './access.js';
|
package/dist/inventoryTypes.d.ts
CHANGED
|
@@ -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;
|
package/dist/merchant.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type ClientOptions } from './http.js';
|
|
2
|
-
import
|
|
2
|
+
import { MerchantAccessRules, MerchantMemberships } from './access.js';
|
|
3
|
+
import type { BuyerSessionMint, CatalogMerchant, Merchant, EventItem, MerchantPspLink, Tier, TierKind, FeeBearer, Scheme, PaymentRow, WebhookEndpoint, MerchantInsights, InventoryCatalog, InventoryLocation, InventoryLocationBinding, InventoryOccurrence, InventoryPool, PurchaseLimit, PurchaseLimitReadiness, SetPurchaseLimitInput } from './types.js';
|
|
3
4
|
/**
|
|
4
5
|
* Merchant integration client — drives the `/v1/integration/*` surface with a
|
|
5
6
|
* console-minted API token (`merchant:read` / `merchant:write` scopes; `merchant:admin` for
|
|
@@ -14,6 +15,8 @@ import type { BuyerSessionMint, CatalogMerchant, Merchant, EventItem, MerchantPs
|
|
|
14
15
|
*/
|
|
15
16
|
export declare class AlyteMerchant {
|
|
16
17
|
private readonly t;
|
|
18
|
+
readonly accessRules: MerchantAccessRules;
|
|
19
|
+
readonly memberships: MerchantMemberships;
|
|
17
20
|
constructor(opts: ClientOptions);
|
|
18
21
|
/** Your tenant's full catalog: shops → events → tiers (with restriction fields). */
|
|
19
22
|
catalog(): Promise<{
|
|
@@ -96,6 +99,31 @@ export declare class AlyteMerchant {
|
|
|
96
99
|
deleteEvent(eventId: string): Promise<{
|
|
97
100
|
ok: boolean;
|
|
98
101
|
}>;
|
|
102
|
+
/**
|
|
103
|
+
* Set or replace the per-customer ticket limit for an event (`merchant:write`).
|
|
104
|
+
* `maxPerCustomer` (`1..1000`) caps the tickets one customer can hold or buy;
|
|
105
|
+
* `maxHeldPerCustomer` optionally caps unpaid tickets held at once;
|
|
106
|
+
* `countWaitingWatches` decides whether queued purchases count while waiting.
|
|
107
|
+
* PUT replaces the whole limit, and the first PUT counts the event's earlier sales.
|
|
108
|
+
*/
|
|
109
|
+
setEventPurchaseLimit(eventId: string, input: SetPurchaseLimitInput): Promise<{
|
|
110
|
+
purchaseLimit: PurchaseLimit;
|
|
111
|
+
readiness: PurchaseLimitReadiness;
|
|
112
|
+
}>;
|
|
113
|
+
/**
|
|
114
|
+
* Read an event's per-customer ticket limit (`null` when it has none) and how many
|
|
115
|
+
* of its tickets the limit can count against a customer (`merchant:read`).
|
|
116
|
+
*/
|
|
117
|
+
getEventPurchaseLimit(eventId: string): Promise<{
|
|
118
|
+
purchaseLimit: PurchaseLimit | null;
|
|
119
|
+
readiness: PurchaseLimitReadiness;
|
|
120
|
+
}>;
|
|
121
|
+
/**
|
|
122
|
+
* Remove an event's per-customer ticket limit (`merchant:write`).
|
|
123
|
+
*/
|
|
124
|
+
clearEventPurchaseLimit(eventId: string): Promise<{
|
|
125
|
+
cleared: boolean;
|
|
126
|
+
}>;
|
|
99
127
|
/** Observed stock and base prices for one shop; not a reserved or quoted offer.
|
|
100
128
|
* Read scope does not grant writes. A read/write key can also manage this inventory.
|
|
101
129
|
* Fails with catalog_too_large if any source relation exceeds 2,000 rows. */
|
|
@@ -126,13 +154,17 @@ export declare class AlyteMerchant {
|
|
|
126
154
|
setSlotLocation(merchantId: string, slotId: string, input: InventoryLocationBinding): Promise<{
|
|
127
155
|
slot: InventoryOccurrence;
|
|
128
156
|
}>;
|
|
157
|
+
/** Create a shared pool. With `externalRef` (your stable id, unique per tenant) the create is
|
|
158
|
+
* idempotent: a repeat returns the existing pool untouched with `existing: true`. */
|
|
129
159
|
createPool(input: {
|
|
130
160
|
merchantId: string;
|
|
131
161
|
eventId?: string | null;
|
|
132
162
|
title: string;
|
|
133
163
|
capacity: number;
|
|
164
|
+
externalRef?: string;
|
|
134
165
|
}): Promise<{
|
|
135
166
|
pool: InventoryPool;
|
|
167
|
+
existing?: boolean;
|
|
136
168
|
}>;
|
|
137
169
|
listPools(merchantId: string): Promise<{
|
|
138
170
|
pools: InventoryPool[];
|
package/dist/merchant.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Transport } from './http.js';
|
|
2
|
+
import { MerchantAccessRules, MerchantMemberships } from './access.js';
|
|
2
3
|
/**
|
|
3
4
|
* Merchant integration client — drives the `/v1/integration/*` surface with a
|
|
4
5
|
* console-minted API token (`merchant:read` / `merchant:write` scopes; `merchant:admin` for
|
|
@@ -13,8 +14,12 @@ import { Transport } from './http.js';
|
|
|
13
14
|
*/
|
|
14
15
|
export class AlyteMerchant {
|
|
15
16
|
t;
|
|
17
|
+
accessRules;
|
|
18
|
+
memberships;
|
|
16
19
|
constructor(opts) {
|
|
17
20
|
this.t = new Transport(opts);
|
|
21
|
+
this.accessRules = new MerchantAccessRules(this.t);
|
|
22
|
+
this.memberships = new MerchantMemberships(this.t);
|
|
18
23
|
}
|
|
19
24
|
/** Your tenant's full catalog: shops → events → tiers (with restriction fields). */
|
|
20
25
|
catalog() {
|
|
@@ -49,6 +54,29 @@ export class AlyteMerchant {
|
|
|
49
54
|
deleteEvent(eventId) {
|
|
50
55
|
return this.t.request('DELETE', `/v1/integration/events/${encodeURIComponent(eventId)}`);
|
|
51
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Set or replace the per-customer ticket limit for an event (`merchant:write`).
|
|
59
|
+
* `maxPerCustomer` (`1..1000`) caps the tickets one customer can hold or buy;
|
|
60
|
+
* `maxHeldPerCustomer` optionally caps unpaid tickets held at once;
|
|
61
|
+
* `countWaitingWatches` decides whether queued purchases count while waiting.
|
|
62
|
+
* PUT replaces the whole limit, and the first PUT counts the event's earlier sales.
|
|
63
|
+
*/
|
|
64
|
+
setEventPurchaseLimit(eventId, input) {
|
|
65
|
+
return this.t.request('PUT', `/v1/integration/events/${encodeURIComponent(eventId)}/purchase-limit`, input);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Read an event's per-customer ticket limit (`null` when it has none) and how many
|
|
69
|
+
* of its tickets the limit can count against a customer (`merchant:read`).
|
|
70
|
+
*/
|
|
71
|
+
getEventPurchaseLimit(eventId) {
|
|
72
|
+
return this.t.request('GET', `/v1/integration/events/${encodeURIComponent(eventId)}/purchase-limit`);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Remove an event's per-customer ticket limit (`merchant:write`).
|
|
76
|
+
*/
|
|
77
|
+
clearEventPurchaseLimit(eventId) {
|
|
78
|
+
return this.t.request('DELETE', `/v1/integration/events/${encodeURIComponent(eventId)}/purchase-limit`);
|
|
79
|
+
}
|
|
52
80
|
/** Observed stock and base prices for one shop; not a reserved or quoted offer.
|
|
53
81
|
* Read scope does not grant writes. A read/write key can also manage this inventory.
|
|
54
82
|
* Fails with catalog_too_large if any source relation exceeds 2,000 rows. */
|
|
@@ -72,6 +100,8 @@ export class AlyteMerchant {
|
|
|
72
100
|
setSlotLocation(merchantId, slotId, input) {
|
|
73
101
|
return this.t.request('PUT', `/v1/integration/merchants/${encodeURIComponent(merchantId)}/slots/${encodeURIComponent(slotId)}/location`, input);
|
|
74
102
|
}
|
|
103
|
+
/** Create a shared pool. With `externalRef` (your stable id, unique per tenant) the create is
|
|
104
|
+
* idempotent: a repeat returns the existing pool untouched with `existing: true`. */
|
|
75
105
|
createPool(input) {
|
|
76
106
|
return this.t.request('POST', '/v1/integration/pools', input);
|
|
77
107
|
}
|
package/dist/onPurchase.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ export interface AlyteEventEnvelope<T = unknown> {
|
|
|
13
13
|
}
|
|
14
14
|
/** A purchase that authorized and captured. Fulfil on `tierId` + `quantity`. */
|
|
15
15
|
export interface PaymentSettled {
|
|
16
|
+
/** Verified purchase facts when the PSP reports them; not a liability-shift assertion. */
|
|
17
|
+
authentication?: import('./types.js').PurchaseAuthentication;
|
|
16
18
|
intentId: string;
|
|
17
19
|
merchantId: string;
|
|
18
20
|
/** Integer minor units. NEVER a float — see formatMinor for display. */
|
|
@@ -45,6 +47,18 @@ export interface WatchFailed {
|
|
|
45
47
|
};
|
|
46
48
|
failedAt: string;
|
|
47
49
|
}
|
|
50
|
+
/** Relay to the merchant's buyer before the deadline. This event grants no authority and is not fulfilment. */
|
|
51
|
+
export interface WatchActionRequired {
|
|
52
|
+
tenantId: string;
|
|
53
|
+
merchantId: string;
|
|
54
|
+
buyerRef: string;
|
|
55
|
+
watchId: string;
|
|
56
|
+
purchaseId: string;
|
|
57
|
+
deadline: string;
|
|
58
|
+
agentId?: string;
|
|
59
|
+
tierId?: string;
|
|
60
|
+
quantity?: number;
|
|
61
|
+
}
|
|
48
62
|
/** A signed delivery carrying no payment data. NEVER fulfil on this. */
|
|
49
63
|
export interface WebhookTest {
|
|
50
64
|
[key: string]: unknown;
|
|
@@ -54,6 +68,8 @@ export interface PurchaseHandlers {
|
|
|
54
68
|
onSettled?: (data: PaymentSettled, event: AlyteEventEnvelope<PaymentSettled>) => Promise<void> | void;
|
|
55
69
|
/** A queued purchase terminally refused. Tell the buyer why. */
|
|
56
70
|
onWatchFailed?: (data: WatchFailed, event: AlyteEventEnvelope<WatchFailed>) => Promise<void> | void;
|
|
71
|
+
/** The merchant owns buyer outreach. Deduplicate by eventId; do not buy again or fulfil. */
|
|
72
|
+
onWatchActionRequired?: (data: WatchActionRequired, event: AlyteEventEnvelope<WatchActionRequired>) => Promise<void> | void;
|
|
57
73
|
/** A test delivery — use it to prove your signature check works. */
|
|
58
74
|
onTest?: (event: AlyteEventEnvelope<WebhookTest>) => Promise<void> | void;
|
|
59
75
|
/** Any event type this SDK version does not know. Default: ignored. */
|
package/dist/onPurchase.js
CHANGED
|
@@ -62,6 +62,9 @@ export async function handleWebhook(rawBody, signatureHeader, handlers, options)
|
|
|
62
62
|
case 'watch.failed':
|
|
63
63
|
await handlers.onWatchFailed?.(event.data, event);
|
|
64
64
|
break;
|
|
65
|
+
case 'watch.action_required':
|
|
66
|
+
await handlers.onWatchActionRequired?.(event.data, event);
|
|
67
|
+
break;
|
|
65
68
|
case 'webhook.test':
|
|
66
69
|
await handlers.onTest?.(event);
|
|
67
70
|
break;
|