@conto_finance/sdk 0.6.1 → 0.6.2-beta.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/index.mjs CHANGED
@@ -8,16 +8,17 @@ import {
8
8
  __commonJS,
9
9
  __privateAdd,
10
10
  __privateGet,
11
+ __privateMethod,
11
12
  __privateSet,
12
13
  __toESM
13
- } from "./chunk-WSIKPUZJ.mjs";
14
+ } from "./chunk-TGOYFBKZ.mjs";
14
15
 
15
16
  // package.json
16
17
  var require_package = __commonJS({
17
18
  "package.json"(exports, module) {
18
19
  module.exports = {
19
20
  name: "@conto_finance/sdk",
20
- version: "0.6.1",
21
+ version: "0.6.2-beta.1",
21
22
  description: "Conto SDK for AI agent payment authorization",
22
23
  main: "./dist/index.js",
23
24
  module: "./dist/index.mjs",
@@ -42,10 +43,16 @@ var require_package = __commonJS({
42
43
  types: "./dist/checkout-verifier.d.ts",
43
44
  import: "./dist/checkout-verifier.mjs",
44
45
  require: "./dist/checkout-verifier.js"
46
+ },
47
+ "./link-wallet": {
48
+ types: "./dist/link-wallet.d.ts",
49
+ import: "./dist/link-wallet.mjs",
50
+ require: "./dist/link-wallet.js"
45
51
  }
46
52
  },
47
53
  publishConfig: {
48
- access: "public"
54
+ access: "public",
55
+ tag: "beta"
49
56
  },
50
57
  engines: {
51
58
  node: ">=20.19.0"
@@ -58,7 +65,7 @@ var require_package = __commonJS({
58
65
  dev: "tsup --watch",
59
66
  lint: "tsc --noEmit",
60
67
  test: "npm run lint && npm run test:contract && npm run test:consumer",
61
- "test:contract": "npm run build && node --test test/contract.test.mjs test/playwright.test.mjs test/browserbase.test.mjs test/checkout-verifier.test.mjs test/developer-experience.test.mjs test/checkout.test.mjs test/purchases.test.mjs",
68
+ "test:contract": "npm run build && node --test test/contract.test.mjs test/playwright.test.mjs test/browserbase.test.mjs test/checkout-verifier.test.mjs test/developer-experience.test.mjs test/checkout.test.mjs test/link-wallet.test.mjs test/purchases.test.mjs test/allowances.test.mjs test/purchase-watch-lifecycle.test.mjs ../../examples/link-wallet-agent/verify.test.mjs",
62
69
  "test:consumer": "npm run build && node --test test/consumer.test.mjs",
63
70
  "verify:release": "node scripts/verify-release.mjs",
64
71
  prepublishOnly: "npm run verify:release && npm run lint && npm run test:contract && npm run test:consumer"
@@ -83,7 +90,7 @@ var require_package = __commonJS({
83
90
  email: "support@conto.finance"
84
91
  },
85
92
  dependencies: {
86
- "@sentry/node": "^10.63.0"
93
+ "@sentry/node": "^10.73.0"
87
94
  },
88
95
  peerDependencies: {
89
96
  "playwright-core": ">=1.50.0"
@@ -121,24 +128,31 @@ var require_package_version = __commonJS({
121
128
  // src/index.ts
122
129
  var import_package_version2 = __toESM(require_package_version());
123
130
  import * as Sentry2 from "@sentry/node";
124
- import { randomUUID } from "crypto";
131
+ import { createHash, randomUUID } from "crypto";
125
132
 
126
133
  // src/purchases.ts
127
134
  import { createHmac, timingSafeEqual } from "crypto";
128
135
  var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "blocked", "failed", "cancelled"]);
129
136
  var isFinalPurchaseStatus = (status) => TERMINAL.has(status);
130
- async function* parseServerSentEvents(body) {
137
+ async function* parseServerSentEvents(body, signal) {
131
138
  const reader = body.getReader();
139
+ const cancel = () => {
140
+ void reader.cancel().catch(() => {
141
+ });
142
+ };
143
+ signal?.addEventListener("abort", cancel, { once: true });
144
+ if (signal?.aborted) cancel();
132
145
  const decoder = new TextDecoder();
133
146
  let buffer = "";
134
147
  let frame = { data: [] };
135
148
  try {
136
149
  while (true) {
137
150
  const { value, done } = await reader.read();
138
- if (done) break;
151
+ if (done || signal?.aborted) break;
139
152
  buffer += decoder.decode(value, { stream: true });
140
153
  let newline;
141
154
  while ((newline = buffer.search(/\r?\n/)) >= 0) {
155
+ if (signal?.aborted) return;
142
156
  const line = buffer.slice(0, newline);
143
157
  buffer = buffer.slice(newline + (buffer[newline] === "\r" ? 2 : 1));
144
158
  if (line === "") {
@@ -157,20 +171,30 @@ async function* parseServerSentEvents(body) {
157
171
  }
158
172
  }
159
173
  } finally {
174
+ signal?.removeEventListener("abort", cancel);
175
+ await reader.cancel().catch(() => {
176
+ });
160
177
  reader.releaseLock();
161
178
  }
162
179
  }
163
180
  var sleep = (ms, signal) => new Promise((resolve) => {
164
- const timer = setTimeout(resolve, ms);
165
- signal?.addEventListener(
166
- "abort",
167
- () => {
168
- clearTimeout(timer);
169
- resolve();
170
- },
171
- { once: true }
172
- );
181
+ if (signal?.aborted) return resolve();
182
+ const finish = () => {
183
+ clearTimeout(timer);
184
+ signal?.removeEventListener("abort", finish);
185
+ resolve();
186
+ };
187
+ const timer = setTimeout(finish, ms);
188
+ signal?.addEventListener("abort", finish, { once: true });
173
189
  });
190
+ function watchRead(pending, signal) {
191
+ return new Promise((resolve, reject) => {
192
+ const abort = () => reject(new DOMException("Watch stopped", "AbortError"));
193
+ signal.addEventListener("abort", abort, { once: true });
194
+ if (signal.aborted) abort();
195
+ pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
196
+ });
197
+ }
174
198
  function requirePurchaseId(id) {
175
199
  if (!/^[a-z0-9]{8,64}$/i.test(id)) throw new TypeError("purchase id is not valid");
176
200
  return encodeURIComponent(id);
@@ -309,82 +333,100 @@ var PurchasesClient = class {
309
333
  const path = `${__privateGet(this, _base2)}/${requirePurchaseId(id)}`;
310
334
  const mode = options.mode ?? "auto";
311
335
  const interval = Math.max(500, options.pollIntervalMs ?? 2e3);
312
- const deadline = options.maxWaitMs ? Date.now() + options.maxWaitMs : Infinity;
313
- let cursor = Math.max(0, options.after ?? 0);
314
- let streaming = mode !== "poll";
315
- const emit = (event) => {
316
- if (event.version <= cursor && event.type !== "purchase.resync") return null;
317
- cursor = Math.max(cursor, event.version);
318
- return event;
319
- };
320
- while (!options.signal?.aborted && Date.now() < deadline) {
321
- if (streaming) {
322
- try {
323
- const response = await __privateGet(this, _transport2).openStream(
324
- `${path}/events/stream?after=${cursor}`,
325
- { signal: options.signal, lastEventId: String(cursor) }
326
- );
327
- if (!response.body) throw new Error("streaming unavailable");
328
- for await (const frame of parseServerSentEvents(response.body)) {
329
- if (frame.event === "end") return;
330
- if (frame.event === "error") break;
331
- if (frame.event === "resync") {
332
- const purchase = JSON.parse(frame.data);
333
- const event2 = {
334
- id: `resync:${purchase.version}`,
335
- purchaseId: purchase.id,
336
- version: purchase.version,
337
- type: "purchase.resync",
338
- createdAt: purchase.updatedAt,
339
- data: purchase
340
- };
341
- cursor = purchase.version;
342
- yield event2;
343
- if (isFinalPurchaseStatus(purchase.status)) return;
336
+ if (options.maxWaitMs !== void 0 && (!Number.isFinite(options.maxWaitMs) || options.maxWaitMs < 0 || options.maxWaitMs > 2147483647))
337
+ throw new TypeError("maxWaitMs must be between 0 and 2147483647");
338
+ if (options.signal?.aborted || options.maxWaitMs === 0) return;
339
+ const controller = new AbortController();
340
+ const signal = controller.signal;
341
+ const abort = () => controller.abort();
342
+ options.signal?.addEventListener("abort", abort, { once: true });
343
+ const timeout = options.maxWaitMs === void 0 ? void 0 : setTimeout(abort, options.maxWaitMs);
344
+ try {
345
+ let cursor = Math.max(0, options.after ?? 0);
346
+ let streaming = mode !== "poll";
347
+ const emit = (event) => {
348
+ if (event.version <= cursor && event.type !== "purchase.resync") return null;
349
+ cursor = Math.max(cursor, event.version);
350
+ return event;
351
+ };
352
+ while (!signal.aborted) {
353
+ if (streaming) {
354
+ try {
355
+ const response = await __privateGet(this, _transport2).openStream(
356
+ `${path}/events/stream?after=${cursor}`,
357
+ { signal, lastEventId: String(cursor) }
358
+ );
359
+ if (!response.body) throw new Error("streaming unavailable");
360
+ for await (const frame of parseServerSentEvents(response.body, signal)) {
361
+ if (frame.event === "end") return;
362
+ if (frame.event === "error") break;
363
+ if (frame.event === "resync") {
364
+ const purchase = JSON.parse(frame.data);
365
+ const event2 = {
366
+ id: `resync:${purchase.version}`,
367
+ purchaseId: purchase.id,
368
+ version: purchase.version,
369
+ type: "purchase.resync",
370
+ createdAt: purchase.updatedAt,
371
+ data: purchase
372
+ };
373
+ cursor = purchase.version;
374
+ yield event2;
375
+ if (isFinalPurchaseStatus(purchase.status)) return;
376
+ continue;
377
+ }
378
+ if (!frame.data) continue;
379
+ const event = emit(JSON.parse(frame.data));
380
+ if (!event) continue;
381
+ yield event;
382
+ if (isFinalPurchaseStatus(event.data.status)) return;
383
+ }
384
+ await sleep(interval, signal);
385
+ continue;
386
+ } catch (error) {
387
+ if (signal.aborted) return;
388
+ if (isClientError(error)) throw error;
389
+ if (mode === "stream") {
390
+ await sleep(interval, signal);
344
391
  continue;
345
392
  }
346
- if (!frame.data) continue;
347
- const event = emit(JSON.parse(frame.data));
348
- if (!event) continue;
349
- yield event;
350
- if (isFinalPurchaseStatus(event.data.status)) return;
393
+ streaming = false;
351
394
  }
352
- continue;
395
+ }
396
+ let page;
397
+ try {
398
+ page = await watchRead(this.events(id, { after: cursor, limit: 100 }), signal);
353
399
  } catch (error) {
354
- if (options.signal?.aborted) return;
355
- if (isClientError(error)) throw error;
356
- if (mode === "stream") {
357
- await sleep(interval, options.signal);
358
- continue;
359
- }
360
- streaming = false;
400
+ if (codeOf(error) !== "CURSOR_INVALID") throw error;
401
+ const purchase = await watchRead(this.get(id), signal);
402
+ cursor = purchase.version;
403
+ yield {
404
+ id: `resync:${purchase.version}`,
405
+ purchaseId: purchase.id,
406
+ version: purchase.version,
407
+ type: "purchase.resync",
408
+ createdAt: purchase.updatedAt,
409
+ data: purchase
410
+ };
411
+ if (isFinalPurchaseStatus(purchase.status)) return;
412
+ continue;
361
413
  }
414
+ if (signal.aborted) return;
415
+ for (const item of page.items) {
416
+ if (signal.aborted) return;
417
+ const event = emit(item);
418
+ if (!event) continue;
419
+ yield event;
420
+ if (isFinalPurchaseStatus(event.data.status)) return;
421
+ }
422
+ if (!page.hasMore) await sleep(interval, signal);
362
423
  }
363
- let page;
364
- try {
365
- page = await this.events(id, { after: cursor, limit: 100 });
366
- } catch (error) {
367
- if (codeOf(error) !== "CURSOR_INVALID") throw error;
368
- const purchase = await this.get(id);
369
- cursor = purchase.version;
370
- yield {
371
- id: `resync:${purchase.version}`,
372
- purchaseId: purchase.id,
373
- version: purchase.version,
374
- type: "purchase.resync",
375
- createdAt: purchase.updatedAt,
376
- data: purchase
377
- };
378
- if (isFinalPurchaseStatus(purchase.status)) return;
379
- continue;
380
- }
381
- for (const item of page.items) {
382
- const event = emit(item);
383
- if (!event) continue;
384
- yield event;
385
- if (isFinalPurchaseStatus(event.data.status)) return;
386
- }
387
- if (!page.hasMore) await sleep(interval, options.signal);
424
+ } catch (error) {
425
+ if (!signal.aborted) throw error;
426
+ } finally {
427
+ if (timeout !== void 0) clearTimeout(timeout);
428
+ options.signal?.removeEventListener("abort", abort);
429
+ controller.abort();
388
430
  }
389
431
  }
390
432
  };
@@ -424,13 +466,80 @@ var _client3;
424
466
  var AdminPurchasingClient = class {
425
467
  constructor(client) {
426
468
  __privateAdd(this, _client3);
469
+ /** Inspect or revoke buyer-approved allowances. Grants remain on the buyer's hosted page. */
470
+ this.allowances = {
471
+ /** Returns up to 50 allowances for this buyer, newest first. */
472
+ list: (params) => __privateGet(this, _client3).request(
473
+ "GET",
474
+ `/api/purchasing/allowances?${new URLSearchParams({ buyerId: params.buyerId })}`
475
+ ),
476
+ get: (id) => __privateGet(this, _client3).request("GET", `/api/purchasing/allowances/${enc(id)}`),
477
+ /** Stops future credential release; does not undo payments already submitted. */
478
+ revoke: (id) => __privateGet(this, _client3).request(
479
+ "POST",
480
+ `/api/purchasing/allowances/${enc(id)}/revoke`
481
+ )
482
+ };
427
483
  this.buyers = {
428
484
  /** Maps one of your users to a buyer with its own agent, or returns the existing one. */
429
485
  create: (input) => __privateGet(this, _client3).request("POST", "/api/purchasing/buyers", input),
430
486
  get: (id) => __privateGet(this, _client3).request("GET", `/api/purchasing/buyers/${enc(id)}`),
431
487
  list: (params = {}) => __privateGet(this, _client3).request("GET", `/api/purchasing/buyers?limit=${params.limit ?? 20}&offset=${params.offset ?? 0}`),
432
488
  /** Stops the buyer's agent. Purchases that may already be paid stay visible. */
433
- stop: (id) => __privateGet(this, _client3).request("POST", `/api/purchasing/buyers/${enc(id)}/stop`)
489
+ stop: (id) => __privateGet(this, _client3).request("POST", `/api/purchasing/buyers/${enc(id)}/stop`),
490
+ /**
491
+ * Lets the buyer pay with your company card within limits you set for
492
+ * them, or replaces those limits. The buyer must not have their own card.
493
+ */
494
+ setCompanyCard: (id, input) => __privateGet(this, _client3).request(
495
+ "PUT",
496
+ `/api/purchasing/buyers/${enc(id)}/company-card`,
497
+ input
498
+ ),
499
+ /** The buyer stops paying with your company card. */
500
+ removeCompanyCard: (id) => __privateGet(this, _client3).request(
501
+ "DELETE",
502
+ `/api/purchasing/buyers/${enc(id)}/company-card`
503
+ ),
504
+ /**
505
+ * Replaces what the buyer has at home: inventory, usuals, preferences,
506
+ * chosen recipes and their list. The whole snapshot, every time. Needs
507
+ * Conto to enable kitchen context for your organization.
508
+ */
509
+ setKitchenContext: (id, context) => __privateGet(this, _client3).request(
510
+ "PUT",
511
+ `/api/purchasing/buyers/${enc(id)}/context`,
512
+ context
513
+ ),
514
+ /** The snapshot Conto holds, with context null when nothing was pushed. */
515
+ getKitchenContext: (id) => __privateGet(this, _client3).request(
516
+ "GET",
517
+ `/api/purchasing/buyers/${enc(id)}/context`
518
+ ),
519
+ clearKitchenContext: (id) => __privateGet(this, _client3).request(
520
+ "DELETE",
521
+ `/api/purchasing/buyers/${enc(id)}/context`
522
+ )
523
+ };
524
+ /** Cards your organization pays its buyers' purchases with. Test cards only for now. */
525
+ this.companyCards = {
526
+ create: (input) => __privateGet(this, _client3).request("POST", "/api/purchasing/company-cards", input),
527
+ list: () => __privateGet(this, _client3).request(
528
+ "GET",
529
+ "/api/purchasing/company-cards"
530
+ ),
531
+ get: (id) => __privateGet(this, _client3).request("GET", `/api/purchasing/company-cards/${enc(id)}`),
532
+ /** Changes the card's own caps. Each buyer's limits stay as they are. */
533
+ update: (id, input) => __privateGet(this, _client3).request(
534
+ "PATCH",
535
+ `/api/purchasing/company-cards/${enc(id)}`,
536
+ input
537
+ ),
538
+ /** No buyer can start or pay a purchase with the card after this. */
539
+ remove: (id) => __privateGet(this, _client3).request(
540
+ "DELETE",
541
+ `/api/purchasing/company-cards/${enc(id)}`
542
+ )
434
543
  };
435
544
  this.paymentMethods = {
436
545
  /** A single-use link to the hosted setup page: limits, card and delegation. */
@@ -461,11 +570,8 @@ var AdminPurchasingClient = class {
461
570
  };
462
571
  this.settings = {
463
572
  get: () => __privateGet(this, _client3).request("GET", "/api/purchasing/settings"),
464
- update: (input) => __privateGet(this, _client3).request(
465
- "PUT",
466
- "/api/purchasing/settings",
467
- input
468
- )
573
+ /** Changes only the fields you pass. */
574
+ update: (input) => __privateGet(this, _client3).request("PUT", "/api/purchasing/settings", input)
469
575
  };
470
576
  __privateSet(this, _client3, client);
471
577
  this.purchases = new OrganizationPurchasesClient(client);
@@ -1365,6 +1471,43 @@ var CheckoutApprovalTimeoutError = class extends ContoError {
1365
1471
  this.checkpoint = checkpoint;
1366
1472
  }
1367
1473
  };
1474
+ var LinkCardError = class extends ContoError {
1475
+ constructor(input) {
1476
+ super(input.message, {
1477
+ code: input.code,
1478
+ status: 0,
1479
+ retryGuidance: input.retryGuidance ?? (input.holdReleased ? "Start a new purchase with a new idempotency key if the buyer still wants it." : "Call checkout.cancel(error.checkpoint.id) to release the held spend.")
1480
+ });
1481
+ this.name = "LinkCardError";
1482
+ this.checkpoint = input.checkpoint;
1483
+ if (input.linkRequestId) this.linkRequestId = input.linkRequestId;
1484
+ this.holdReleased = input.holdReleased;
1485
+ }
1486
+ };
1487
+ var LinkCardDeniedError = class extends LinkCardError {
1488
+ constructor(input) {
1489
+ super(input);
1490
+ this.name = "LinkCardDeniedError";
1491
+ }
1492
+ };
1493
+ var LinkCardExpiredError = class extends LinkCardError {
1494
+ constructor(input) {
1495
+ super(input);
1496
+ this.name = "LinkCardExpiredError";
1497
+ }
1498
+ };
1499
+ var LinkCardTimeoutError = class extends LinkCardError {
1500
+ constructor(input) {
1501
+ super(input);
1502
+ this.name = "LinkCardTimeoutError";
1503
+ }
1504
+ };
1505
+ var LinkWalletUnavailableError = class extends LinkCardError {
1506
+ constructor(input) {
1507
+ super(input);
1508
+ this.name = "LinkWalletUnavailableError";
1509
+ }
1510
+ };
1368
1511
  function generatedIdempotencyKey(prefix) {
1369
1512
  return `${prefix}_${randomUUID()}`;
1370
1513
  }
@@ -2485,9 +2628,179 @@ function sleep2(ms, signal) {
2485
2628
  signal?.addEventListener("abort", onAbort, { once: true });
2486
2629
  });
2487
2630
  }
2488
- var _client4;
2631
+ var LINK_REQUEST_ID = /^lsrq_[A-Za-z0-9]{1,64}$/;
2632
+ var LINK_WAITING_STATUSES = /* @__PURE__ */ new Set(["created", "pending_approval"]);
2633
+ var LINK_APPROVED_STATUSES = /* @__PURE__ */ new Set(["approved", "submitted", "succeeded"]);
2634
+ var LINK_CLOSED_STATUSES = /* @__PURE__ */ new Set(["denied", "expired", "canceled", "failed"]);
2635
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
2636
+ function assertPaymentReference(reference) {
2637
+ if (reference === void 0) return;
2638
+ if (reference === null || typeof reference !== "object" || reference.provider !== "LINK" || typeof reference.id !== "string" || !LINK_REQUEST_ID.test(reference.id) || /\d{12,}/.test(reference.id)) {
2639
+ throw checkoutError(
2640
+ 'paymentReference must be { provider: "LINK", id } with a Link spend request id',
2641
+ "INVALID_PAYMENT_REFERENCE"
2642
+ );
2643
+ }
2644
+ }
2645
+ function linkRequestWaiting(request) {
2646
+ return LINK_WAITING_STATUSES.has(request.status) || // 3D Secure: Link continues on its own once the person finishes it.
2647
+ request.status === "requires_action" && request.actionResolution === "auto_resume";
2648
+ }
2649
+ function usd(amountMinor) {
2650
+ return `$${(amountMinor / 100).toFixed(2)}`;
2651
+ }
2652
+ function clip(value, maxLength) {
2653
+ const single = value.replace(/\s+/g, " ").trim();
2654
+ return single.length > maxLength ? `${single.slice(0, maxLength - 3).trimEnd()}...` : single;
2655
+ }
2656
+ function linkCardContext(checkpoint, merchantHost) {
2657
+ const items = checkpoint.cart.lineItems;
2658
+ const listed = items.slice(0, 5).map((item) => `${item.quantity} x ${clip(item.name, 80)}`).join(", ");
2659
+ const more = items.length > 5 ? ` and ${items.length - 5} more` : "";
2660
+ return `Your agent asked for a card to buy ${clip(listed, 300)}${more} from ${clip(checkpoint.merchant.name, 120)} (${merchantHost}) for ${usd(checkpoint.amountMinor)}. Purpose: ${clip(checkpoint.purpose, 200)}. Conto checked this purchase against your rules and approved it. The card is limited to this amount. Approve only if you expect this purchase.`;
2661
+ }
2662
+ function linkCardRequest(checkpoint) {
2663
+ if (!checkpoint.merchant.checkoutUrl) {
2664
+ throw checkoutError("The checkpoint has no checkout URL", "INVALID_CHECKOUT_CHECKPOINT");
2665
+ }
2666
+ const merchantUrl = new URL(checkpoint.merchant.checkoutUrl);
2667
+ return {
2668
+ amountMinor: checkpoint.amountMinor,
2669
+ currency: "USD",
2670
+ merchantName: checkpoint.merchant.name,
2671
+ merchantUrl: merchantUrl.origin,
2672
+ context: linkCardContext(checkpoint, merchantUrl.hostname),
2673
+ lineItems: checkpoint.cart.lineItems.map((item) => ({
2674
+ name: item.name,
2675
+ quantity: item.quantity,
2676
+ unitAmountMinor: item.unitAmountMinor
2677
+ })),
2678
+ // Conto approved amountMinor, so the Link total is exactly that.
2679
+ totals: [
2680
+ ...checkpoint.cart.totals.filter((total) => total.type !== "total").map((total) => ({ type: total.type, label: total.label, amountMinor: total.amountMinor })),
2681
+ { type: "total", label: "Total", amountMinor: checkpoint.amountMinor }
2682
+ ],
2683
+ // One checkpoint and amount is one Link request, so a retry resumes it.
2684
+ idempotencyKey: `conto_${createHash("sha256").update(`${checkpoint.id}:${checkpoint.amountMinor}`).digest("hex").slice(0, 40)}`,
2685
+ metadata: { conto_checkpoint: checkpoint.id }
2686
+ };
2687
+ }
2688
+ function protectLinkCard(card) {
2689
+ const safe = Object.freeze({
2690
+ last4: card.number.slice(-4),
2691
+ ...card.brand ? { brand: card.brand } : {},
2692
+ expMonth: card.expMonth,
2693
+ expYear: card.expYear,
2694
+ ...card.validUntil ? { validUntil: card.validUntil } : {},
2695
+ redacted: true
2696
+ });
2697
+ const result = {
2698
+ number: card.number,
2699
+ securityValue: card.securityValue,
2700
+ expMonth: card.expMonth,
2701
+ expYear: card.expYear,
2702
+ ...card.validUntil ? { validUntil: card.validUntil } : {},
2703
+ last4: card.number.slice(-4),
2704
+ ...card.brand ? { brand: card.brand } : {}
2705
+ };
2706
+ Object.defineProperty(result, "toJSON", { value: () => safe, enumerable: false });
2707
+ Object.defineProperty(result, INSPECT, { value: () => safe, enumerable: false });
2708
+ return Object.freeze(result);
2709
+ }
2710
+ function errorCode(error) {
2711
+ return error && typeof error === "object" && typeof error.code === "string" ? error.code : void 0;
2712
+ }
2713
+ function errorReason(error) {
2714
+ return error && typeof error === "object" && typeof error.reason === "string" ? error.reason : void 0;
2715
+ }
2716
+ function linkFailure(error, signal) {
2717
+ if (error instanceof LinkCardError) {
2718
+ return {
2719
+ kind: error.constructor,
2720
+ code: error.code,
2721
+ message: error.message
2722
+ };
2723
+ }
2724
+ if (errorCode(error) === "LINK_WALLET_UNAVAILABLE") {
2725
+ return {
2726
+ kind: LinkWalletUnavailableError,
2727
+ code: "LINK_WALLET_UNAVAILABLE",
2728
+ message: errorReason(error) === "not_logged_in" ? 'link-cli is not logged in on this machine. Run "link-cli auth login".' : 'The Link wallet is not available here. Install link-cli with "npm i -g @stripe/link-cli", then run "link-cli auth login".'
2729
+ };
2730
+ }
2731
+ if (signal?.aborted || errorReason(error) === "aborted") {
2732
+ return {
2733
+ kind: LinkCardError,
2734
+ code: "LINK_CARD_ABORTED",
2735
+ message: "The Link card request was stopped."
2736
+ };
2737
+ }
2738
+ return {
2739
+ kind: LinkCardError,
2740
+ code: "LINK_CARD_FAILED",
2741
+ message: "The Link card request failed."
2742
+ };
2743
+ }
2744
+ function closedLinkFailure(request) {
2745
+ switch (request.status) {
2746
+ case "denied":
2747
+ return {
2748
+ kind: LinkCardDeniedError,
2749
+ code: "LINK_CARD_DENIED",
2750
+ message: "The person declined the Link card request.",
2751
+ linkClosed: true
2752
+ };
2753
+ case "canceled":
2754
+ return {
2755
+ kind: LinkCardDeniedError,
2756
+ code: "LINK_CARD_DENIED",
2757
+ message: "The Link card request was cancelled in Link.",
2758
+ linkClosed: true
2759
+ };
2760
+ case "expired":
2761
+ return {
2762
+ kind: LinkCardExpiredError,
2763
+ code: "LINK_CARD_EXPIRED",
2764
+ message: "The Link card request expired before the person approved it.",
2765
+ linkClosed: true
2766
+ };
2767
+ case "requires_action":
2768
+ return {
2769
+ kind: LinkCardError,
2770
+ code: "LINK_CARD_ACTION_REQUIRED",
2771
+ message: "Link needs the person to finish a step in Link before it can issue a card."
2772
+ };
2773
+ default:
2774
+ return {
2775
+ kind: LinkCardError,
2776
+ code: "LINK_CARD_FAILED",
2777
+ message: "Link did not issue a card for this request.",
2778
+ linkClosed: LINK_CLOSED_STATUSES.has(request.status)
2779
+ };
2780
+ }
2781
+ }
2782
+ async function closeLinkRequest(wallet, id) {
2783
+ try {
2784
+ await wallet.cancel(id);
2785
+ return true;
2786
+ } catch {
2787
+ const status = await wallet.waitForApproval(id, { timeoutSeconds: 0 }).then((request) => request.status).catch(() => void 0);
2788
+ return status !== void 0 && LINK_CLOSED_STATUSES.has(status);
2789
+ }
2790
+ }
2791
+ function linkCreatedNothing(error) {
2792
+ return errorCode(error) === "LINK_WALLET_UNAVAILABLE" || errorReason(error) === "invalid_input";
2793
+ }
2794
+ var LinkFailureSignal = class extends Error {
2795
+ constructor(failure) {
2796
+ super(failure.message);
2797
+ this.failure = failure;
2798
+ }
2799
+ };
2800
+ var _client4, _CheckoutClient_instances, linkCardFor_fn;
2489
2801
  var CheckoutClient = class {
2490
2802
  constructor(client) {
2803
+ __privateAdd(this, _CheckoutClient_instances);
2491
2804
  __privateAdd(this, _client4);
2492
2805
  __privateSet(this, _client4, client);
2493
2806
  }
@@ -2566,8 +2879,16 @@ var CheckoutClient = class {
2566
2879
  if (!Number.isSafeInteger(input.amountMinor) || input.amountMinor <= 0) {
2567
2880
  throw checkoutError("amountMinor must be a positive integer number of cents");
2568
2881
  }
2882
+ assertPaymentReference(input.paymentReference);
2569
2883
  let current = checkpoint;
2570
2884
  if (input.amountMinor !== checkpoint.amountMinor) {
2885
+ if (input.paymentReference) {
2886
+ throw new ContoError("The Link card covers the approved total, not this one. Do not pay.", {
2887
+ code: "LINK_CARD_TOTAL_CHANGED",
2888
+ status: 0,
2889
+ retryGuidance: "Call checkout.replaceLinkCard(result, { wallet, amountMinor }) for a card at the final total, then confirm the checkpoint it returns."
2890
+ });
2891
+ }
2571
2892
  try {
2572
2893
  await this.cancel(checkpoint.id);
2573
2894
  } catch (error) {
@@ -2597,7 +2918,15 @@ var CheckoutClient = class {
2597
2918
  {
2598
2919
  amountMinor: input.amountMinor,
2599
2920
  currency: "USD",
2600
- ...input.pageUrl ? { pageUrl: input.pageUrl } : {}
2921
+ ...input.lineItems !== void 0 || input.totals !== void 0 ? {
2922
+ cart: checkpointCart(
2923
+ input.amountMinor,
2924
+ input.lineItems ?? current.cart.lineItems,
2925
+ input.totals ?? current.cart.totals
2926
+ )
2927
+ } : {},
2928
+ ...input.pageUrl ? { pageUrl: input.pageUrl } : {},
2929
+ ...input.paymentReference ? { paymentReference: { provider: "LINK", id: input.paymentReference.id } } : {}
2601
2930
  },
2602
2931
  { idempotent: true }
2603
2932
  );
@@ -2612,12 +2941,14 @@ var CheckoutClient = class {
2612
2941
  }
2613
2942
  /** Report what happened after a confirmed checkpoint. Safe to repeat with the same outcome. */
2614
2943
  async reportOutcome(checkpointId, input) {
2944
+ assertPaymentReference(input.paymentReference);
2615
2945
  const result = await __privateGet(this, _client4).request(
2616
2946
  "POST",
2617
2947
  `/api/sdk/checkout-checkpoints/${encodeURIComponent(checkpointId)}/outcome`,
2618
2948
  {
2619
2949
  outcome: input.outcome,
2620
- ...input.reference ? { reference: input.reference } : {}
2950
+ ...input.reference ? { reference: input.reference } : {},
2951
+ ...input.paymentReference ? { paymentReference: { provider: "LINK", id: input.paymentReference.id } } : {}
2621
2952
  },
2622
2953
  { idempotent: true }
2623
2954
  );
@@ -2643,8 +2974,189 @@ var CheckoutClient = class {
2643
2974
  );
2644
2975
  return result.checkpoint;
2645
2976
  }
2977
+ /**
2978
+ * Get a Stripe Link card for one purchase, issued only after Conto approves
2979
+ * it. Call this at the payment step, once the final total with shipping and
2980
+ * tax is known.
2981
+ *
2982
+ * 1. Conto runs checkpoint 1 and holds the spend. When a rule requires the
2983
+ * owner's approval, this waits for it.
2984
+ * 2. Only then does the wallet ask Link for a card for exactly the approved
2985
+ * amount at this merchant. The person approves it in their Link app.
2986
+ * 3. The card is returned. It never reaches Conto.
2987
+ *
2988
+ * Then fill in the card, call confirm(result.checkpoint, { amountMinor,
2989
+ * paymentReference: result.paymentReference }) right before paying, pay only
2990
+ * if it resolves, and report the outcome. If the final total differs, call
2991
+ * replaceLinkCard() instead of confirming.
2992
+ *
2993
+ * A Conto denial throws before Link is called. When Link declines, expires,
2994
+ * times out, or is unavailable, this cancels the checkpoint to release the
2995
+ * held spend and throws a LinkCardError. When Conto cannot cancel an open Link
2996
+ * request, it keeps the hold and throws LINK_CARD_NOT_CANCELLED with the
2997
+ * request id. Retrying with the same input resumes the same checkpoint and
2998
+ * Link request.
2999
+ */
3000
+ async getLinkCard(input) {
3001
+ const { wallet, ownerApprovalTimeoutMs, linkApprovalTimeoutMs, signal, ...beginInput } = input;
3002
+ if (!wallet || typeof wallet.createCardRequest !== "function") {
3003
+ throw checkoutError("wallet must be a LinkWallet, such as linkCliWallet()");
3004
+ }
3005
+ let checkpoint = await this.begin({ ...beginInput, checkoutMethod: "LINK" });
3006
+ if (checkpoint.stage === "AWAITING_APPROVAL") {
3007
+ checkpoint = await this.waitForApproval(checkpoint, {
3008
+ ...ownerApprovalTimeoutMs !== void 0 ? { timeoutMs: ownerApprovalTimeoutMs } : {},
3009
+ ...signal ? { signal } : {}
3010
+ });
3011
+ }
3012
+ return __privateMethod(this, _CheckoutClient_instances, linkCardFor_fn).call(this, checkpoint, wallet, linkApprovalTimeoutMs, signal);
3013
+ }
3014
+ /**
3015
+ * The final total differs from the one the Link card covers. This cancels
3016
+ * the old Link request and checkpoint, begins a checkpoint at the final
3017
+ * total (waiting for the owner when a rule requires it), and gets a new card
3018
+ * for it. Confirm the returned checkpoint with the same total.
3019
+ */
3020
+ async replaceLinkCard(previous, input) {
3021
+ const { wallet, amountMinor, ownerApprovalTimeoutMs, linkApprovalTimeoutMs, signal } = input;
3022
+ if (!Number.isSafeInteger(amountMinor) || amountMinor <= 0) {
3023
+ throw checkoutError("amountMinor must be a positive integer number of cents");
3024
+ }
3025
+ if (amountMinor === previous.checkpoint.amountMinor) return previous;
3026
+ const old = previous.checkpoint;
3027
+ if (!await closeLinkRequest(wallet, previous.linkRequestId)) {
3028
+ throw new LinkCardError({
3029
+ message: "Conto could not cancel the earlier Link card. Nothing changed. Do not pay.",
3030
+ code: "LINK_CARD_NOT_CANCELLED",
3031
+ checkpoint: old,
3032
+ linkRequestId: previous.linkRequestId,
3033
+ holdReleased: false,
3034
+ retryGuidance: "Try replaceLinkCard again."
3035
+ });
3036
+ }
3037
+ try {
3038
+ await this.cancel(old.id);
3039
+ } catch (error) {
3040
+ const closed = error instanceof ContoError && error.status === 409 && ["CANCELLED", "EXPIRED", "DENIED"].includes((await this.get(old.id)).stage);
3041
+ if (!closed) throw error;
3042
+ }
3043
+ let checkpoint = await this.begin({
3044
+ idempotencyKey: `${old.idempotencyKey.slice(0, 200)}:final-${amountMinor}`,
3045
+ merchant: {
3046
+ id: old.merchant.id,
3047
+ name: old.merchant.name,
3048
+ checkoutUrl: old.merchant.checkoutUrl ?? ""
3049
+ },
3050
+ amountMinor,
3051
+ purpose: old.purpose,
3052
+ ...old.category ? { category: old.category } : {},
3053
+ checkoutMethod: "LINK",
3054
+ lineItems: input.lineItems ?? old.cart.lineItems,
3055
+ totals: input.totals
3056
+ });
3057
+ if (checkpoint.stage === "AWAITING_APPROVAL") {
3058
+ checkpoint = await this.waitForApproval(checkpoint, {
3059
+ ...ownerApprovalTimeoutMs !== void 0 ? { timeoutMs: ownerApprovalTimeoutMs } : {},
3060
+ ...signal ? { signal } : {}
3061
+ });
3062
+ }
3063
+ return __privateMethod(this, _CheckoutClient_instances, linkCardFor_fn).call(this, checkpoint, wallet, linkApprovalTimeoutMs, signal);
3064
+ }
2646
3065
  };
2647
3066
  _client4 = new WeakMap();
3067
+ _CheckoutClient_instances = new WeakSet();
3068
+ linkCardFor_fn = async function(checkpoint, wallet, linkApprovalTimeoutMs = 10 * 6e4, signal) {
3069
+ if (checkpoint.stage !== "APPROVED") {
3070
+ throw checkoutError(
3071
+ `Conto has not approved a card for this checkpoint (stage ${checkpoint.stage}). Do not pay.`,
3072
+ "CHECKOUT_CHECKPOINT_NOT_APPROVED"
3073
+ );
3074
+ }
3075
+ const deadline = Date.now() + linkApprovalTimeoutMs;
3076
+ const call = signal ? { signal } : {};
3077
+ let linkRequestId;
3078
+ let createStarted = false;
3079
+ try {
3080
+ const cardRequest = linkCardRequest(checkpoint);
3081
+ createStarted = true;
3082
+ let request = await wallet.createCardRequest(cardRequest, call);
3083
+ if (!LINK_REQUEST_ID.test(request.id)) {
3084
+ throw new LinkFailureSignal({
3085
+ kind: LinkCardError,
3086
+ code: "LINK_CARD_FAILED",
3087
+ message: "The Link wallet returned an invalid request id."
3088
+ });
3089
+ }
3090
+ linkRequestId = request.id;
3091
+ if (request.amountMinor !== void 0 && request.amountMinor !== checkpoint.amountMinor) {
3092
+ throw new LinkFailureSignal({
3093
+ kind: LinkCardError,
3094
+ code: "LINK_CARD_MISMATCH",
3095
+ message: "Link returned a request for a different amount."
3096
+ });
3097
+ }
3098
+ while (linkRequestWaiting(request)) {
3099
+ const remainingSeconds = Math.floor((deadline - Date.now()) / 1e3);
3100
+ if (remainingSeconds <= 0) {
3101
+ throw new LinkFailureSignal({
3102
+ kind: LinkCardTimeoutError,
3103
+ code: "LINK_CARD_TIMEOUT",
3104
+ message: "The person did not approve the Link card request in time."
3105
+ });
3106
+ }
3107
+ const started = Date.now();
3108
+ request = await wallet.waitForApproval(request.id, {
3109
+ ...call,
3110
+ timeoutSeconds: remainingSeconds
3111
+ });
3112
+ if (linkRequestWaiting(request) && Date.now() - started < 1e3) {
3113
+ await sleep2(1e3, signal);
3114
+ }
3115
+ }
3116
+ if (!LINK_APPROVED_STATUSES.has(request.status)) {
3117
+ throw new LinkFailureSignal(closedLinkFailure(request));
3118
+ }
3119
+ const card = await wallet.retrieveCard(request.id, call);
3120
+ return {
3121
+ checkpoint,
3122
+ card: protectLinkCard(card),
3123
+ linkRequestId: request.id,
3124
+ paymentReference: { provider: "LINK", id: request.id }
3125
+ };
3126
+ } catch (error) {
3127
+ const failure = error instanceof LinkFailureSignal ? error.failure : linkFailure(error, signal);
3128
+ if (!linkRequestId && createStarted && !linkCreatedNothing(error)) {
3129
+ throw new LinkCardError({
3130
+ message: `${failure.message} Conto could not tell whether Link created the card request, so the held spend stays in place. Do not pay.`,
3131
+ code: "LINK_CARD_NOT_CANCELLED",
3132
+ checkpoint,
3133
+ holdReleased: false,
3134
+ retryGuidance: "Retry with the same input to resume the Link request, or call checkout.cancel(error.checkpoint.id) once you know Link created none."
3135
+ });
3136
+ }
3137
+ if (linkRequestId && !failure.linkClosed && !await closeLinkRequest(wallet, linkRequestId)) {
3138
+ throw new LinkCardError({
3139
+ message: `${failure.message} Conto could not cancel the Link request, so the held spend stays in place. Do not pay.`,
3140
+ code: "LINK_CARD_NOT_CANCELLED",
3141
+ checkpoint,
3142
+ linkRequestId,
3143
+ holdReleased: false,
3144
+ retryGuidance: "Retry with the same input to resume this Link request, or cancel it with wallet.cancel(error.linkRequestId) and then call checkout.cancel(error.checkpoint.id)."
3145
+ });
3146
+ }
3147
+ const holdReleased = await this.cancel(checkpoint.id).then(
3148
+ () => true,
3149
+ () => false
3150
+ );
3151
+ throw new failure.kind({
3152
+ message: `${failure.message} ${holdReleased ? "Conto cancelled the checkpoint and released the held spend." : "Conto could not cancel the checkpoint yet."} Do not pay.`,
3153
+ code: failure.code,
3154
+ checkpoint,
3155
+ ...linkRequestId ? { linkRequestId } : {},
3156
+ holdReleased
3157
+ });
3158
+ }
3159
+ };
2648
3160
  export {
2649
3161
  AdminPurchasingClient,
2650
3162
  BrowserActionFinalizationPendingError,
@@ -2664,6 +3176,11 @@ export {
2664
3176
  ControlledExternalCardPaymentTool,
2665
3177
  ExternalCardConfirmationPendingError,
2666
3178
  Conto as Giro,
3179
+ LinkCardDeniedError,
3180
+ LinkCardError,
3181
+ LinkCardExpiredError,
3182
+ LinkCardTimeoutError,
3183
+ LinkWalletUnavailableError,
2667
3184
  OrganizationPurchasesClient,
2668
3185
  OrganizationRecurringPurchasesClient,
2669
3186
  PurchasesClient,