@delopay/sdk 0.274.0 → 0.279.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/dist/internal.cjs CHANGED
@@ -36,6 +36,7 @@ __export(internal_exports, {
36
36
  APPLE_PAY_BUTTON_STYLES: () => APPLE_PAY_BUTTON_STYLES,
37
37
  APPLE_PAY_BUTTON_TYPES: () => APPLE_PAY_BUTTON_TYPES,
38
38
  Admin: () => Admin,
39
+ AdminLive: () => AdminLive,
39
40
  AdminPortal: () => AdminPortal,
40
41
  Analytics: () => Analytics,
41
42
  AnalyticsDashboard: () => AnalyticsDashboard,
@@ -94,6 +95,8 @@ __export(internal_exports, {
94
95
  InvoiceSettingsResource: () => InvoiceSettingsResource,
95
96
  Invoices: () => Invoices,
96
97
  LOCALIZABLE_COPY_FIELDS: () => LOCALIZABLE_COPY_FIELDS,
98
+ Live: () => Live,
99
+ LiveEventStream: () => LiveEventStream,
97
100
  MAX_SECTION_LABEL_LENGTH: () => MAX_SECTION_LABEL_LENGTH,
98
101
  MAX_SECTION_ORDER: () => MAX_SECTION_ORDER,
99
102
  METHOD_SECTIONS: () => METHOD_SECTIONS,
@@ -324,6 +327,100 @@ var DelopayAuthenticationError = class extends DelopayError {
324
327
  }
325
328
  };
326
329
 
330
+ // src/eventStream.ts
331
+ var LF = 10;
332
+ var CR = 13;
333
+ var EventStreamParser = class {
334
+ /**
335
+ * @param lastEventId - The id the stream resumes after, as `EventSource`
336
+ * carries it into a reconnection: a dispatch before the server names an
337
+ * id keeps this one.
338
+ */
339
+ constructor(lastEventId = "") {
340
+ this.line = "";
341
+ /** The previous chunk ended in CR: a LF opening the next one belongs to it. */
342
+ this.skipLf = false;
343
+ this.data = "";
344
+ this.hasData = false;
345
+ this.eventType = "";
346
+ this.retry = null;
347
+ this.idBuffer = lastEventId;
348
+ }
349
+ /** Feed the next piece of decoded text; returns the dispatches it completed. */
350
+ push(text) {
351
+ const out = [];
352
+ if (text.length === 0) return out;
353
+ let start = 0;
354
+ if (this.skipLf) {
355
+ this.skipLf = false;
356
+ if (text.charCodeAt(0) === LF) start = 1;
357
+ }
358
+ for (let i = start; i < text.length; i++) {
359
+ const c = text.charCodeAt(i);
360
+ if (c !== LF && c !== CR) continue;
361
+ const line = this.line + text.slice(start, i);
362
+ this.line = "";
363
+ this.processLine(line, out);
364
+ if (c === CR) {
365
+ if (i + 1 < text.length) {
366
+ if (text.charCodeAt(i + 1) === LF) i++;
367
+ } else {
368
+ this.skipLf = true;
369
+ }
370
+ }
371
+ start = i + 1;
372
+ }
373
+ this.line += text.slice(start);
374
+ return out;
375
+ }
376
+ processLine(line, out) {
377
+ if (line === "") {
378
+ this.dispatch(out);
379
+ return;
380
+ }
381
+ if (line.charCodeAt(0) === 58) return;
382
+ const colon = line.indexOf(":");
383
+ let field;
384
+ let value;
385
+ if (colon === -1) {
386
+ field = line;
387
+ value = "";
388
+ } else {
389
+ field = line.slice(0, colon);
390
+ value = line.slice(colon + 1);
391
+ if (value.charCodeAt(0) === 32) value = value.slice(1);
392
+ }
393
+ switch (field) {
394
+ case "event":
395
+ this.eventType = value;
396
+ break;
397
+ case "data":
398
+ this.data = this.hasData ? `${this.data}
399
+ ${value}` : value;
400
+ this.hasData = true;
401
+ break;
402
+ case "id":
403
+ if (!value.includes("\0")) this.idBuffer = value;
404
+ break;
405
+ case "retry":
406
+ if (/^[0-9]+$/.test(value)) {
407
+ const ms = Number(value);
408
+ if (Number.isSafeInteger(ms)) this.retry = ms;
409
+ }
410
+ break;
411
+ default:
412
+ break;
413
+ }
414
+ }
415
+ dispatch(out) {
416
+ const event = this.hasData ? { type: this.eventType || "message", data: this.data } : null;
417
+ out.push({ lastEventId: this.idBuffer, retry: this.retry, event });
418
+ this.data = "";
419
+ this.hasData = false;
420
+ this.eventType = "";
421
+ }
422
+ };
423
+
327
424
  // src/resources/apiKeys.ts
328
425
  var ApiKeys = class {
329
426
  constructor(request) {
@@ -927,6 +1024,23 @@ var Connectors = class {
927
1024
  { body: params }
928
1025
  );
929
1026
  }
1027
+ /**
1028
+ * Fold copies of the same provider account into this connector (todos#395).
1029
+ * `POST /account/{accountId}/connectors/{connectorId}/consolidate`
1030
+ *
1031
+ * The copies' shops move to the connector with their on/off state, routing,
1032
+ * checkout layout, currencies, saved credentials, mandates and
1033
+ * subscriptions. A copy keeps answering for the payments made on it and
1034
+ * serves no shop. Send `dry_run: true` first, then confirm with the
1035
+ * preview's `preview_token` and a choice for every conflict.
1036
+ */
1037
+ async consolidate(accountId, connectorId, params) {
1038
+ return this.request(
1039
+ "POST",
1040
+ `/account/${encodeURIComponent(accountId)}/connectors/${encodeURIComponent(connectorId)}/consolidate`,
1041
+ { body: params }
1042
+ );
1043
+ }
930
1044
  /**
931
1045
  * Switch a connector off, or back on, in one shop it serves.
932
1046
  * `POST /account/{accountId}/connectors/{connectorId}/shops/{profileId}`
@@ -1552,8 +1666,8 @@ var Customers = class {
1552
1666
  };
1553
1667
 
1554
1668
  // src/recordCounter.ts
1555
- var LF = 10;
1556
- var CR = 13;
1669
+ var LF2 = 10;
1670
+ var CR2 = 13;
1557
1671
  var QUOTE = 34;
1558
1672
  var BACKSLASH = 92;
1559
1673
  var OPEN_BRACE = 123;
@@ -1577,10 +1691,10 @@ var CsvRecordCounter = class {
1577
1691
  lineHasContent = true;
1578
1692
  } else if (inQuotes) {
1579
1693
  lineHasContent = true;
1580
- } else if (byte === LF) {
1694
+ } else if (byte === LF2) {
1581
1695
  newlines++;
1582
1696
  lineHasContent = false;
1583
- } else if (byte !== CR) {
1697
+ } else if (byte !== CR2) {
1584
1698
  lineHasContent = true;
1585
1699
  }
1586
1700
  }
@@ -6070,6 +6184,55 @@ var BuyerConversations = class {
6070
6184
  body: params
6071
6185
  });
6072
6186
  }
6187
+ /**
6188
+ * A team member's internal note. Only the team reads it: the buyer never
6189
+ * sees a note, and a note does not move the conversation or mark it unread.
6190
+ * A closed conversation takes notes as well.
6191
+ * `POST /buyer-conversations/{id}/notes`
6192
+ */
6193
+ async addNote(id, params) {
6194
+ return this.request("POST", `/buyer-conversations/${encodeURIComponent(id)}/notes`, {
6195
+ body: params
6196
+ });
6197
+ }
6198
+ /**
6199
+ * Upload a file for the caller's next answer, under the shop's attachment
6200
+ * rules (`attachment_rules` on the conversation). It belongs to the caller
6201
+ * until an answer names it in `attachments`; one no answer took within a
6202
+ * day is cleared. Uploading again with the same `clientUploadId` returns
6203
+ * the file the first upload stored.
6204
+ * `POST /buyer-conversation-files/{conversation}`
6205
+ */
6206
+ async uploadFile(id, file, clientUploadId, fileName) {
6207
+ const form = new FormData();
6208
+ form.append("client_upload_id", clientUploadId);
6209
+ if (fileName === void 0) form.append("file", file);
6210
+ else form.append("file", file, fileName);
6211
+ return this.request("POST", `/buyer-conversation-files/${encodeURIComponent(id)}`, {
6212
+ body: form
6213
+ });
6214
+ }
6215
+ /**
6216
+ * Download a file a message of the conversation carries.
6217
+ * `GET /buyer-conversation-files/{conversation}/{file}`
6218
+ */
6219
+ async downloadFile(id, fileId) {
6220
+ return this.request(
6221
+ "GET",
6222
+ `/buyer-conversation-files/${encodeURIComponent(id)}/${encodeURIComponent(fileId)}`,
6223
+ { responseType: "blob" }
6224
+ );
6225
+ }
6226
+ /**
6227
+ * Remove a file the caller uploaded that no answer took.
6228
+ * `DELETE /buyer-conversation-files/{conversation}/{file}`
6229
+ */
6230
+ async removeFile(id, fileId) {
6231
+ return this.request(
6232
+ "DELETE",
6233
+ `/buyer-conversation-files/${encodeURIComponent(id)}/${encodeURIComponent(fileId)}`
6234
+ );
6235
+ }
6073
6236
  /**
6074
6237
  * The team has read the conversation up to its last accepted message.
6075
6238
  * `POST /buyer-conversations/{id}/read`
@@ -7886,6 +8049,53 @@ var BuyerAccount = class {
7886
8049
  }
7887
8050
  );
7888
8051
  }
8052
+ /**
8053
+ * Upload a file for the buyer's next message to one shop of a confirmed
8054
+ * record, under the shop's attachment rules (`attachment_rules` on the
8055
+ * message page). It belongs to the buyer until a message names it in
8056
+ * `attachments`; one no message took within a day is cleared. Uploading
8057
+ * again with the same `clientUploadId` returns the file the first upload
8058
+ * stored. `shop` is required here.
8059
+ */
8060
+ async uploadRecordMessageFile(record, file, clientUploadId, query, options) {
8061
+ const { fileName, ...extras } = options ?? {};
8062
+ const form = new FormData();
8063
+ form.append("client_upload_id", clientUploadId);
8064
+ if (fileName === void 0) form.append("file", file);
8065
+ else form.append("file", file, fileName);
8066
+ return this.request(
8067
+ "POST",
8068
+ `/buyer-account/records/${encodeURIComponent(record)}/messages/files`,
8069
+ {
8070
+ body: form,
8071
+ query,
8072
+ ...extras
8073
+ }
8074
+ );
8075
+ }
8076
+ /** Download a file a message of a record's conversation with one shop carries. */
8077
+ async downloadRecordMessageFile(record, fileId, query, options) {
8078
+ return this.request(
8079
+ "GET",
8080
+ `/buyer-account/records/${encodeURIComponent(record)}/messages/files/${encodeURIComponent(fileId)}`,
8081
+ {
8082
+ query,
8083
+ responseType: "blob",
8084
+ ...options
8085
+ }
8086
+ );
8087
+ }
8088
+ /** Remove a file the buyer uploaded for a record's conversation that no message took. */
8089
+ async removeRecordMessageFile(record, fileId, query, options) {
8090
+ return this.request(
8091
+ "DELETE",
8092
+ `/buyer-account/records/${encodeURIComponent(record)}/messages/files/${encodeURIComponent(fileId)}`,
8093
+ {
8094
+ query,
8095
+ ...options
8096
+ }
8097
+ );
8098
+ }
7889
8099
  /**
7890
8100
  * What the buyer spent in a period: paid purchases summed per currency,
7891
8101
  * never converted, for the whole period, per day, week or month, per shop
@@ -8108,6 +8318,40 @@ var BuyerPortal = class {
8108
8318
  ...options
8109
8319
  });
8110
8320
  }
8321
+ /**
8322
+ * Upload a file for the buyer's next message to one shop, under the shop's
8323
+ * attachment rules (`attachment_rules` on the message page). It belongs to
8324
+ * the buyer until a message names it in `attachments`; one no message took
8325
+ * within a day is cleared. Uploading again with the same `clientUploadId`
8326
+ * returns the file the first upload stored.
8327
+ */
8328
+ async uploadMessageFile(file, clientUploadId, query, options) {
8329
+ const { fileName, ...extras } = options ?? {};
8330
+ const form = new FormData();
8331
+ form.append("client_upload_id", clientUploadId);
8332
+ if (fileName === void 0) form.append("file", file);
8333
+ else form.append("file", file, fileName);
8334
+ return this.request("POST", "/buyer-portal/messages/files", {
8335
+ body: form,
8336
+ query,
8337
+ ...extras
8338
+ });
8339
+ }
8340
+ /** Download a file a message of the buyer's conversation with one shop carries. */
8341
+ async downloadMessageFile(fileId, query, options) {
8342
+ return this.request("GET", `/buyer-portal/messages/files/${encodeURIComponent(fileId)}`, {
8343
+ query,
8344
+ responseType: "blob",
8345
+ ...options
8346
+ });
8347
+ }
8348
+ /** Remove a file the buyer uploaded that no message took. */
8349
+ async removeMessageFile(fileId, query, options) {
8350
+ return this.request("DELETE", `/buyer-portal/messages/files/${encodeURIComponent(fileId)}`, {
8351
+ query,
8352
+ ...options
8353
+ });
8354
+ }
8111
8355
  /** The buyer's contact and billing details, and what they may change. */
8112
8356
  async getProfile(options) {
8113
8357
  return this.request("GET", "/buyer-portal/profile", { ...options });
@@ -8984,6 +9228,133 @@ var Risk = class {
8984
9228
  }
8985
9229
  };
8986
9230
 
9231
+ // src/resources/live.ts
9232
+ function readField(data, key) {
9233
+ let value;
9234
+ try {
9235
+ value = JSON.parse(data);
9236
+ } catch {
9237
+ return void 0;
9238
+ }
9239
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
9240
+ return Object.getOwnPropertyDescriptor(value, key)?.value;
9241
+ }
9242
+ function toLiveStreamEvent(event, id, retry) {
9243
+ switch (event.type) {
9244
+ case "ready": {
9245
+ const resumed = readField(event.data, "resumed");
9246
+ return { type: "ready", id, retry, resumed: typeof resumed === "boolean" ? resumed : null };
9247
+ }
9248
+ case "change": {
9249
+ const changes = readField(event.data, "changes");
9250
+ if (!Array.isArray(changes)) return { type: "resync", id };
9251
+ return { type: "change", id, changes };
9252
+ }
9253
+ case "resync":
9254
+ return { type: "resync", id };
9255
+ default:
9256
+ return null;
9257
+ }
9258
+ }
9259
+ var LiveEventStream = class {
9260
+ constructor(connection, lastEventId = null) {
9261
+ this.connection = connection;
9262
+ this._retry = null;
9263
+ this._lastEventId = lastEventId || null;
9264
+ }
9265
+ /**
9266
+ * The position to resume after: the id of the last event read, advanced by
9267
+ * keepalives too. `null` before the server named one. Send it as
9268
+ * `lastEventId` when reconnecting.
9269
+ */
9270
+ get lastEventId() {
9271
+ return this._lastEventId;
9272
+ }
9273
+ /** The wait before reconnecting the server asked for, in ms; `null` until it says. */
9274
+ get retry() {
9275
+ return this._retry;
9276
+ }
9277
+ /** Close the stream; the iteration ends without an error. */
9278
+ close() {
9279
+ this.connection.close();
9280
+ }
9281
+ [Symbol.asyncIterator]() {
9282
+ this.iterator ?? (this.iterator = this.events());
9283
+ return this.iterator;
9284
+ }
9285
+ async *events() {
9286
+ for await (const dispatch of this.connection.dispatches) {
9287
+ const event = this.read(dispatch);
9288
+ if (event) yield event;
9289
+ }
9290
+ }
9291
+ read(dispatch) {
9292
+ this._lastEventId = dispatch.lastEventId || null;
9293
+ if (dispatch.retry !== null) this._retry = dispatch.retry;
9294
+ if (!dispatch.event) return null;
9295
+ return toLiveStreamEvent(dispatch.event, this._lastEventId, this._retry);
9296
+ }
9297
+ };
9298
+ async function openLiveStream(openStream, path, options = {}) {
9299
+ const connection = await openStream(path, {
9300
+ ...options.lastEventId ? { lastEventId: options.lastEventId } : {},
9301
+ ...options.signal ? { signal: options.signal } : {},
9302
+ ...options.idleTimeoutMs !== void 0 ? { idleTimeoutMs: options.idleTimeoutMs } : {},
9303
+ ...options.headers ? { headers: options.headers } : {}
9304
+ });
9305
+ return new LiveEventStream(connection, options.lastEventId ?? null);
9306
+ }
9307
+ var Live = class {
9308
+ constructor(request, openStream) {
9309
+ this.request = request;
9310
+ this.openStream = openStream;
9311
+ }
9312
+ /**
9313
+ * Open the stream of what changed in the caller's merchant, as their role
9314
+ * may read it. Resolves once the server answered; a `401` rejects with
9315
+ * `DelopayAuthenticationError`.
9316
+ *
9317
+ * The first event is `ready`. `change` names the kinds of record and, when
9318
+ * few, the ids that changed: read them again through the usual endpoints.
9319
+ * `resync`, and `ready` with `resumed: false`, mean read everything again.
9320
+ * The SDK does not reconnect — see {@link LiveEventStream}.
9321
+ *
9322
+ * `GET /live/stream`
9323
+ *
9324
+ * @example
9325
+ * ```typescript
9326
+ * const stream = await delopay.live.stream({ lastEventId, signal });
9327
+ * for await (const event of stream) {
9328
+ * if (event.type === 'change') refresh(event.changes);
9329
+ * else if (event.type === 'resync' || event.resumed === false) refreshAll();
9330
+ * }
9331
+ * lastEventId = stream.lastEventId; // reconnect after stream.retry
9332
+ * ```
9333
+ */
9334
+ async stream(options) {
9335
+ return openLiveStream(this.openStream, "/live/stream", options);
9336
+ }
9337
+ /**
9338
+ * The current version of each kind of record named, in the caller's
9339
+ * merchant and shop. Read it before the record and send the entry's
9340
+ * `if_match` in the `If-Match` header of the save: a save over a newer
9341
+ * version is refused with `IR_16` (400), `error.data` a
9342
+ * `LiveChangedElsewhere` naming who made the change.
9343
+ *
9344
+ * `GET /live/versions`
9345
+ */
9346
+ async versions(params, options) {
9347
+ return this.request("GET", "/live/versions", {
9348
+ query: {
9349
+ entities: params.entities.join(","),
9350
+ profile_id: params.profile_id,
9351
+ record_id: params.record_id
9352
+ },
9353
+ ...options
9354
+ });
9355
+ }
9356
+ };
9357
+
8987
9358
  // src/client.ts
8988
9359
  var PRODUCTION_URL = "https://api.delopay.net";
8989
9360
  var SANDBOX_URL = "https://sandbox.delopay.net";
@@ -9007,6 +9378,40 @@ function truncateRawBody(raw) {
9007
9378
  if (!raw) return void 0;
9008
9379
  return raw.length > MAX_RAW_BODY_BYTES ? raw.slice(0, MAX_RAW_BODY_BYTES) + "\u2026" : raw;
9009
9380
  }
9381
+ async function errorFromResponse(response, requestId) {
9382
+ const rawBody = await response.text().catch(() => "");
9383
+ let parsed = {};
9384
+ if (rawBody) {
9385
+ try {
9386
+ parsed = JSON.parse(rawBody);
9387
+ } catch {
9388
+ }
9389
+ }
9390
+ const err = parsed.error ?? parsed;
9391
+ const message = err.message ?? `Request failed with status ${response.status}`;
9392
+ const code = err.code ?? "";
9393
+ const type = err.error_type ?? err.type ?? "";
9394
+ const data = err.data && typeof err.data === "object" && !Array.isArray(err.data) ? err.data : void 0;
9395
+ const truncatedRaw = truncateRawBody(rawBody);
9396
+ const isConnectorPassthrough = type === "connector" || code.startsWith("CE_");
9397
+ if (response.status === 401 && !isConnectorPassthrough) {
9398
+ return new DelopayAuthenticationError(message, {
9399
+ code,
9400
+ type,
9401
+ requestId,
9402
+ rawBody: truncatedRaw,
9403
+ data
9404
+ });
9405
+ }
9406
+ return new DelopayError(message, {
9407
+ status: response.status,
9408
+ code,
9409
+ type,
9410
+ requestId,
9411
+ rawBody: truncatedRaw,
9412
+ data
9413
+ });
9414
+ }
9010
9415
  function findIdempotencyKey(headers) {
9011
9416
  for (const [k, v] of Object.entries(headers)) {
9012
9417
  if (k.toLowerCase() === "idempotency-key") return v;
@@ -9167,6 +9572,7 @@ function redactUrlForLogging(url) {
9167
9572
  });
9168
9573
  return `${base}?${parts.join("&")}`;
9169
9574
  }
9575
+ var DEFAULT_STREAM_IDLE_TIMEOUT_MS = 45e3;
9170
9576
  var Delopay = class {
9171
9577
  /**
9172
9578
  * Create a new Delopay client.
@@ -9189,6 +9595,7 @@ var Delopay = class {
9189
9595
  this.baseUrl = PRODUCTION_URL;
9190
9596
  }
9191
9597
  const request = this.request.bind(this);
9598
+ const openStream = this.openEventStream.bind(this);
9192
9599
  this.payments = new Payments(request);
9193
9600
  this.refunds = new Refunds(request);
9194
9601
  this.customers = new Customers(request);
@@ -9225,6 +9632,7 @@ var Delopay = class {
9225
9632
  this.settings = new Settings(request);
9226
9633
  this.messageTemplates = new MessageTemplates(request);
9227
9634
  this.risk = new Risk(request);
9635
+ this.live = new Live(request, openStream);
9228
9636
  this.subscriptions = new Subscriptions(request);
9229
9637
  this.buyerPortal = new BuyerPortal(request);
9230
9638
  this.buyerAccount = new BuyerAccount(request);
@@ -9301,24 +9709,12 @@ var Delopay = class {
9301
9709
  this.setJwtToken(response.token);
9302
9710
  return response;
9303
9711
  }
9304
- /**
9305
- * Make a raw HTTP request to the Delopay API.
9306
- *
9307
- * You rarely need to call this directly — prefer the typed resource methods.
9308
- * Use it only for endpoints not yet covered by a resource class.
9309
- *
9310
- * @param method - HTTP method (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`).
9311
- * @param path - API path starting with `/` (e.g. `/payments`).
9312
- * @param options - Optional body, query parameters, and headers.
9313
- * @returns Parsed JSON response body typed as `T`.
9314
- * @throws {DelopayAuthenticationError} On 401 responses.
9315
- * @throws {DelopayError} On all other non-2xx responses, timeouts, and network errors.
9316
- */
9317
- async request(method, path, options) {
9712
+ /** `path` on the base URL, with the query string `query` makes. */
9713
+ buildUrl(path, query) {
9318
9714
  let url = `${this.baseUrl}${path}`;
9319
- if (options?.query) {
9715
+ if (query) {
9320
9716
  const params = new URLSearchParams();
9321
- for (const [key, value] of Object.entries(options.query)) {
9717
+ for (const [key, value] of Object.entries(query)) {
9322
9718
  if (value === void 0 || value === null) continue;
9323
9719
  if (Array.isArray(value)) {
9324
9720
  for (const v of value) {
@@ -9333,8 +9729,189 @@ var Delopay = class {
9333
9729
  url += `?${qs}`;
9334
9730
  }
9335
9731
  }
9732
+ return url;
9733
+ }
9734
+ /** The credential header: the JWT when one is set, else the API key. */
9735
+ authHeaders() {
9736
+ if (this.jwtToken) return { Authorization: `Bearer ${this.jwtToken}` };
9737
+ if (this.apiKey) return { "api-key": this.apiKey };
9738
+ return {};
9739
+ }
9740
+ /** One debug event, when `debug` is on. */
9741
+ log(event, data) {
9742
+ if (!this.debug) return;
9743
+ if (this.logger) {
9744
+ this.logger(event, data);
9745
+ return;
9746
+ }
9747
+ if (event === "request")
9748
+ console.log(`[delopay] ${data.method} ${data.url}`);
9749
+ else if (event === "response")
9750
+ console.log(
9751
+ `[delopay] ${data.status} ${data.method} ${data.path}`
9752
+ );
9753
+ else
9754
+ console.log(
9755
+ `[delopay] retry ${data.attempt}/${data.maxRetries} ${data.method} ${data.path}`
9756
+ );
9757
+ }
9758
+ /**
9759
+ * Open a `GET` `text/event-stream` and read it as it arrives.
9760
+ *
9761
+ * `request()` keeps every chunk of a body until the body ends, which a
9762
+ * stream that stays open for half an hour must not do; this reads the body
9763
+ * chunk by chunk through {@link EventStreamParser} and keeps nothing it has
9764
+ * dispatched. Credentials, the base URL, debug logging and the mapping of a
9765
+ * non-2xx answer to `DelopayError` / `DelopayAuthenticationError` are the
9766
+ * ones `request()` uses.
9767
+ *
9768
+ * Never retried, and never reconnected: the caller owns reconnection.
9769
+ * Resolves once the response headers arrive; rejects on a non-2xx answer,
9770
+ * on a 2xx that is not `text/event-stream` (code `NOT_EVENT_STREAM`), and
9771
+ * with `TIMEOUT`, `NETWORK` or `ABORTED` like `request()`.
9772
+ */
9773
+ async openEventStream(path, options = {}) {
9774
+ const url = this.buildUrl(path, options.query);
9775
+ const lastEventId = options.lastEventId ?? "";
9776
+ const headers = {
9777
+ ...this.authHeaders(),
9778
+ Accept: "text/event-stream",
9779
+ ...lastEventId ? { "Last-Event-ID": lastEventId } : {},
9780
+ ...options.headers
9781
+ };
9782
+ const idleMs = options.idleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS;
9783
+ const callerSignal = options.signal;
9784
+ const aborted = () => new DelopayError("Request aborted", { status: 0, code: "ABORTED", type: "abort_error" });
9785
+ if (callerSignal?.aborted) throw aborted();
9786
+ const idleCtrl = new AbortController();
9787
+ const closeCtrl = new AbortController();
9788
+ let timer;
9789
+ const stopIdleTimer = () => {
9790
+ if (timer !== void 0) clearTimeout(timer);
9791
+ timer = void 0;
9792
+ };
9793
+ const startIdleTimer = () => {
9794
+ stopIdleTimer();
9795
+ if (!idleCtrl.signal.aborted) timer = setTimeout(() => idleCtrl.abort(), idleMs);
9796
+ };
9797
+ const combined = combineSignals(
9798
+ callerSignal ? [idleCtrl.signal, closeCtrl.signal, callerSignal] : [idleCtrl.signal, closeCtrl.signal]
9799
+ );
9800
+ const release = () => {
9801
+ stopIdleTimer();
9802
+ combined.dispose();
9803
+ };
9804
+ const timedOut = () => new DelopayError(`Event stream silent for ${idleMs} ms`, {
9805
+ status: 0,
9806
+ code: "TIMEOUT",
9807
+ type: "timeout_error"
9808
+ });
9809
+ const network = (cause) => new DelopayError(
9810
+ `Network error: ${cause instanceof Error ? cause.message : String(cause ?? "stream failed")}`,
9811
+ { status: 0, code: "NETWORK", type: "network_error" }
9812
+ );
9813
+ this.log("request", { method: "GET", url: redactUrlForLogging(url), path });
9814
+ startIdleTimer();
9815
+ let response;
9816
+ try {
9817
+ response = await fetch(url, { method: "GET", headers, signal: combined.signal });
9818
+ } catch (err) {
9819
+ release();
9820
+ if (callerSignal?.aborted) throw aborted();
9821
+ if (idleCtrl.signal.aborted) throw timedOut();
9822
+ throw network(err);
9823
+ }
9824
+ const requestId = response.headers?.get("x-request-id") ?? response.headers?.get("x-trace-id") ?? void 0;
9825
+ this.log("response", { status: response.status, method: "GET", path, requestId });
9826
+ if (!response.ok) {
9827
+ const error = await errorFromResponse(response, requestId);
9828
+ release();
9829
+ throw error;
9830
+ }
9831
+ const body = response.body;
9832
+ const contentType = response.headers?.get("content-type") ?? "";
9833
+ const mediaType = (contentType.split(";")[0] ?? "").trim().toLowerCase();
9834
+ if (mediaType !== "text/event-stream" || !body || typeof body.getReader !== "function") {
9835
+ release();
9836
+ body?.cancel().catch(noop);
9837
+ throw new DelopayError(
9838
+ mediaType === "text/event-stream" ? "The event stream has no readable body" : `Expected a text/event-stream response, got ${contentType ? `"${contentType}"` : "no content type"}`,
9839
+ {
9840
+ status: response.status,
9841
+ code: "NOT_EVENT_STREAM",
9842
+ type: "invalid_response",
9843
+ requestId
9844
+ }
9845
+ );
9846
+ }
9847
+ stopIdleTimer();
9848
+ const reader = body.getReader();
9849
+ const parser = new EventStreamParser(lastEventId);
9850
+ const decoder = new TextDecoder();
9851
+ const stopped = () => Boolean(callerSignal?.aborted) || closeCtrl.signal.aborted;
9852
+ let finished = false;
9853
+ const finish = () => {
9854
+ if (finished) return;
9855
+ finished = true;
9856
+ release();
9857
+ reader.cancel().catch(noop);
9858
+ };
9859
+ async function* dispatches() {
9860
+ try {
9861
+ for (; ; ) {
9862
+ let result;
9863
+ startIdleTimer();
9864
+ try {
9865
+ result = await readChunk(reader, combined.signal);
9866
+ } catch (err) {
9867
+ if (callerSignal?.aborted || closeCtrl.signal.aborted) return;
9868
+ if (idleCtrl.signal.aborted) throw timedOut();
9869
+ throw network(err instanceof BodyStreamFailure ? err.cause : err);
9870
+ } finally {
9871
+ stopIdleTimer();
9872
+ }
9873
+ if (result.done) {
9874
+ for (const dispatch of parser.push(decoder.decode())) {
9875
+ if (stopped()) return;
9876
+ yield dispatch;
9877
+ }
9878
+ return;
9879
+ }
9880
+ if (!result.value || result.value.byteLength === 0) continue;
9881
+ for (const dispatch of parser.push(decoder.decode(result.value, { stream: true }))) {
9882
+ if (stopped()) return;
9883
+ yield dispatch;
9884
+ }
9885
+ }
9886
+ } finally {
9887
+ finish();
9888
+ }
9889
+ }
9890
+ return {
9891
+ dispatches: dispatches(),
9892
+ close: () => {
9893
+ closeCtrl.abort();
9894
+ finish();
9895
+ }
9896
+ };
9897
+ }
9898
+ /**
9899
+ * Make a raw HTTP request to the Delopay API.
9900
+ *
9901
+ * You rarely need to call this directly — prefer the typed resource methods.
9902
+ * Use it only for endpoints not yet covered by a resource class.
9903
+ *
9904
+ * @param method - HTTP method (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`).
9905
+ * @param path - API path starting with `/` (e.g. `/payments`).
9906
+ * @param options - Optional body, query parameters, and headers.
9907
+ * @returns Parsed JSON response body typed as `T`.
9908
+ * @throws {DelopayAuthenticationError} On 401 responses.
9909
+ * @throws {DelopayError} On all other non-2xx responses, timeouts, and network errors.
9910
+ */
9911
+ async request(method, path, options) {
9912
+ const url = this.buildUrl(path, options?.query);
9336
9913
  let headers = {
9337
- ...this.jwtToken ? { Authorization: `Bearer ${this.jwtToken}` } : this.apiKey ? { "api-key": this.apiKey } : {},
9914
+ ...this.authHeaders(),
9338
9915
  ...options?.headers
9339
9916
  };
9340
9917
  const isRawBody = options?.body !== void 0 && options?.body !== null && (options.body instanceof FormData || options.body instanceof Blob || options.body instanceof ArrayBuffer || options.body instanceof URLSearchParams);
@@ -9387,23 +9964,7 @@ var Delopay = class {
9387
9964
  let lastError;
9388
9965
  let retryAfterOverrideMs = null;
9389
9966
  const safeUrl = () => redactUrlForLogging(url);
9390
- const emit = (event, data) => {
9391
- if (!this.debug) return;
9392
- if (this.logger) {
9393
- this.logger(event, data);
9394
- return;
9395
- }
9396
- if (event === "request")
9397
- console.log(`[delopay] ${data.method} ${data.url}`);
9398
- else if (event === "response")
9399
- console.log(
9400
- `[delopay] ${data.status} ${data.method} ${data.path}`
9401
- );
9402
- else
9403
- console.log(
9404
- `[delopay] retry ${data.attempt}/${data.maxRetries} ${data.method} ${data.path}`
9405
- );
9406
- };
9967
+ const emit = (event, data) => this.log(event, data);
9407
9968
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
9408
9969
  if (attempt > 0) {
9409
9970
  const base = Math.min(500 * 2 ** (attempt - 1), 5e3);
@@ -9435,38 +9996,7 @@ var Delopay = class {
9435
9996
  const requestId = response.headers?.get("x-request-id") ?? response.headers?.get("x-trace-id") ?? void 0;
9436
9997
  emit("response", { status: response.status, method, path, requestId });
9437
9998
  if (!response.ok) {
9438
- const rawBody = await response.text().catch(() => "");
9439
- let parsed = {};
9440
- if (rawBody) {
9441
- try {
9442
- parsed = JSON.parse(rawBody);
9443
- } catch {
9444
- }
9445
- }
9446
- const err = parsed.error ?? parsed;
9447
- const message = err.message ?? `Request failed with status ${response.status}`;
9448
- const code = err.code ?? "";
9449
- const type = err.error_type ?? err.type ?? "";
9450
- const data = err.data && typeof err.data === "object" && !Array.isArray(err.data) ? err.data : void 0;
9451
- const truncatedRaw = truncateRawBody(rawBody);
9452
- const isConnectorPassthrough = type === "connector" || code.startsWith("CE_");
9453
- if (response.status === 401 && !isConnectorPassthrough) {
9454
- throw new DelopayAuthenticationError(message, {
9455
- code,
9456
- type,
9457
- requestId,
9458
- rawBody: truncatedRaw,
9459
- data
9460
- });
9461
- }
9462
- const error = new DelopayError(message, {
9463
- status: response.status,
9464
- code,
9465
- type,
9466
- requestId,
9467
- rawBody: truncatedRaw,
9468
- data
9469
- });
9999
+ const error = await errorFromResponse(response, requestId);
9470
10000
  const isTransientStatus = response.status >= 500 || response.status === 429;
9471
10001
  if (isTransientStatus && isRetryable && attempt < this.maxRetries) {
9472
10002
  if (response.status === 429) {
@@ -10934,6 +11464,13 @@ var DEFAULT_BRANDING_BASE = {
10934
11464
  paypalFocusRing: "strong",
10935
11465
  mollieFocusRing: "strong",
10936
11466
  paypalValidTint: false,
11467
+ epayoutsCardLayout: "split",
11468
+ epayoutsLabelStyle: "above",
11469
+ epayoutsFieldChrome: "outlined",
11470
+ epayoutsFieldFontSize: "md",
11471
+ epayoutsFieldWeight: "regular",
11472
+ epayoutsFocusRing: "strong",
11473
+ epayoutsValidTint: false,
10937
11474
  nomupayFormStyle: "plain",
10938
11475
  nomupayShowLabels: true,
10939
11476
  nomupayShowPlaceholders: true,
@@ -11964,6 +12501,66 @@ function decodeBranding(source) {
11964
12501
  DEFAULT_BRANDING.whopSelection
11965
12502
  ),
11966
12503
  paypalValidTint: parseBool(extras["paypalValidTint"], DEFAULT_BRANDING.paypalValidTint),
12504
+ // A look stored before todos#412 has no e-Payouts keys: the form keeps
12505
+ // the PayPal values it was drawn with until then.
12506
+ epayoutsCardLayout: pickEnum(
12507
+ extras["epayoutsCardLayout"],
12508
+ PAYPAL_CARD_LAYOUTS,
12509
+ pickEnum(
12510
+ extras["paypalCardLayout"],
12511
+ PAYPAL_CARD_LAYOUTS,
12512
+ DEFAULT_BRANDING.epayoutsCardLayout
12513
+ )
12514
+ ),
12515
+ epayoutsLabelStyle: pickEnum(
12516
+ extras["epayoutsLabelStyle"],
12517
+ PAYPAL_LABEL_STYLES,
12518
+ pickEnum(
12519
+ extras["paypalLabelStyle"],
12520
+ PAYPAL_LABEL_STYLES,
12521
+ DEFAULT_BRANDING.epayoutsLabelStyle
12522
+ )
12523
+ ),
12524
+ epayoutsFieldChrome: pickEnum(
12525
+ extras["epayoutsFieldChrome"],
12526
+ CARD_FIELD_CHROMES,
12527
+ pickEnum(
12528
+ extras["paypalFieldChrome"],
12529
+ CARD_FIELD_CHROMES,
12530
+ DEFAULT_BRANDING.epayoutsFieldChrome
12531
+ )
12532
+ ),
12533
+ epayoutsFieldFontSize: pickEnum(
12534
+ extras["epayoutsFieldFontSize"],
12535
+ CARD_FIELD_FONT_SIZES,
12536
+ pickEnum(
12537
+ extras["paypalFieldFontSize"],
12538
+ CARD_FIELD_FONT_SIZES,
12539
+ DEFAULT_BRANDING.epayoutsFieldFontSize
12540
+ )
12541
+ ),
12542
+ epayoutsFieldWeight: pickEnum(
12543
+ extras["epayoutsFieldWeight"],
12544
+ CARD_FIELD_WEIGHTS,
12545
+ pickEnum(
12546
+ extras["paypalFieldWeight"],
12547
+ CARD_FIELD_WEIGHTS,
12548
+ DEFAULT_BRANDING.epayoutsFieldWeight
12549
+ )
12550
+ ),
12551
+ epayoutsFocusRing: pickEnum(
12552
+ extras["epayoutsFocusRing"],
12553
+ CARD_FOCUS_RINGS,
12554
+ pickEnum(
12555
+ extras["paypalFocusRing"],
12556
+ CARD_FOCUS_RINGS,
12557
+ DEFAULT_BRANDING.epayoutsFocusRing
12558
+ )
12559
+ ),
12560
+ epayoutsValidTint: parseBool(
12561
+ extras["epayoutsValidTint"],
12562
+ parseBool(extras["paypalValidTint"], DEFAULT_BRANDING.epayoutsValidTint)
12563
+ ),
11967
12564
  nomupayFormStyle: pickEnum(
11968
12565
  extras["nomupayFormStyle"],
11969
12566
  NOMUPAY_FORM_STYLES,
@@ -12125,6 +12722,13 @@ function encodeBranding(branding, base) {
12125
12722
  whopMethodIcons: String(branding.whopMethodIcons),
12126
12723
  whopSelection: branding.whopSelection,
12127
12724
  paypalValidTint: String(branding.paypalValidTint),
12725
+ epayoutsCardLayout: branding.epayoutsCardLayout,
12726
+ epayoutsLabelStyle: branding.epayoutsLabelStyle,
12727
+ epayoutsFieldChrome: branding.epayoutsFieldChrome,
12728
+ epayoutsFieldFontSize: branding.epayoutsFieldFontSize,
12729
+ epayoutsFieldWeight: branding.epayoutsFieldWeight,
12730
+ epayoutsFocusRing: branding.epayoutsFocusRing,
12731
+ epayoutsValidTint: String(branding.epayoutsValidTint),
12128
12732
  nomupayFormStyle: branding.nomupayFormStyle,
12129
12733
  nomupayShowLabels: String(branding.nomupayShowLabels),
12130
12734
  nomupayShowPlaceholders: String(branding.nomupayShowPlaceholders),
@@ -12586,6 +13190,62 @@ function parseImportedBranding(raw) {
12586
13190
  dflt.whopSelection
12587
13191
  ),
12588
13192
  paypalValidTint: parseBool(root["paypalValidTint"], dflt.paypalValidTint),
13193
+ // A look stored before todos#412 has no e-Payouts keys: the form keeps
13194
+ // the PayPal values it was drawn with until then.
13195
+ epayoutsCardLayout: pickEnum(
13196
+ root["epayoutsCardLayout"],
13197
+ PAYPAL_CARD_LAYOUTS,
13198
+ pickEnum(
13199
+ root["paypalCardLayout"],
13200
+ PAYPAL_CARD_LAYOUTS,
13201
+ dflt.epayoutsCardLayout
13202
+ )
13203
+ ),
13204
+ epayoutsLabelStyle: pickEnum(
13205
+ root["epayoutsLabelStyle"],
13206
+ PAYPAL_LABEL_STYLES,
13207
+ pickEnum(
13208
+ root["paypalLabelStyle"],
13209
+ PAYPAL_LABEL_STYLES,
13210
+ dflt.epayoutsLabelStyle
13211
+ )
13212
+ ),
13213
+ epayoutsFieldChrome: pickEnum(
13214
+ root["epayoutsFieldChrome"],
13215
+ CARD_FIELD_CHROMES,
13216
+ pickEnum(
13217
+ root["paypalFieldChrome"],
13218
+ CARD_FIELD_CHROMES,
13219
+ dflt.epayoutsFieldChrome
13220
+ )
13221
+ ),
13222
+ epayoutsFieldFontSize: pickEnum(
13223
+ root["epayoutsFieldFontSize"],
13224
+ CARD_FIELD_FONT_SIZES,
13225
+ pickEnum(
13226
+ root["paypalFieldFontSize"],
13227
+ CARD_FIELD_FONT_SIZES,
13228
+ dflt.epayoutsFieldFontSize
13229
+ )
13230
+ ),
13231
+ epayoutsFieldWeight: pickEnum(
13232
+ root["epayoutsFieldWeight"],
13233
+ CARD_FIELD_WEIGHTS,
13234
+ pickEnum(
13235
+ root["paypalFieldWeight"],
13236
+ CARD_FIELD_WEIGHTS,
13237
+ dflt.epayoutsFieldWeight
13238
+ )
13239
+ ),
13240
+ epayoutsFocusRing: pickEnum(
13241
+ root["epayoutsFocusRing"],
13242
+ CARD_FOCUS_RINGS,
13243
+ pickEnum(root["paypalFocusRing"], CARD_FOCUS_RINGS, dflt.epayoutsFocusRing)
13244
+ ),
13245
+ epayoutsValidTint: parseBool(
13246
+ root["epayoutsValidTint"],
13247
+ parseBool(root["paypalValidTint"], dflt.epayoutsValidTint)
13248
+ ),
12589
13249
  nomupayFormStyle: pickEnum(
12590
13250
  root["nomupayFormStyle"],
12591
13251
  NOMUPAY_FORM_STYLES,
@@ -14100,6 +14760,41 @@ var Admin = class {
14100
14760
  }
14101
14761
  };
14102
14762
 
14763
+ // src/internal/resources/adminLive.ts
14764
+ var AdminLive = class {
14765
+ constructor(request, openStream) {
14766
+ this.request = request;
14767
+ this.openStream = openStream;
14768
+ }
14769
+ /**
14770
+ * Open the stream of what changed in every merchant. Each change names its
14771
+ * `merchant_id`. The SDK does not reconnect — see `LiveEventStream`.
14772
+ *
14773
+ * `GET /admin-portal/live/stream`
14774
+ */
14775
+ async stream(options) {
14776
+ return openLiveStream(this.openStream, "/admin-portal/live/stream", options);
14777
+ }
14778
+ /**
14779
+ * The versions an admin editor of `merchantId` names in `If-Match`. A save
14780
+ * over a newer version is refused with `IR_16` (400), `error.data` a
14781
+ * `LiveChangedElsewhere`.
14782
+ *
14783
+ * `GET /admin-portal/live/versions`
14784
+ */
14785
+ async versions(merchantId, params, options) {
14786
+ return this.request("GET", "/admin-portal/live/versions", {
14787
+ query: {
14788
+ merchant_id: merchantId,
14789
+ entities: params.entities.join(","),
14790
+ profile_id: params.profile_id,
14791
+ record_id: params.record_id
14792
+ },
14793
+ ...options
14794
+ });
14795
+ }
14796
+ };
14797
+
14103
14798
  // src/internal/resources/adminPortal.ts
14104
14799
  var AdminPortal = class {
14105
14800
  constructor(request) {
@@ -15765,6 +16460,8 @@ var DelopayInternal = class extends Delopay {
15765
16460
  const request = this.request.bind(this);
15766
16461
  this.admin = new Admin(request);
15767
16462
  this.adminPortal = new AdminPortal(request);
16463
+ const openStream = this.openEventStream.bind(this);
16464
+ this.adminLive = new AdminLive(request, openStream);
15768
16465
  this.auditLogs = new AuditLogs(request);
15769
16466
  this.cache = new Cache(request);
15770
16467
  this.cardIssuers = new CardIssuers(request);
@@ -15798,6 +16495,7 @@ var DelopayInternal = class extends Delopay {
15798
16495
  APPLE_PAY_BUTTON_STYLES,
15799
16496
  APPLE_PAY_BUTTON_TYPES,
15800
16497
  Admin,
16498
+ AdminLive,
15801
16499
  AdminPortal,
15802
16500
  Analytics,
15803
16501
  AnalyticsDashboard,
@@ -15856,6 +16554,8 @@ var DelopayInternal = class extends Delopay {
15856
16554
  InvoiceSettingsResource,
15857
16555
  Invoices,
15858
16556
  LOCALIZABLE_COPY_FIELDS,
16557
+ Live,
16558
+ LiveEventStream,
15859
16559
  MAX_SECTION_LABEL_LENGTH,
15860
16560
  MAX_SECTION_ORDER,
15861
16561
  METHOD_SECTIONS,