@invisi-labs/ipp 0.0.0-stage → 1.2.5

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.
@@ -0,0 +1,68 @@
1
+ import { R as Request, P as PaymentSession, C as Checkout, a as CheckoutInput, b as Credential, c as CredentialAcknowledgement } from './types-DTdAUlps.cjs';
2
+ export { A as Asset, d as CreditOption, e as CreditReceipt, f as CreditRequest, g as CreditTerms, E as ErrorMessage, h as EvidenceStatus, F as FailureReason, L as Link, M as Mode, O as Option, i as PaymentOption, j as PaymentReceipt, k as PaymentRequest, l as RequestStatus, S as SessionStatus } from './types-DTdAUlps.cjs';
3
+
4
+ /** Error details deliberately exclude response bodies, request URLs and credentials. */
5
+ declare class IppError extends Error {
6
+ readonly code: string;
7
+ readonly retryable: boolean;
8
+ readonly status?: number | undefined;
9
+ readonly retryAfterMs?: number | undefined;
10
+ constructor(code: string, message: string, retryable?: boolean, status?: number | undefined, retryAfterMs?: number | undefined);
11
+ }
12
+
13
+ /** JSON.parse alone loses duplicate properties and accepts unpaired surrogate escapes. */
14
+ declare function parseIppJson(text: string): unknown;
15
+
16
+ declare function parsePaymentSession(value: unknown, origin?: string): PaymentSession;
17
+ declare function parsePaymentRequest(value: unknown, origin?: string): Request;
18
+ declare function assertRequestMatchesSession(request: Request, session: PaymentSession): void;
19
+ declare function parseCheckoutEntry(value: string): {
20
+ sessionUrl: string;
21
+ token: string;
22
+ };
23
+ declare function parseCheckout(value: unknown): Checkout;
24
+ declare function parseCheckoutInput(value: unknown, now?: number): CheckoutInput;
25
+ declare function parseCredential(value: unknown, request?: Request): Credential;
26
+
27
+ interface HttpOptions {
28
+ fetch?: typeof fetch;
29
+ requestTimeoutMs?: number;
30
+ }
31
+
32
+ interface IppClientOptions extends HttpOptions {
33
+ sessionUrl: string;
34
+ token: string;
35
+ }
36
+ interface WaitOptions {
37
+ intervalMs?: number;
38
+ timeoutMs?: number;
39
+ signal?: AbortSignal;
40
+ }
41
+ /** A session-bound HTTP client. It never signs, broadcasts, pays or redeems evidence. */
42
+ declare class IppClient {
43
+ #private;
44
+ constructor(options: IppClientOptions);
45
+ static fromCheckout(value: Checkout | unknown, options?: HttpOptions): IppClient;
46
+ static fromPaymentRequired(response: Response, options?: HttpOptions): Promise<IppClient>;
47
+ readSession(signal?: AbortSignal): Promise<PaymentSession>;
48
+ confirm(optionId: string, key: string, signal?: AbortSignal): Promise<Request>;
49
+ readRequest(signal?: AbortSignal): Promise<Request>;
50
+ submitCredential(value: Credential, key?: string, signal?: AbortSignal): Promise<CredentialAcknowledgement>;
51
+ waitForResult(options?: WaitOptions): Promise<PaymentSession>;
52
+ }
53
+
54
+ interface MerchantClientOptions extends HttpOptions {
55
+ createUrl: string;
56
+ token: string;
57
+ }
58
+ /** The merchant chooses its creation URL and supplies its own scoped Bearer credential. */
59
+ declare class IppMerchantClient {
60
+ #private;
61
+ constructor(options: MerchantClientOptions);
62
+ createCheckout(value: CheckoutInput | unknown, key: string, signal?: AbortSignal): Promise<Checkout>;
63
+ }
64
+ declare function createCheckoutUrl(sessionUrl: string, token: string, checkoutPage?: string): string;
65
+ /** Serializes a previously created session; no order creation or redemption side effects. */
66
+ declare function paymentRequiredResponse(value: PaymentSession | unknown, entry: Checkout | unknown): Response;
67
+
68
+ export { Checkout, CheckoutInput, Credential, CredentialAcknowledgement, type HttpOptions, IppClient, type IppClientOptions, IppError, IppMerchantClient, type MerchantClientOptions, PaymentSession, Request, type WaitOptions, assertRequestMatchesSession, createCheckoutUrl, parseCheckout, parseCheckoutEntry, parseCheckoutInput, parseCredential, parseIppJson, parsePaymentRequest, parsePaymentSession, paymentRequiredResponse };
@@ -0,0 +1,68 @@
1
+ import { R as Request, P as PaymentSession, C as Checkout, a as CheckoutInput, b as Credential, c as CredentialAcknowledgement } from './types-DTdAUlps.js';
2
+ export { A as Asset, d as CreditOption, e as CreditReceipt, f as CreditRequest, g as CreditTerms, E as ErrorMessage, h as EvidenceStatus, F as FailureReason, L as Link, M as Mode, O as Option, i as PaymentOption, j as PaymentReceipt, k as PaymentRequest, l as RequestStatus, S as SessionStatus } from './types-DTdAUlps.js';
3
+
4
+ /** Error details deliberately exclude response bodies, request URLs and credentials. */
5
+ declare class IppError extends Error {
6
+ readonly code: string;
7
+ readonly retryable: boolean;
8
+ readonly status?: number | undefined;
9
+ readonly retryAfterMs?: number | undefined;
10
+ constructor(code: string, message: string, retryable?: boolean, status?: number | undefined, retryAfterMs?: number | undefined);
11
+ }
12
+
13
+ /** JSON.parse alone loses duplicate properties and accepts unpaired surrogate escapes. */
14
+ declare function parseIppJson(text: string): unknown;
15
+
16
+ declare function parsePaymentSession(value: unknown, origin?: string): PaymentSession;
17
+ declare function parsePaymentRequest(value: unknown, origin?: string): Request;
18
+ declare function assertRequestMatchesSession(request: Request, session: PaymentSession): void;
19
+ declare function parseCheckoutEntry(value: string): {
20
+ sessionUrl: string;
21
+ token: string;
22
+ };
23
+ declare function parseCheckout(value: unknown): Checkout;
24
+ declare function parseCheckoutInput(value: unknown, now?: number): CheckoutInput;
25
+ declare function parseCredential(value: unknown, request?: Request): Credential;
26
+
27
+ interface HttpOptions {
28
+ fetch?: typeof fetch;
29
+ requestTimeoutMs?: number;
30
+ }
31
+
32
+ interface IppClientOptions extends HttpOptions {
33
+ sessionUrl: string;
34
+ token: string;
35
+ }
36
+ interface WaitOptions {
37
+ intervalMs?: number;
38
+ timeoutMs?: number;
39
+ signal?: AbortSignal;
40
+ }
41
+ /** A session-bound HTTP client. It never signs, broadcasts, pays or redeems evidence. */
42
+ declare class IppClient {
43
+ #private;
44
+ constructor(options: IppClientOptions);
45
+ static fromCheckout(value: Checkout | unknown, options?: HttpOptions): IppClient;
46
+ static fromPaymentRequired(response: Response, options?: HttpOptions): Promise<IppClient>;
47
+ readSession(signal?: AbortSignal): Promise<PaymentSession>;
48
+ confirm(optionId: string, key: string, signal?: AbortSignal): Promise<Request>;
49
+ readRequest(signal?: AbortSignal): Promise<Request>;
50
+ submitCredential(value: Credential, key?: string, signal?: AbortSignal): Promise<CredentialAcknowledgement>;
51
+ waitForResult(options?: WaitOptions): Promise<PaymentSession>;
52
+ }
53
+
54
+ interface MerchantClientOptions extends HttpOptions {
55
+ createUrl: string;
56
+ token: string;
57
+ }
58
+ /** The merchant chooses its creation URL and supplies its own scoped Bearer credential. */
59
+ declare class IppMerchantClient {
60
+ #private;
61
+ constructor(options: MerchantClientOptions);
62
+ createCheckout(value: CheckoutInput | unknown, key: string, signal?: AbortSignal): Promise<Checkout>;
63
+ }
64
+ declare function createCheckoutUrl(sessionUrl: string, token: string, checkoutPage?: string): string;
65
+ /** Serializes a previously created session; no order creation or redemption side effects. */
66
+ declare function paymentRequiredResponse(value: PaymentSession | unknown, entry: Checkout | unknown): Response;
67
+
68
+ export { Checkout, CheckoutInput, Credential, CredentialAcknowledgement, type HttpOptions, IppClient, type IppClientOptions, IppError, IppMerchantClient, type MerchantClientOptions, PaymentSession, Request, type WaitOptions, assertRequestMatchesSession, createCheckoutUrl, parseCheckout, parseCheckoutEntry, parseCheckoutInput, parseCredential, parseIppJson, parsePaymentRequest, parsePaymentSession, paymentRequiredResponse };
package/dist/index.js ADDED
@@ -0,0 +1,532 @@
1
+ import {
2
+ IppError,
3
+ apiUrl,
4
+ assertNoSecret,
5
+ assertReceiptMatchesRequest,
6
+ assertRequestLinksSafe,
7
+ assertRequestMatchesSession,
8
+ bearer,
9
+ idempotencyKey,
10
+ invalid,
11
+ methodValidation,
12
+ object,
13
+ parseCheckout,
14
+ parseCheckoutEntry,
15
+ parseCheckoutInput,
16
+ parseCredential,
17
+ parsePaymentRequest,
18
+ parsePaymentSession,
19
+ text
20
+ } from "./chunk-SFITNDN5.js";
21
+
22
+ // src/core/json.ts
23
+ function parseIppJson(text2) {
24
+ if (text2.length > 1024 * 1024) return invalid();
25
+ let pos = 0;
26
+ const space = () => {
27
+ while (/\s/.test(text2[pos] ?? "") && pos < text2.length) pos++;
28
+ };
29
+ const string = () => {
30
+ const start = pos++;
31
+ while (pos < text2.length) {
32
+ const c = text2[pos++];
33
+ if (c === "\\") {
34
+ pos++;
35
+ continue;
36
+ }
37
+ if (c === '"') {
38
+ let value2;
39
+ try {
40
+ value2 = JSON.parse(text2.slice(start, pos));
41
+ } catch {
42
+ return invalid();
43
+ }
44
+ for (let i = 0; i < value2.length; i++) {
45
+ const n = value2.charCodeAt(i);
46
+ if (n >= 55296 && n <= 56319) {
47
+ const next = value2.charCodeAt(++i);
48
+ if (!(next >= 56320 && next <= 57343)) return invalid();
49
+ } else if (n >= 56320 && n <= 57343) return invalid();
50
+ }
51
+ return value2;
52
+ }
53
+ }
54
+ return invalid();
55
+ };
56
+ const value = (depth) => {
57
+ if (depth > 64) return invalid();
58
+ space();
59
+ const c = text2[pos];
60
+ if (c === '"') {
61
+ string();
62
+ return;
63
+ }
64
+ if (c === "{" || c === "[") {
65
+ pos++;
66
+ space();
67
+ const close = c === "{" ? "}" : "]";
68
+ const keys = /* @__PURE__ */ new Set();
69
+ if (text2[pos] === close) {
70
+ pos++;
71
+ return;
72
+ }
73
+ while (pos < text2.length) {
74
+ if (c === "{") {
75
+ space();
76
+ if (text2[pos] !== '"') return invalid();
77
+ const key = string();
78
+ if (keys.has(key)) return invalid();
79
+ keys.add(key);
80
+ space();
81
+ if (text2[pos++] !== ":") return invalid();
82
+ }
83
+ value(depth + 1);
84
+ space();
85
+ if (text2[pos] === close) {
86
+ pos++;
87
+ return;
88
+ }
89
+ if (text2[pos++] !== ",") return invalid();
90
+ }
91
+ return invalid();
92
+ }
93
+ const match = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(
94
+ text2.slice(pos)
95
+ );
96
+ if (!match) return invalid();
97
+ pos += match[0].length;
98
+ };
99
+ try {
100
+ value(0);
101
+ space();
102
+ if (pos !== text2.length) return invalid();
103
+ return JSON.parse(text2);
104
+ } catch {
105
+ return invalid();
106
+ }
107
+ }
108
+ async function readIppResponse(response) {
109
+ const maximum = 1024 * 1024;
110
+ const length = response.headers.get("Content-Length");
111
+ if (length && (!/^\d+$/.test(length) || Number(length) > maximum)) return invalid();
112
+ if (!response.body) return invalid();
113
+ const reader = response.body.getReader();
114
+ const chunks = [];
115
+ let total = 0;
116
+ try {
117
+ while (true) {
118
+ const chunk = await reader.read();
119
+ if (chunk.done) break;
120
+ total += chunk.value.byteLength;
121
+ if (total > maximum) {
122
+ await reader.cancel();
123
+ return invalid();
124
+ }
125
+ chunks.push(chunk.value);
126
+ }
127
+ } finally {
128
+ reader.releaseLock();
129
+ }
130
+ const bytes = new Uint8Array(total);
131
+ let offset = 0;
132
+ for (const chunk of chunks) {
133
+ bytes.set(chunk, offset);
134
+ offset += chunk.byteLength;
135
+ }
136
+ let text2;
137
+ try {
138
+ text2 = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
139
+ } catch {
140
+ return invalid();
141
+ }
142
+ return parseIppJson(text2);
143
+ }
144
+
145
+ // src/http/transport.ts
146
+ function duration(value) {
147
+ if (!Number.isSafeInteger(value) || value <= 0 || value > 2147483647) return invalid();
148
+ return value;
149
+ }
150
+ function aborted(signal) {
151
+ if (signal?.aborted) throw new IppError("aborted", "IPP operation aborted.");
152
+ }
153
+ function retryAfter(value) {
154
+ if (value === null) return void 0;
155
+ const ms = /^\d+$/.test(value) ? Number(value) * 1e3 : Date.parse(value) - Date.now();
156
+ return Number.isFinite(ms) ? Math.min(2147483647, Math.max(0, ms)) : void 0;
157
+ }
158
+ async function sendIpp(options, url, token, method, body, key, signal, statuses) {
159
+ apiUrl(url);
160
+ bearer(token);
161
+ assertNoSecret(url, token);
162
+ aborted(signal);
163
+ const controller = new AbortController();
164
+ const abort = () => controller.abort();
165
+ signal?.addEventListener("abort", abort, { once: true });
166
+ const timer = setTimeout(abort, duration(options.requestTimeoutMs ?? 15e3));
167
+ try {
168
+ const headers = {
169
+ Accept: "application/json",
170
+ Authorization: `Bearer ${token}`
171
+ };
172
+ if (body !== void 0) headers["Content-Type"] = "application/json";
173
+ if (key !== void 0) headers["Idempotency-Key"] = key;
174
+ const response = await (options.fetch ?? globalThis.fetch)(url, {
175
+ method,
176
+ headers,
177
+ redirect: "error",
178
+ credentials: "omit",
179
+ cache: "no-store",
180
+ signal: controller.signal,
181
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
182
+ });
183
+ if (response.redirected || response.url && response.url !== url || response.status >= 300 && response.status < 400)
184
+ return invalid();
185
+ if (!/^application\/json(?:\s*;|$)/i.test(response.headers.get("Content-Type") ?? ""))
186
+ return invalid();
187
+ const value = await readIppResponse(response);
188
+ if (!response.ok) {
189
+ const e = object(value, ["ippVersion", "type", "error"]);
190
+ const details = object(e.error, ["code", "message", "retryable"]);
191
+ if (e.ippVersion !== 1 || e.type !== "error" || typeof details.retryable !== "boolean" || !/^[a-z][a-z0-9_]{0,63}$/.test(text(details.code)))
192
+ return invalid();
193
+ text(details.message);
194
+ throw new IppError(
195
+ details.code,
196
+ "IPP request failed.",
197
+ details.retryable,
198
+ response.status,
199
+ retryAfter(response.headers.get("Retry-After"))
200
+ );
201
+ }
202
+ if (!statuses.includes(response.status)) return invalid();
203
+ return { value, response };
204
+ } catch (error) {
205
+ if (error instanceof IppError) throw error;
206
+ if (signal?.aborted) throw new IppError("aborted", "IPP operation aborted.");
207
+ throw new IppError(
208
+ "transport_error",
209
+ "IPP transport failed; recover the original operation before retrying.",
210
+ true
211
+ );
212
+ } finally {
213
+ clearTimeout(timer);
214
+ signal?.removeEventListener("abort", abort);
215
+ }
216
+ }
217
+ function delay(ms, signal) {
218
+ aborted(signal);
219
+ return new Promise((resolve, reject) => {
220
+ const abort = () => {
221
+ clearTimeout(timer);
222
+ signal?.removeEventListener("abort", abort);
223
+ reject(new IppError("aborted", "IPP operation aborted."));
224
+ };
225
+ const timer = setTimeout(() => {
226
+ signal?.removeEventListener("abort", abort);
227
+ resolve();
228
+ }, ms);
229
+ signal?.addEventListener("abort", abort, { once: true });
230
+ });
231
+ }
232
+ function stable(value) {
233
+ if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
234
+ if (value && typeof value === "object")
235
+ return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${stable(v)}`).join(",")}}`;
236
+ return JSON.stringify(value) ?? "null";
237
+ }
238
+
239
+ // src/http/client.ts
240
+ var IppClient = class _IppClient {
241
+ #url;
242
+ #token;
243
+ #origin;
244
+ #http;
245
+ #session;
246
+ #request;
247
+ #requestUrl;
248
+ #option;
249
+ #retryAfterMs;
250
+ constructor(options) {
251
+ this.#url = apiUrl(options.sessionUrl);
252
+ this.#origin = new URL(this.#url).origin;
253
+ this.#token = bearer(options.token);
254
+ assertNoSecret(this.#url, this.#token);
255
+ this.#http = {
256
+ ...options.fetch ? { fetch: options.fetch } : {},
257
+ requestTimeoutMs: duration(options.requestTimeoutMs ?? 15e3)
258
+ };
259
+ }
260
+ static fromCheckout(value, options = {}) {
261
+ const c = parseCheckout(value);
262
+ const entry = parseCheckoutEntry(c.checkoutUrl);
263
+ return new _IppClient({ ...entry, ...options });
264
+ }
265
+ static async fromPaymentRequired(response, options = {}) {
266
+ if (response.status !== 402 || !/^application\/json(?:\s*;|$)/i.test(response.headers.get("Content-Type") ?? ""))
267
+ return invalid();
268
+ const links = response.headers.get("Link") ?? "";
269
+ const entries = [...links.matchAll(/<([^<>]+)>\s*;\s*rel="ipp-(session|checkout)"/g)];
270
+ const sessions = entries.filter((e) => e[2] === "session");
271
+ const checkouts = entries.filter((e) => e[2] === "checkout");
272
+ if (sessions.length !== 1 || checkouts.length !== 1) return invalid();
273
+ const sessionUrl = apiUrl(sessions[0][1]);
274
+ const entry = parseCheckoutEntry(checkouts[0][1]);
275
+ if (entry.sessionUrl !== sessionUrl) return invalid();
276
+ const client = new _IppClient({ ...entry, ...options });
277
+ client.#session = parsePaymentSession(
278
+ await readIppResponse(response),
279
+ new URL(sessionUrl).origin
280
+ );
281
+ client.#assertSessionLinks(client.#session);
282
+ if (client.#session.links.request) client.#requestUrl = client.#session.links.request.href;
283
+ return client;
284
+ }
285
+ async readSession(signal) {
286
+ const { value, response } = await sendIpp(
287
+ this.#http,
288
+ this.#url,
289
+ this.#token,
290
+ "GET",
291
+ void 0,
292
+ void 0,
293
+ signal,
294
+ [200]
295
+ );
296
+ const s = parsePaymentSession(value, this.#origin);
297
+ this.#assertSessionLinks(s);
298
+ this.#retryAfterMs = retryAfter(response.headers.get("Retry-After"));
299
+ const old = this.#session;
300
+ if (old) {
301
+ for (const key of [
302
+ "sessionId",
303
+ "mode",
304
+ "createdAt",
305
+ "expiresAt",
306
+ "merchant",
307
+ "description",
308
+ "options"
309
+ ])
310
+ if (stable(old[key]) !== stable(s[key])) return invalid();
311
+ if (old.activeRequestId && old.activeRequestId !== s.activeRequestId) return invalid();
312
+ if (["succeeded", "failed"].includes(old.status) && (old.status !== s.status || old.failureReason !== s.failureReason))
313
+ return invalid();
314
+ if (old.receipt && stable(old.receipt) !== stable(s.receipt)) return invalid();
315
+ }
316
+ if (this.#request) {
317
+ assertRequestMatchesSession(this.#request, s);
318
+ if (s.activeRequestId !== this.#request.requestId) return invalid();
319
+ if (s.receipt) {
320
+ assertReceiptMatchesRequest(s.receipt, this.#request);
321
+ }
322
+ }
323
+ this.#session = s;
324
+ if (s.links.request) this.#requestUrl = s.links.request.href;
325
+ return structuredClone(s);
326
+ }
327
+ #assertUrl(url, request = this.#request) {
328
+ assertNoSecret(url, this.#token);
329
+ if (request)
330
+ for (const secret of methodValidation(request.method).privateValues(request))
331
+ assertNoSecret(url, secret);
332
+ }
333
+ #assertSessionLinks(session, request = this.#request) {
334
+ this.#assertUrl(session.links.confirm.href, request);
335
+ if (session.links.request) this.#assertUrl(session.links.request.href, request);
336
+ }
337
+ #accept(value) {
338
+ const r = parsePaymentRequest(value, this.#origin);
339
+ assertRequestLinksSafe(r, this.#token);
340
+ if (!this.#session) return invalid();
341
+ assertRequestMatchesSession(r, this.#session);
342
+ this.#assertSessionLinks(this.#session, r);
343
+ this.#assertUrl(this.#url, r);
344
+ if (this.#requestUrl) this.#assertUrl(this.#requestUrl, r);
345
+ if (this.#session.receipt) assertReceiptMatchesRequest(this.#session.receipt, r);
346
+ if (this.#option && r.optionId !== this.#option) return invalid();
347
+ if (this.#request) {
348
+ const frozen = (v) => {
349
+ const { status: _s, failureReason: _f, links: _l, ...terms } = v;
350
+ return terms;
351
+ };
352
+ if (stable(frozen(r)) !== stable(frozen(this.#request))) return invalid();
353
+ if (["succeeded", "failed"].includes(this.#request.status) && (r.status !== this.#request.status || r.failureReason !== this.#request.failureReason))
354
+ return invalid();
355
+ }
356
+ this.#request = r;
357
+ this.#option = r.optionId;
358
+ return structuredClone(r);
359
+ }
360
+ async confirm(optionId, key, signal) {
361
+ idempotencyKey(key);
362
+ if (!this.#session) await this.readSession(signal);
363
+ const s = this.#session;
364
+ if (!s.options.some((o) => o.id === optionId) || this.#option && optionId !== this.#option)
365
+ return invalid();
366
+ const { value, response } = await sendIpp(
367
+ this.#http,
368
+ s.links.confirm.href,
369
+ this.#token,
370
+ "POST",
371
+ { optionId },
372
+ key,
373
+ signal,
374
+ [200, 201]
375
+ );
376
+ const location = apiUrl(response.headers.get("Location"), this.#origin);
377
+ if (parsePaymentRequest(value, this.#origin).optionId !== optionId) return invalid();
378
+ const parsed = parsePaymentRequest(value, this.#origin);
379
+ this.#assertUrl(location, parsed);
380
+ const r = this.#accept(parsed);
381
+ this.#requestUrl = location;
382
+ return r;
383
+ }
384
+ async readRequest(signal) {
385
+ if (!this.#session) await this.readSession(signal);
386
+ if (!this.#requestUrl) return invalid();
387
+ const { value } = await sendIpp(
388
+ this.#http,
389
+ this.#requestUrl,
390
+ this.#token,
391
+ "GET",
392
+ void 0,
393
+ void 0,
394
+ signal,
395
+ [200]
396
+ );
397
+ return this.#accept(value);
398
+ }
399
+ async submitCredential(value, key, signal) {
400
+ if (!this.#request) await this.readRequest(signal);
401
+ const r = this.#request;
402
+ const c = parseCredential(value, r);
403
+ const result = await sendIpp(
404
+ this.#http,
405
+ r.links.credentials.href,
406
+ this.#token,
407
+ "POST",
408
+ c,
409
+ key === void 0 ? void 0 : idempotencyKey(key),
410
+ signal,
411
+ [202]
412
+ );
413
+ const ack = object(result.value, [
414
+ "ippVersion",
415
+ "type",
416
+ "sessionId",
417
+ "requestId",
418
+ "status"
419
+ ]);
420
+ if (ack.ippVersion !== 1 || ack.type !== "credential_acknowledgement" || ack.status !== "accepted" || ack.sessionId !== r.sessionId || ack.requestId !== r.requestId)
421
+ return invalid();
422
+ return structuredClone(ack);
423
+ }
424
+ async waitForResult(options = {}) {
425
+ const interval = duration(options.intervalMs ?? 1e3), timeout = duration(options.timeoutMs ?? 6e4);
426
+ const controller = new AbortController();
427
+ const abort = () => controller.abort();
428
+ aborted(options.signal);
429
+ options.signal?.addEventListener("abort", abort, { once: true });
430
+ const timer = setTimeout(abort, timeout);
431
+ const end = Date.now() + timeout;
432
+ try {
433
+ while (Date.now() < end) {
434
+ let wait = interval;
435
+ try {
436
+ const s = await this.readSession(controller.signal);
437
+ if (s.status === "succeeded" || s.status === "failed") return s;
438
+ wait = this.#retryAfterMs ?? interval;
439
+ } catch (error) {
440
+ if (!(error instanceof IppError) || !error.retryable || ![429, 503].includes(error.status ?? 0))
441
+ throw error;
442
+ wait = error.retryAfterMs ?? interval;
443
+ }
444
+ await delay(Math.min(wait, Math.max(1, end - Date.now())), controller.signal);
445
+ }
446
+ throw new IppError(
447
+ "timeout",
448
+ "IPP result is still unknown; query the same session to recover.",
449
+ true
450
+ );
451
+ } catch (error) {
452
+ if (options.signal?.aborted) throw new IppError("aborted", "IPP operation aborted.");
453
+ if (controller.signal.aborted)
454
+ throw new IppError(
455
+ "timeout",
456
+ "IPP result is still unknown; query the same session to recover.",
457
+ true
458
+ );
459
+ throw error;
460
+ } finally {
461
+ clearTimeout(timer);
462
+ options.signal?.removeEventListener("abort", abort);
463
+ }
464
+ }
465
+ };
466
+
467
+ // src/http/merchant.ts
468
+ var IppMerchantClient = class {
469
+ #url;
470
+ #token;
471
+ #http;
472
+ constructor(options) {
473
+ this.#url = apiUrl(options.createUrl);
474
+ this.#token = bearer(options.token);
475
+ this.#http = {
476
+ ...options.fetch ? { fetch: options.fetch } : {},
477
+ ...options.requestTimeoutMs !== void 0 ? { requestTimeoutMs: options.requestTimeoutMs } : {}
478
+ };
479
+ }
480
+ async createCheckout(value, key, signal) {
481
+ const input = parseCheckoutInput(value);
482
+ const result = await sendIpp(
483
+ this.#http,
484
+ this.#url,
485
+ this.#token,
486
+ "POST",
487
+ input,
488
+ idempotencyKey(key),
489
+ signal,
490
+ [200, 201]
491
+ );
492
+ const c = parseCheckout(result.value);
493
+ if (c.expiresAt !== input.expiresAt) return invalid();
494
+ return c;
495
+ }
496
+ };
497
+ function createCheckoutUrl(sessionUrl, token, checkoutPage = "https://dapp.invisipay.fi/checkout") {
498
+ const base = apiUrl(checkoutPage);
499
+ assertNoSecret(base, bearer(token));
500
+ assertNoSecret(apiUrl(sessionUrl), bearer(token));
501
+ return `${base}#${new URLSearchParams({ sessionUrl: apiUrl(sessionUrl), token: bearer(token) })}`;
502
+ }
503
+ function paymentRequiredResponse(value, entry) {
504
+ const checkout = parseCheckout(entry);
505
+ const s = parsePaymentSession(value, new URL(checkout.sessionUrl).origin);
506
+ if (s.expiresAt !== checkout.expiresAt || s.status === "succeeded" || s.status === "failed")
507
+ return invalid();
508
+ return new Response(JSON.stringify(s), {
509
+ status: 402,
510
+ headers: {
511
+ "Content-Type": "application/json",
512
+ "Cache-Control": "no-store",
513
+ Link: `<${checkout.sessionUrl}>; rel="ipp-session", <${checkout.checkoutUrl}>; rel="ipp-checkout"`
514
+ }
515
+ });
516
+ }
517
+ export {
518
+ IppClient,
519
+ IppError,
520
+ IppMerchantClient,
521
+ assertRequestMatchesSession,
522
+ createCheckoutUrl,
523
+ parseCheckout,
524
+ parseCheckoutEntry,
525
+ parseCheckoutInput,
526
+ parseCredential,
527
+ parseIppJson,
528
+ parsePaymentRequest,
529
+ parsePaymentSession,
530
+ paymentRequiredResponse
531
+ };
532
+ //# sourceMappingURL=index.js.map