@assinafy/sdk 2.11.0 → 3.0.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/index.mjs CHANGED
@@ -32,6 +32,24 @@ var AssinafyError = class extends Error {
32
32
  var ApiError = class _ApiError extends AssinafyError {
33
33
  statusCode;
34
34
  responseData;
35
+ /**
36
+ * Machine-readable refusal code from the error body, on the refusals a
37
+ * client can act on: `PlanRestricted` (offer the upgrade, don't retry),
38
+ * `InsufficientScope`, `DocumentNotReady`, `CreditCeilingExceeded`,
39
+ * `IdempotencyKeyInUse`, `EnvelopeOpen`, `EnvelopeClosed`, `DocumentClosed`,
40
+ * `ContractChanged`, `NoContractTerms`, `TagInUse`, `embed_origins_missing`, ….
41
+ * `undefined` when the body has none.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * if (error instanceof ApiError && error.code === 'IdempotencyKeyInUse') {
46
+ * await sleep(1000); // the first request with this key is still running
47
+ * }
48
+ * ```
49
+ */
50
+ code;
51
+ /** Each field a `400` refused, in the order the API reports them. */
52
+ fieldErrors;
35
53
  /**
36
54
  * Parsed `WWW-Authenticate` challenge, when the response carried one.
37
55
  *
@@ -39,8 +57,8 @@ var ApiError = class _ApiError extends AssinafyError {
39
57
  * means the OAuth token is valid but was never granted that permission:
40
58
  * send the user through the authorization flow again asking for the scope
41
59
  * named in `scope`. A `403` without a challenge has a different cause —
42
- * another workspace, the user's role, or a surface OAuth tokens never
43
- * reach — and reconnecting will not fix it.
60
+ * another workspace, the user's role, the plan (`code: 'PlanRestricted'`),
61
+ * or a surface OAuth tokens never reach — and reconnecting will not fix it.
44
62
  *
45
63
  * @example
46
64
  * ```ts
@@ -87,6 +105,14 @@ var ApiError = class _ApiError extends AssinafyError {
87
105
  this.name = "ApiError";
88
106
  this.statusCode = statusCode;
89
107
  this.responseData = responseData;
108
+ if (responseData !== null && typeof responseData === "object") {
109
+ const body = responseData;
110
+ if (typeof body["code"] === "string" && body["code"].length > 0) this.code = body["code"];
111
+ if (Array.isArray(body["errors"])) {
112
+ const fieldErrors = body["errors"].filter(isFieldError);
113
+ if (fieldErrors.length > 0) this.fieldErrors = fieldErrors;
114
+ }
115
+ }
90
116
  }
91
117
  /**
92
118
  * Convert a status/body pair into an {@link ApiError}.
@@ -219,6 +245,11 @@ var NetworkError = class extends AssinafyError {
219
245
  this.name = "NetworkError";
220
246
  }
221
247
  };
248
+ function isFieldError(value) {
249
+ if (value === null || typeof value !== "object") return false;
250
+ const entry = value;
251
+ return (entry["field"] === null || typeof entry["field"] === "string") && typeof entry["code"] === "string" && typeof entry["message"] === "string";
252
+ }
222
253
 
223
254
  // src/utils.ts
224
255
  import axios from "axios";
@@ -279,6 +310,7 @@ var SAFE_LOG_NUMBER_FIELDS = /* @__PURE__ */ new Set([
279
310
  "delayMs",
280
311
  "maxRetries",
281
312
  "signerCount",
313
+ "documentCount",
282
314
  "size"
283
315
  ]);
284
316
  function handleAssinafyResponse(response) {
@@ -465,6 +497,34 @@ function assertExpirationDate(value, label) {
465
497
  throw new ValidationError(`${label} must be an ISO-8601 date or date-time`);
466
498
  }
467
499
  }
500
+ function assertCreditCeiling(value) {
501
+ if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value) || value < 0)) {
502
+ throw new ValidationError("max_total_credits must be a finite number of credits, zero or more");
503
+ }
504
+ }
505
+ function idempotencyConfig(key) {
506
+ if (key === void 0) return {};
507
+ if (typeof key !== "string" || key.trim().length === 0) {
508
+ throw new ValidationError("idempotencyKey must be a non-empty string");
509
+ }
510
+ return { headers: { "Idempotency-Key": key } };
511
+ }
512
+ function assertBooleanMap(value, label, known) {
513
+ assertRecord(value, label);
514
+ const entries = Object.entries(value);
515
+ if (entries.length === 0) throw new ValidationError(`${label} must set at least one key`);
516
+ for (const [key, item] of entries) {
517
+ if (known && !known.has(key)) throw new ValidationError(`unknown ${label} key: ${key}`);
518
+ if (typeof item !== "boolean") throw new ValidationError(`${label}.${key} must be a boolean`);
519
+ }
520
+ }
521
+ function expandParam(value, allowed) {
522
+ if (value === void 0) return {};
523
+ if (!Array.isArray(value) || value.some((item) => !allowed.has(item))) {
524
+ throw new ValidationError(`expand must list only ${[...allowed].join(", ")}`);
525
+ }
526
+ return value.length > 0 ? { expand: value.join(",") } : {};
527
+ }
468
528
  function cleanParams(params) {
469
529
  assertRecord(params, "params");
470
530
  const out = {};
@@ -639,7 +699,7 @@ import axios2 from "axios";
639
699
  // package.json
640
700
  var package_default = {
641
701
  name: "@assinafy/sdk",
642
- version: "2.11.0",
702
+ version: "3.0.0",
643
703
  packageManager: "bun@1.4.4",
644
704
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
645
705
  type: "commonjs",
@@ -991,14 +1051,23 @@ function toInt(value) {
991
1051
 
992
1052
  // src/resources/assignments.ts
993
1053
  var ASSIGNMENT_METHODS = /* @__PURE__ */ new Set(["virtual", "collect"]);
994
- var VERIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp", "DigitalCertificate", "IdDocumentFaceMatchBasic"]);
995
- var NOTIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp"]);
1054
+ var VERIFICATION_METHODS = /* @__PURE__ */ new Set([
1055
+ "Email",
1056
+ "Whatsapp",
1057
+ "DigitalCertificate",
1058
+ "IdDocumentFaceMatchBasic",
1059
+ "Bypass"
1060
+ ]);
1061
+ var MESSAGE_CHANNELS = /* @__PURE__ */ new Set(["Email", "Whatsapp"]);
1062
+ var NOTIFICATION_METHODS = /* @__PURE__ */ new Set([...MESSAGE_CHANNELS, "Bypass"]);
1063
+ var EMBEDDED_VERIFICATION_METHODS = /* @__PURE__ */ new Set(["Email", "Whatsapp", "Bypass"]);
996
1064
  var DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD = "digital_certificate_requires_virtual_method";
997
1065
  var ALLOWED_NOTIFICATION_METHODS = {
998
1066
  Email: /* @__PURE__ */ new Set(["Email"]),
999
1067
  Whatsapp: /* @__PURE__ */ new Set(["Whatsapp"]),
1000
- DigitalCertificate: NOTIFICATION_METHODS,
1001
- IdDocumentFaceMatchBasic: NOTIFICATION_METHODS
1068
+ DigitalCertificate: MESSAGE_CHANNELS,
1069
+ IdDocumentFaceMatchBasic: MESSAGE_CHANNELS,
1070
+ Bypass: NOTIFICATION_METHODS
1002
1071
  };
1003
1072
  function validateAssignmentSignerOptions(signer, label = "signer") {
1004
1073
  if (signer.verification_method !== void 0 && (typeof signer.verification_method !== "string" || !VERIFICATION_METHODS.has(signer.verification_method))) {
@@ -1024,6 +1093,14 @@ function validateAssignmentSignerOptions(signer, label = "signer") {
1024
1093
  }
1025
1094
  }
1026
1095
  }
1096
+ if (signer.embedded !== void 0 && typeof signer.embedded !== "boolean") {
1097
+ throw new ValidationError(`${label} embedded must be a boolean`);
1098
+ }
1099
+ if (signer.embedded === true && typeof signer.verification_method === "string" && !EMBEDDED_VERIFICATION_METHODS.has(signer.verification_method)) {
1100
+ throw new ValidationError(
1101
+ `${label} embedded signing supports only Email, Whatsapp and Bypass verification`
1102
+ );
1103
+ }
1027
1104
  if (signer.step !== void 0 && (typeof signer.step !== "number" || !Number.isSafeInteger(signer.step) || signer.step < 1)) {
1028
1105
  throw new ValidationError(`${label} step must be a positive safe integer`);
1029
1106
  }
@@ -1084,6 +1161,7 @@ function buildAssignmentPayload(payload) {
1084
1161
  ))) {
1085
1162
  throw new ValidationError("copy_receivers must be an array of non-empty signer IDs");
1086
1163
  }
1164
+ assertCreditCeiling(payload.max_total_credits);
1087
1165
  const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref));
1088
1166
  validateDigitalCertificateMethod(method, normalisedSigners);
1089
1167
  validateSigningOrder(normalisedSigners, "assignment signers");
@@ -1093,7 +1171,8 @@ function buildAssignmentPayload(payload) {
1093
1171
  message: payload.message,
1094
1172
  expires_at: payload.expires_at,
1095
1173
  copy_receivers: payload.copy_receivers,
1096
- entries
1174
+ entries,
1175
+ max_total_credits: payload.max_total_credits
1097
1176
  });
1098
1177
  }
1099
1178
  function buildAssignmentEstimatePayload(payload) {
@@ -1138,6 +1217,7 @@ function normaliseSignerRef(ref) {
1138
1217
  id,
1139
1218
  verification_method: input.verification_method,
1140
1219
  notification_methods: input.notification_methods,
1220
+ embedded: input.embedded,
1141
1221
  step: input.step
1142
1222
  });
1143
1223
  if (typeof id === "string" && id.trim().length > 0) {
@@ -1245,12 +1325,13 @@ var AssignmentResource = class extends BaseResource {
1245
1325
  /**
1246
1326
  * List assignments across the workspace (`GET /assignments`).
1247
1327
  *
1248
- * The account is passed as an `accountId` **query parameter** — the API
1249
- * responds `400` ("Um contexto de conta é necessário e não foi fornecido")
1250
- * without it. Note the camelCase spelling: `account_id` and an
1251
- * `X-Account-Id` header are both rejected.
1328
+ * The account is passed as the camelCase `accountId` **query parameter**,
1329
+ * required unless an OAuth token names the workspace (the SDK always sends
1330
+ * it; for a token, its own workspace). `account_id` and an `X-Account-Id`
1331
+ * header are ignored.
1252
1332
  *
1253
- * @param params - `page`, `per-page`, and `sort`.
1333
+ * @param params - `page`, `per-page` (at most 50), and `sort`: `created_at`
1334
+ * (default, oldest first), `expires_at` or `id`, `-` prefix for descending.
1254
1335
  * @param accountId - Override the client's default account ID.
1255
1336
  * @returns Assignments, with pagination in `meta`. Each item is a full
1256
1337
  * {@link IAssignment} (same shape as {@link AssignmentResource.create}
@@ -1318,13 +1399,15 @@ var AssignmentResource = class extends BaseResource {
1318
1399
  * "signing_urls": [
1319
1400
  * {
1320
1401
  * "signer_id": "19e6b92e7895332ed9708535d8c",
1321
- * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com"
1402
+ * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com",
1403
+ * "embedded": false
1322
1404
  * }
1323
1405
  * ]
1324
1406
  * }
1325
1407
  * ```
1326
1408
  * @throws {ValidationError} If no account ID is available.
1327
- * @throws {ApiError} If the API rejects the request.
1409
+ * @throws {ApiError} `400` when no workspace is named, `403` when a role or
1410
+ * OAuth scope refuses it, `404` for an unknown workspace.
1328
1411
  *
1329
1412
  * @example
1330
1413
  * ```ts
@@ -1384,7 +1467,13 @@ var AssignmentResource = class extends BaseResource {
1384
1467
  * `message`, `expires_at`, `copy_receivers` (existing signer IDs, not
1385
1468
  * addresses), and `collect`-mode `entries` with page-image geometry.
1386
1469
  * `expires_at` accepts a date (ending at 23:59 UTC), a date-time without
1387
- * an offset (UTC), or an offset-aware date-time.
1470
+ * an offset (UTC), or an offset-aware date-time, at least one hour ahead.
1471
+ * `max_total_credits` refuses the send above that many credits. Signers may
1472
+ * set `embedded: true` (Embed feature; `Email`, `Whatsapp` or `Bypass`
1473
+ * verification) to sign in your app through `embed.createSession()`.
1474
+ * This route takes no `Idempotency-Key`: a document takes one assignment,
1475
+ * so a retry after a lost response answers `400` and charges nothing —
1476
+ * read the document to see whether the first request went through.
1388
1477
  * @returns The created {@link IAssignment}: `signers` (rich, with `step` /
1389
1478
  * `notified` / `verification_method`), `items` (one row per signer × field),
1390
1479
  * a `summary` count block, and per-signer `signing_urls`. Response shape:
@@ -1449,7 +1538,8 @@ var AssignmentResource = class extends BaseResource {
1449
1538
  * "signing_urls": [
1450
1539
  * {
1451
1540
  * "signer_id": "19e6b92e7895332ed9708535d8c",
1452
- * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com"
1541
+ * "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c?email=signer%40example.com",
1542
+ * "embedded": false // an embedded signer has "url": null
1453
1543
  * }
1454
1544
  * ]
1455
1545
  * }
@@ -1459,7 +1549,10 @@ var AssignmentResource = class extends BaseResource {
1459
1549
  * combined with `collect`. The last case has `errors.code ===
1460
1550
  * 'digital_certificate_requires_virtual_method'`.
1461
1551
  * @throws {ApiError} `400` for an invalid assignment or unmet verification
1462
- * precondition; otherwise if the API rejects the request.
1552
+ * precondition; `403` (`PlanRestricted` for a method or Embed the plan
1553
+ * lacks, `InsufficientScope`); `404` for a document outside the workspace;
1554
+ * `409` (`CreditCeilingExceeded`, with `total_credits` and
1555
+ * `max_total_credits` in `responseData`).
1463
1556
  *
1464
1557
  * @example
1465
1558
  * ```ts
@@ -1468,7 +1561,7 @@ var AssignmentResource = class extends BaseResource {
1468
1561
  * message: 'Please sign this contract',
1469
1562
  * });
1470
1563
  * // → wire body: { method: 'virtual', signers: [{ id: '19e6…' }], message: 'Please sign this contract' }
1471
- * console.log(assignment.signing_urls?.length); // one protected link per signer
1564
+ * console.log(assignment.signing_urls?.length); // one entry per notified signer; url is null for embedded or WhatsApp-only signers
1472
1565
  * ```
1473
1566
  */
1474
1567
  async create(documentId, payload) {
@@ -1660,7 +1753,11 @@ var AssignmentResource = class extends BaseResource {
1660
1753
  * }
1661
1754
  * ```
1662
1755
  * @throws {ValidationError} If any of the three IDs is missing.
1663
- * @throws {ApiError} If the API rejects the request.
1756
+ * @throws {ApiError} `400` when the document is not pending signature, the
1757
+ * signer already signed or waits for an earlier step, or credits are short;
1758
+ * `403`; `404`. The same verification code is resent, so an open embed frame
1759
+ * keeps working; envelope signers can be reminded of every document at once
1760
+ * with `envelopes.resendNotification()`.
1664
1761
  *
1665
1762
  * @example
1666
1763
  * ```ts
@@ -1689,26 +1786,20 @@ var AssignmentResource = class extends BaseResource {
1689
1786
  * @param documentId - The document the assignment belongs to.
1690
1787
  * @param assignmentId - The assignment containing the signer.
1691
1788
  * @param signerId - The signer whose notification would be resent.
1692
- * @returns An {@link IResendCostEstimate}: either the full
1693
- * {@link ICostEstimate} or the compact `total` /
1694
- * `has_sufficient_credits` compatibility shape:
1789
+ * @returns An {@link IResendCostEstimate}: the compact `total` /
1790
+ * `has_sufficient_credits` shape production returns, or the full
1791
+ * {@link ICostEstimate} on older deployments:
1695
1792
  * ```jsonc
1696
1793
  * {
1697
- * "documents": 1,
1698
- * "credits": 0,
1699
- * "needs_extra_document": false,
1700
- * "extra_document_cost": 0,
1701
- * "total_credits": 0,
1702
- * "breakdown": [],
1703
- * "document_balance": 67,
1704
- * "credit_balance": 0,
1705
- * "has_sufficient_resources": true,
1706
- * "blocking_reason": null,
1707
- * "message": null
1794
+ * "total": 0.45,
1795
+ * "breakdown": [{ "code": "NotificationWhatsappResend", "name": "WhatsApp Notification Resend", "cost": 0.45 }],
1796
+ * "credit_balance": 10, // null when credits are not limited
1797
+ * "has_sufficient_credits": true
1708
1798
  * }
1709
1799
  * ```
1710
1800
  * @throws {ValidationError} If any of the three IDs is missing.
1711
- * @throws {ApiError} If the API rejects the request.
1801
+ * @throws {ApiError} `400` when the signer cannot be reminded (signed, not
1802
+ * yet notified, or notified only by `Bypass`), `403`, `404`.
1712
1803
  *
1713
1804
  * @example
1714
1805
  * ```ts
@@ -1746,11 +1837,11 @@ var AssignmentResource = class extends BaseResource {
1746
1837
  * ```jsonc
1747
1838
  * [
1748
1839
  * {
1749
- * "sent_at": 1784145573,
1840
+ * "sent_at": "2026-10-19T19:05:48Z",
1750
1841
  * "header": "Assinafy",
1751
1842
  * "body": "Você tem um documento para assinar.",
1752
1843
  * "buttons": [
1753
- * { "text": "Assinar documento", "url": "https://app.assinafy.com.br/sign/103033c950d865a248a11c5cf96c" }
1844
+ * { "text": "Assinar documento" } // production strips button URLs
1754
1845
  * ],
1755
1846
  * "phone_number": "+5511999998888",
1756
1847
  * "signer_id": "19e6b92e7895332ed9708535d8c"
@@ -2209,7 +2300,11 @@ var DocumentResource = class extends BaseResource {
2209
2300
  * `null`), rendered `pages`, and `artifacts`. `decline_reason` is returned
2210
2301
  * only when the access token belongs to the document creator.
2211
2302
  *
2303
+ * `expand: ['envelope_id']` adds the envelope the document is in and
2304
+ * `expand: ['envelope']` its `{ id, name }` (each `null` outside one).
2305
+ *
2212
2306
  * @param documentId - The document to fetch.
2307
+ * @param options - `expand`: `envelope_id` and/or `envelope`.
2213
2308
  * @returns The document. Response shape (once `metadata_ready`):
2214
2309
  * ```jsonc
2215
2310
  * {
@@ -2238,30 +2333,38 @@ var DocumentResource = class extends BaseResource {
2238
2333
  * "download_url": "https://…/documents/103ad216…/pages/103ad216…/download"
2239
2334
  * }
2240
2335
  * ],
2336
+ * "has_contract": false,
2337
+ * "envelope_id": null, // with expand: ['envelope_id']
2338
+ * "envelope": null, // with expand: ['envelope']
2241
2339
  * "created_at": "2026-07-19T17:24:43Z",
2242
2340
  * "updated_at": "2026-07-19T17:24:46Z"
2243
2341
  * }
2244
2342
  * ```
2245
- * @throws {ValidationError} If `documentId` is missing.
2246
- * @throws {ApiError} `404` if the document does not exist.
2343
+ * @throws {ValidationError} If `documentId` is missing or `expand` is unknown.
2344
+ * @throws {ApiError} `403` when a role or OAuth scope refuses it, `404` if the
2345
+ * document does not exist.
2247
2346
  *
2248
2347
  * @example
2249
2348
  * ```ts
2250
- * const doc = await client.documents.details('103ad216846e6b90710cb9acef59');
2251
- * console.log(doc.status, doc.pages.length);
2349
+ * const doc = await client.documents.details('103ad216846e6b90710cb9acef59', {
2350
+ * expand: ['envelope'],
2351
+ * });
2352
+ * console.log(doc.status, doc.envelope?.name);
2252
2353
  * ```
2253
2354
  */
2254
- async details(documentId) {
2355
+ async details(documentId, options = {}) {
2255
2356
  const id = this.requireId(documentId, "Document ID");
2256
- return this.fetchDetails(id);
2257
- }
2258
- fetchDetails(id, signal) {
2357
+ return this.fetchDetails(id, void 0, options);
2358
+ }
2359
+ fetchDetails(id, signal, options = {}) {
2360
+ assertRecord(options, "document details options");
2361
+ const params = expandParam(options.expand, DETAIL_EXPANSIONS);
2362
+ const config = {};
2363
+ if (signal) config.signal = signal;
2364
+ if (params.expand) config.params = params;
2259
2365
  return this.call(
2260
2366
  "Failed to fetch document details",
2261
- () => this.http.get(
2262
- `/documents/${this.pathSegment(id, "Document ID")}`,
2263
- signal ? { signal } : void 0
2264
- )
2367
+ () => this.http.get(`/documents/${this.pathSegment(id, "Document ID")}`, config)
2265
2368
  );
2266
2369
  }
2267
2370
  /**
@@ -2269,18 +2372,19 @@ var DocumentResource = class extends BaseResource {
2269
2372
  * (`GET /documents/{documentId}`).
2270
2373
  *
2271
2374
  * @param documentId - The document to fetch.
2375
+ * @param options - `expand`, as on {@link DocumentResource.details}.
2272
2376
  * @returns The document details (see {@link DocumentResource.details} for
2273
2377
  * the response shape).
2274
2378
  * @throws {ValidationError} If `documentId` is missing.
2275
- * @throws {ApiError} `404` if the document does not exist.
2379
+ * @throws {ApiError} `403` or `404`, as on {@link DocumentResource.details}.
2276
2380
  *
2277
2381
  * @example
2278
2382
  * ```ts
2279
2383
  * const doc = await client.documents.get('103ad216846e6b90710cb9acef59');
2280
2384
  * ```
2281
2385
  */
2282
- async get(documentId) {
2283
- return this.details(documentId);
2386
+ async get(documentId, options = {}) {
2387
+ return this.details(documentId, options);
2284
2388
  }
2285
2389
  /**
2286
2390
  * Poll {@link DocumentResource.details} until the document reaches a ready
@@ -2394,10 +2498,15 @@ var DocumentResource = class extends BaseResource {
2394
2498
  * Download the document thumbnail image
2395
2499
  * (`GET /documents/{documentId}/thumbnail`).
2396
2500
  *
2501
+ * `artifact: 'certificated'` renders it as it is in the signed document.
2502
+ *
2397
2503
  * @param documentId - The document whose thumbnail to fetch.
2398
- * @returns A {@link Buffer} of the thumbnail image bytes.
2399
- * @throws {ValidationError} If `documentId` is missing.
2400
- * @throws {ApiError} `404` if the document or its thumbnail does not exist.
2504
+ * @param options - `artifact: 'certificated'` for the signed render.
2505
+ * @returns A {@link Buffer} of the thumbnail image bytes (`image/*`).
2506
+ * @throws {ValidationError} If `documentId` is missing or `artifact` is unknown.
2507
+ * @throws {ApiError} `404` if the document, its thumbnail, or (with
2508
+ * `certificated`) its certification does not exist; `503` while the signed
2509
+ * render is still being produced — wait `rateLimit.retryAfter` seconds.
2401
2510
  *
2402
2511
  * @example
2403
2512
  * ```ts
@@ -2405,28 +2514,29 @@ var DocumentResource = class extends BaseResource {
2405
2514
  * await fs.promises.writeFile('thumb.jpg', thumb);
2406
2515
  * ```
2407
2516
  */
2408
- async thumbnail(documentId) {
2517
+ async thumbnail(documentId, options = {}) {
2409
2518
  const id = this.requireId(documentId, "Document ID");
2519
+ const config = renderConfig(options);
2410
2520
  return this.callBinary(
2411
2521
  "Failed to download document thumbnail",
2412
- () => this.http.get(
2413
- `/documents/${this.pathSegment(id, "Document ID")}/thumbnail`,
2414
- { responseType: "arraybuffer" }
2415
- )
2522
+ () => this.http.get(`/documents/${this.pathSegment(id, "Document ID")}/thumbnail`, config)
2416
2523
  );
2417
2524
  }
2418
2525
  /**
2419
- * Download a single rendered page as a JPEG
2526
+ * Download a single rendered page image
2420
2527
  * (`GET /documents/{documentId}/pages/{pageId}/download`).
2421
2528
  *
2422
2529
  * The `pageId` comes from a page's `id` in {@link DocumentResource.details}
2423
- * or {@link DocumentResource.list} (`pages[].id`).
2530
+ * or {@link DocumentResource.list} (`pages[].id`). `artifact: 'certificated'`
2531
+ * renders the page as it is in the signed document.
2424
2532
  *
2425
2533
  * @param documentId - The document the page belongs to.
2426
2534
  * @param pageId - The page to download.
2427
- * @returns A {@link Buffer} of the page's JPEG bytes.
2428
- * @throws {ValidationError} If `documentId` or `pageId` is missing.
2429
- * @throws {ApiError} `404` if the document or page does not exist.
2535
+ * @param options - `artifact: 'certificated'` for the signed render.
2536
+ * @returns A {@link Buffer} of the page image bytes (`image/*`).
2537
+ * @throws {ValidationError} If `documentId` or `pageId` is missing, or `artifact` is unknown.
2538
+ * @throws {ApiError} `404` if the document or page does not exist (or, with
2539
+ * `certificated`, is not certified); `503` while the signed render is pending.
2430
2540
  *
2431
2541
  * @example
2432
2542
  * ```ts
@@ -2435,14 +2545,15 @@ var DocumentResource = class extends BaseResource {
2435
2545
  * await fs.promises.writeFile('page-1.jpg', page);
2436
2546
  * ```
2437
2547
  */
2438
- async downloadPage(documentId, pageId) {
2548
+ async downloadPage(documentId, pageId, options = {}) {
2439
2549
  const docId = this.requireId(documentId, "Document ID");
2440
2550
  const pid = this.requireId(pageId, "Page ID");
2551
+ const config = renderConfig(options);
2441
2552
  return this.callBinary(
2442
2553
  "Failed to download page",
2443
2554
  () => this.http.get(
2444
2555
  `/documents/${this.pathSegment(docId, "Document ID")}/pages/${this.pathSegment(pid, "Page ID")}/download`,
2445
- { responseType: "arraybuffer" }
2556
+ config
2446
2557
  )
2447
2558
  );
2448
2559
  }
@@ -2459,7 +2570,7 @@ var DocumentResource = class extends BaseResource {
2459
2570
  * @param documentId - The document whose activity log to fetch.
2460
2571
  * @param params - Optional pagination and sorting parameters.
2461
2572
  * @param params.page - Page number, starting at 1.
2462
- * @param params.per-page - Entries per page (production default 20, documented max 100).
2573
+ * @param params.per-page - Entries per page (default 20, at most 50; a larger value answers 50).
2463
2574
  * @param params.per_page - Alias for `per-page`; explicit `per-page` wins.
2464
2575
  * @param params.sort - `-id` (default, newest first) or `id` (oldest first).
2465
2576
  * @returns The requested page of activity entries, or `[]`:
@@ -2489,7 +2600,7 @@ var DocumentResource = class extends BaseResource {
2489
2600
  * @example
2490
2601
  * ```ts
2491
2602
  * const events = await client.documents.activities('doc-1', {
2492
- * page: 2, 'per-page': 100, sort: 'id',
2603
+ * page: 2, 'per-page': 50, sort: 'id',
2493
2604
  * });
2494
2605
  * console.log(events.map((e) => e.event));
2495
2606
  * ```
@@ -2509,7 +2620,7 @@ var DocumentResource = class extends BaseResource {
2509
2620
  * @param documentId - The document whose activity log to fetch.
2510
2621
  * @param params - Optional pagination and sorting parameters.
2511
2622
  * @param params.page - Page number, starting at 1.
2512
- * @param params.per-page - Entries per page (production default 20, documented max 100).
2623
+ * @param params.per-page - Entries per page (default 20, at most 50; a larger value answers 50).
2513
2624
  * @param params.per_page - Alias for `per-page`; explicit `per-page` wins.
2514
2625
  * @param params.sort - `-id` (default, newest first) or `id` (oldest first).
2515
2626
  * @returns Activity entries and pagination metadata when the server supplies it:
@@ -2550,13 +2661,16 @@ var DocumentResource = class extends BaseResource {
2550
2661
  * Only documents in a deletable status can be removed — the API returns
2551
2662
  * `400` while the document is still `uploading` / `metadata_processing`
2552
2663
  * (await {@link DocumentResource.waitUntilReady} first) or once it has been
2553
- * certificated.
2664
+ * certificated. Deleting a `pending_signature` or `pending_identity_review`
2665
+ * document cancels it and notifies its signers. A document of an envelope
2666
+ * with an open document cannot be deleted on its own: cancel the envelope.
2554
2667
  *
2555
2668
  * @param documentId - The document to delete.
2556
2669
  * @returns Nothing; resolves when the document is deleted.
2557
2670
  * @throws {ValidationError} If `documentId` is missing.
2558
2671
  * @throws {ApiError} `400` if the document is not in a deletable status;
2559
- * `404` if it does not exist.
2672
+ * `403` when a role or OAuth scope refuses it; `404` if it does not exist;
2673
+ * `409` (`EnvelopeOpen`) while its envelope has an open document.
2560
2674
  *
2561
2675
  * @example
2562
2676
  * ```ts
@@ -2861,6 +2975,8 @@ var DocumentResource = class extends BaseResource {
2861
2975
  if (options.tags !== void 0 && (!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== "string" || !tag.trim()))) {
2862
2976
  throw new ValidationError("tags must be an array of non-empty tag names");
2863
2977
  }
2978
+ assertCreditCeiling(options.max_total_credits);
2979
+ const config = idempotencyConfig(options.idempotencyKey);
2864
2980
  const tmplId = this.requireId(templateId, "Template ID");
2865
2981
  const accId = this.accountId(accountId);
2866
2982
  const body = {
@@ -2871,12 +2987,14 @@ var DocumentResource = class extends BaseResource {
2871
2987
  if (options.expires_at !== void 0) body["expires_at"] = options.expires_at;
2872
2988
  if (editorFields !== void 0) body["editor_fields"] = editorFields;
2873
2989
  if (options.tags !== void 0) body["tags"] = [...options.tags];
2990
+ if (options.max_total_credits !== void 0) body["max_total_credits"] = options.max_total_credits;
2874
2991
  this.logger.info("Creating document from template", { templateId: tmplId, accountId: accId });
2875
2992
  return this.call(
2876
2993
  "Failed to create document from template",
2877
2994
  () => this.http.post(
2878
2995
  `/accounts/${this.pathSegment(accId, "Account ID")}/templates/${this.pathSegment(tmplId, "Template ID")}/documents`,
2879
- body
2996
+ body,
2997
+ config
2880
2998
  )
2881
2999
  );
2882
3000
  }
@@ -3010,13 +3128,14 @@ var DocumentResource = class extends BaseResource {
3010
3128
  * { "code": "uploaded", "deletable": false },
3011
3129
  * { "code": "metadata_processing", "deletable": false },
3012
3130
  * { "code": "metadata_ready", "deletable": true },
3013
- * { "code": "pending_signature", "deletable": true },
3014
- * { "code": "expired", "deletable": false },
3131
+ * { "code": "expired", "deletable": true },
3015
3132
  * { "code": "certificating", "deletable": false },
3016
3133
  * { "code": "certificated", "deletable": false },
3017
- * { "code": "rejected_by_signer", "deletable": false },
3018
- * { "code": "rejected_by_user", "deletable": false },
3019
- * { "code": "failed", "deletable": false }
3134
+ * { "code": "rejected_by_signer", "deletable": true },
3135
+ * { "code": "pending_signature", "deletable": true },
3136
+ * { "code": "pending_identity_review", "deletable": true }, // deleting cancels and notifies signers
3137
+ * { "code": "rejected_by_user", "deletable": true },
3138
+ * { "code": "failed", "deletable": true }
3020
3139
  * ]
3021
3140
  * ```
3022
3141
  * @throws {ApiError} If the API rejects the request.
@@ -3245,11 +3364,21 @@ function normaliseTemplateSigners(signers) {
3245
3364
  if (signer.notification_methods !== void 0) {
3246
3365
  projected.notification_methods = [...signer.notification_methods];
3247
3366
  }
3367
+ if (signer.embedded !== void 0) projected.embedded = signer.embedded;
3248
3368
  if (signer.step !== void 0) projected.step = signer.step;
3249
3369
  return projected;
3250
3370
  });
3251
3371
  return normalised;
3252
3372
  }
3373
+ var DETAIL_EXPANSIONS = /* @__PURE__ */ new Set(["envelope_id", "envelope"]);
3374
+ function renderConfig(options) {
3375
+ assertRecord(options, "render options");
3376
+ if (options.artifact === void 0) return { responseType: "arraybuffer" };
3377
+ if (options.artifact !== "certificated") {
3378
+ throw new ValidationError("artifact must be certificated when given");
3379
+ }
3380
+ return { responseType: "arraybuffer", params: { artifact: options.artifact } };
3381
+ }
3253
3382
  function normaliseTemplateEditorFields(fields) {
3254
3383
  if (!Array.isArray(fields)) {
3255
3384
  throw new ValidationError("editor_fields must be an array");
@@ -3530,7 +3659,7 @@ var SignerResource = class extends BaseResource {
3530
3659
  "Failed to update signer",
3531
3660
  () => this.http.put(
3532
3661
  `/accounts/${this.pathSegment(id, "Account ID")}/signers/${this.pathSegment(sid, "Signer ID")}`,
3533
- normaliseSignerPayload(payload)
3662
+ { ...normaliseSignerPayload(payload), ...clearedContacts(payload) }
3534
3663
  )
3535
3664
  );
3536
3665
  }
@@ -3656,13 +3785,19 @@ function validateUpdateSignerPayload(payload) {
3656
3785
  if (payload.full_name !== void 0 && (typeof payload.full_name !== "string" || !payload.full_name.trim())) {
3657
3786
  throw new ValidationError("full_name cannot be empty");
3658
3787
  }
3659
- if (payload.email !== void 0 && !isEmail(payload.email)) {
3788
+ if (payload.email !== void 0 && !isClear(payload.email) && !isEmail(payload.email)) {
3660
3789
  throw new ValidationError("Invalid email address", { email: payload.email });
3661
3790
  }
3662
- const phone = payload.whatsapp_phone_number ?? payload.phone;
3663
- validateOptionalPhone(phone);
3791
+ const phone = updatePhone(payload);
3792
+ if (!isClear(phone)) validateOptionalPhone(phone);
3664
3793
  validateOptionalDigits(payload.cpf, "cpf");
3665
- validateOptionalDigits(payload.government_id, "government_id");
3794
+ if (!isClear(payload.government_id)) validateOptionalDigits(payload.government_id, "government_id");
3795
+ }
3796
+ function isClear(value) {
3797
+ return value === null || value === "";
3798
+ }
3799
+ function updatePhone(payload) {
3800
+ return payload.whatsapp_phone_number !== void 0 ? payload.whatsapp_phone_number : payload.phone;
3666
3801
  }
3667
3802
  function validateOptionalDigits(value, field) {
3668
3803
  if (value === void 0) return;
@@ -3693,6 +3828,18 @@ function normaliseSignerPayload(payload) {
3693
3828
  }
3694
3829
  return cleanParams(normalised);
3695
3830
  }
3831
+ function clearedContacts(payload) {
3832
+ const cleared = {};
3833
+ const candidates = {
3834
+ email: payload.email,
3835
+ whatsapp_phone_number: updatePhone(payload),
3836
+ government_id: payload.government_id
3837
+ };
3838
+ for (const [key, value] of Object.entries(candidates)) {
3839
+ if (isClear(value)) cleared[key] = value;
3840
+ }
3841
+ return cleared;
3842
+ }
3696
3843
 
3697
3844
  // src/support/stats.ts
3698
3845
  var MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
@@ -3813,7 +3960,13 @@ var WorkspaceResource = class extends BaseResource {
3813
3960
  /**
3814
3961
  * Fetch a single workspace (`GET /accounts/{accountId}`).
3815
3962
  *
3963
+ * `expand: 'signing_features'` adds which signing methods the plan allows
3964
+ * (OAuth: `account:read`). A `false` feature makes creating or estimating an
3965
+ * assignment, template document or envelope with that method answer `403`
3966
+ * (`PlanRestricted`); check it before offering the method.
3967
+ *
3816
3968
  * @param accountId - The workspace to fetch.
3969
+ * @param options - `expand: 'signing_features'`.
3817
3970
  * @returns The workspace. `primary_color` / `secondary_color` are `null`
3818
3971
  * until brand colours are set (6-char hex, no `#`, when present):
3819
3972
  * ```jsonc
@@ -3826,22 +3979,154 @@ var WorkspaceResource = class extends BaseResource {
3826
3979
  * "notification_sender_type": "User",
3827
3980
  * "roles": ["owner"],
3828
3981
  * "is_delete_allowed": true,
3982
+ * "limits": { "webhook_endpoints": 3 },
3983
+ * "signing_features": { // only with expand: 'signing_features'
3984
+ * "DigitalCertificate": true,
3985
+ * "VerificationIdDocumentFaceMatchBasic": true,
3986
+ * "WhatsappNotification": true,
3987
+ * "VerificationBypass": false,
3988
+ * "Embed": true
3989
+ * },
3829
3990
  * "created_at": "2026-05-12T18:05:11Z"
3830
3991
  * }
3831
3992
  * ```
3832
- * @throws {ValidationError} If `accountId` is missing.
3833
- * @throws {ApiError} `404` if the workspace does not exist.
3993
+ * @throws {ValidationError} If `accountId` is missing or `expand` is unknown.
3994
+ * @throws {ApiError} `403` for another workspace's token, `404` if the
3995
+ * workspace does not exist.
3834
3996
  *
3835
3997
  * @example
3836
3998
  * ```ts
3837
- * const ws = await client.workspaces.get('acc_example');
3999
+ * const ws = await client.workspaces.get('acc_example', { expand: 'signing_features' });
4000
+ * if (ws.signing_features?.Embed) await client.embed.listOrigins();
3838
4001
  * ```
3839
4002
  */
3840
- async get(accountId) {
4003
+ async get(accountId, options = {}) {
3841
4004
  const id = this.requireId(accountId, "Account ID");
4005
+ assertRecord(options, "workspace options");
4006
+ if (options.expand !== void 0 && options.expand !== "signing_features") {
4007
+ throw new ValidationError("expand must be signing_features");
4008
+ }
4009
+ const config = options.expand === void 0 ? {} : { params: { expand: options.expand } };
3842
4010
  return this.call(
3843
4011
  "Failed to fetch workspace",
3844
- () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}`)
4012
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}`, config)
4013
+ );
4014
+ }
4015
+ /**
4016
+ * Read the workspace's plan and balances (`GET /accounts/{accountId}/usage`).
4017
+ *
4018
+ * For a plan and credit meter; prices and payments are not included. Not
4019
+ * available to third-party OAuth applications (`403`), whatever their scopes.
4020
+ *
4021
+ * @param accountId - The workspace to read.
4022
+ * @returns The plan meter:
4023
+ * ```jsonc
4024
+ * {
4025
+ * "plan": "Pro", // null without a current plan
4026
+ * "documents_renewal_date": "2026-12-11",
4027
+ * "balances": {
4028
+ * "documents": { "balance": 97, "limit": 100, "spent": 3 },
4029
+ * "credits": { "balance": 12.5, "limit": null, "spent": 0.9 } // null: unlimited / not cycle-limited
4030
+ * }
4031
+ * }
4032
+ * ```
4033
+ * @throws {ValidationError} If `accountId` is missing.
4034
+ * @throws {ApiError} `403` for an OAuth application token, `404` for an unknown workspace.
4035
+ *
4036
+ * @example
4037
+ * ```ts
4038
+ * const { balances } = await client.workspaces.getUsage('acc_example');
4039
+ * ```
4040
+ */
4041
+ async getUsage(accountId) {
4042
+ const id = this.requireId(accountId, "Account ID");
4043
+ return this.call(
4044
+ "Failed to fetch account usage",
4045
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}/usage`)
4046
+ );
4047
+ }
4048
+ /**
4049
+ * Read which document alerts the workspace sends
4050
+ * (`GET /accounts/{accountId}/notification-policy`).
4051
+ *
4052
+ * Every member can read it; `editable` says whether the caller (an owner)
4053
+ * can change it. Not available to third-party OAuth applications.
4054
+ *
4055
+ * @param accountId - The workspace to read.
4056
+ * @returns The policy; every event key is present:
4057
+ * ```jsonc
4058
+ * {
4059
+ * "editable": true,
4060
+ * "owners_receive_all": false, // owners also get push alerts for members' documents
4061
+ * "events": {
4062
+ * "DocumentCompleted": true, "SignerDeclined": true, "DocumentCancelled": true,
4063
+ * "DocumentAboutToExpire": true, "DocumentExpired": true, "DocumentExpirationReset": true,
4064
+ * "DocumentProcessingFailed": true, "TemplateProcessingFailed": true, "SignerWhatsappFailed": true,
4065
+ * "ContractRenewalNotice": true, "ContractExpiring": true, "ContractExpired": true,
4066
+ * "ContractRenewed": true, "SignerViewed": true, "SignerSigned": true,
4067
+ * "SignerIdentityReviewRequired": true
4068
+ * }
4069
+ * }
4070
+ * ```
4071
+ * @throws {ValidationError} If `accountId` is missing.
4072
+ * @throws {ApiError} `403` for an OAuth application token.
4073
+ *
4074
+ * @example
4075
+ * ```ts
4076
+ * const policy = await client.workspaces.getNotificationPolicy('acc_example');
4077
+ * ```
4078
+ */
4079
+ async getNotificationPolicy(accountId) {
4080
+ const id = this.requireId(accountId, "Account ID");
4081
+ return this.call(
4082
+ "Failed to fetch notification policy",
4083
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}/notification-policy`)
4084
+ );
4085
+ }
4086
+ /**
4087
+ * Change which document alerts the workspace sends
4088
+ * (`PUT /accounts/{accountId}/notification-policy`).
4089
+ *
4090
+ * Owners only. Merges what is sent: an event set to `false` reaches nobody
4091
+ * in the workspace on any channel, whatever each member's preferences. The
4092
+ * identity-review e-mail is always sent, because the signer cannot continue
4093
+ * without it.
4094
+ *
4095
+ * @param accountId - The workspace to change.
4096
+ * @param payload - `events` keys to change and/or `owners_receive_all`.
4097
+ * @returns The full policy, as {@link WorkspaceResource.getNotificationPolicy} returns.
4098
+ * @throws {ValidationError} If nothing would change or a value is not a boolean.
4099
+ * @throws {ApiError} `400` for an unknown event code, `403` for a non-owner or
4100
+ * an OAuth application token.
4101
+ *
4102
+ * @example
4103
+ * ```ts
4104
+ * await client.workspaces.updateNotificationPolicy('acc_example', {
4105
+ * events: { SignerViewed: false },
4106
+ * owners_receive_all: true,
4107
+ * });
4108
+ * ```
4109
+ */
4110
+ async updateNotificationPolicy(accountId, payload) {
4111
+ const id = this.requireId(accountId, "Account ID");
4112
+ assertRecord(payload, "notification policy");
4113
+ const body = {};
4114
+ if (payload.events !== void 0) {
4115
+ assertBooleanMap(payload.events, "events");
4116
+ body["events"] = { ...payload.events };
4117
+ }
4118
+ if (payload.owners_receive_all !== void 0) {
4119
+ if (typeof payload.owners_receive_all !== "boolean") {
4120
+ throw new ValidationError("owners_receive_all must be a boolean");
4121
+ }
4122
+ body["owners_receive_all"] = payload.owners_receive_all;
4123
+ }
4124
+ if (Object.keys(body).length === 0) {
4125
+ throw new ValidationError("notification policy update must change events or owners_receive_all");
4126
+ }
4127
+ return this.call(
4128
+ "Failed to update notification policy",
4129
+ () => this.http.put(`/accounts/${this.pathSegment(id, "Account ID")}/notification-policy`, body)
3845
4130
  );
3846
4131
  }
3847
4132
  /**
@@ -3850,13 +4135,13 @@ var WorkspaceResource = class extends BaseResource {
3850
4135
  * Request body/query: none.
3851
4136
  *
3852
4137
  * @param accountId - Account whose public branding should be returned.
3853
- * @returns The unwrapped theme:
4138
+ * @returns The unwrapped theme. Colours fall back to the platform default:
3854
4139
  * ```jsonc
3855
4140
  * {
3856
4141
  * "account_name": "Acme Inc.",
3857
- * "primary_color": "aabbcc",
3858
- * "secondary_color": "112233",
3859
- * "logo": "https://api.assinafy.com.br/v1/accounts/account-id/logo"
4142
+ * "primary_color": "aabbcc", // button background
4143
+ * "secondary_color": "112233", // button text
4144
+ * "logo": "https://api.assinafy.com.br/v1/accounts/account-id/logo" // null without a logo
3860
4145
  * }
3861
4146
  * ```
3862
4147
  * @throws {ValidationError} If `accountId` is empty.
@@ -4770,31 +5055,98 @@ var WebhookResource = class extends BaseResource {
4770
5055
  /**
4771
5056
  * Replace an endpoint's signing secret and return the new one
4772
5057
  * (`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret/rotate`).
4773
- * The old secret stops working immediately: deliveries sent after the
4774
- * rotation are signed only with the new secret, so update the receiver at
4775
- * once. OAuth tokens need the `webhooks:write` scope.
5058
+ *
5059
+ * Without `keep_previous` the old secret stops at once: update the receiver
5060
+ * immediately. With `keep_previous: true` both secrets sign deliveries for
5061
+ * 24 hours (each delivery carries one `v1,` entry per secret, which
5062
+ * `webhookVerifier.verifySignature()` already accepts), so the receiver can
5063
+ * switch without dropping events; rotating again ends the overlap. OAuth
5064
+ * tokens need the `webhooks:write` scope.
4776
5065
  *
4777
5066
  * @param endpointId - The endpoint ID.
4778
5067
  * @param accountId - Override the client's default account ID.
5068
+ * @param options - `keep_previous`: keep the old secret signing for 24 hours.
4779
5069
  * @returns The new secret:
4780
5070
  * ```jsonc
4781
- * { "secret": "whsec_bmV3LWtleS1iYXNlNjQtZW5jb2RlZA==" }
5071
+ * {
5072
+ * "secret": "whsec_bmV3LWtleS1iYXNlNjQtZW5jb2RlZA==",
5073
+ * "previous_secret_expires_at": "2026-11-12T14:00:00Z" // only with keep_previous: true
5074
+ * }
4782
5075
  * ```
4783
- * @throws {ValidationError} If `endpointId` is empty or no account ID is
4784
- * available.
5076
+ * @throws {ValidationError} If `endpointId` is empty, no account ID is
5077
+ * available, or `keep_previous` is not a boolean.
4785
5078
  * @throws {ApiError} `400` when signing is disabled on the endpoint; `404`
4786
5079
  * if it does not exist.
4787
5080
  *
4788
5081
  * @example
4789
5082
  * ```ts
4790
- * const { secret } = await client.webhooks.rotateEndpointSecret(endpoint.id);
5083
+ * const { secret } = await client.webhooks.rotateEndpointSecret(endpoint.id, undefined, {
5084
+ * keep_previous: true,
5085
+ * });
4791
5086
  * await secretStore.put('assinafy-webhook-secret', secret);
4792
5087
  * ```
4793
5088
  */
4794
- async rotateEndpointSecret(endpointId, accountId) {
5089
+ async rotateEndpointSecret(endpointId, accountId, options = {}) {
5090
+ assertRecord(options, "rotation options");
5091
+ if (options.keep_previous !== void 0 && typeof options.keep_previous !== "boolean") {
5092
+ throw new ValidationError("keep_previous must be a boolean");
5093
+ }
4795
5094
  const path2 = `${this.endpointPath(endpointId, accountId)}/secret/rotate`;
5095
+ const body = options.keep_previous === void 0 ? void 0 : { keep_previous: options.keep_previous };
4796
5096
  this.logger.info("Rotating webhook endpoint secret");
4797
- return this.call("Failed to rotate webhook endpoint secret", () => this.http.post(path2));
5097
+ return this.call("Failed to rotate webhook endpoint secret", () => this.http.post(path2, body));
5098
+ }
5099
+ /**
5100
+ * Send the endpoint one `webhook_test` event now
5101
+ * (`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/test`).
5102
+ *
5103
+ * Signed and sent like any delivery, to this endpoint only, also while it is
5104
+ * paused or inactive; it neither lifts nor counts toward a pause. The
5105
+ * endpoint has 10 seconds to answer. The event's `payload` and `origin` are
5106
+ * `null`, and its `subject`/`object` describe the endpoint (never its
5107
+ * secret). Up to 10 tests per user every 10 minutes; OAuth tokens need
5108
+ * `webhooks:write`.
5109
+ *
5110
+ * @param endpointId - The endpoint ID.
5111
+ * @param accountId - Override the client's default account ID.
5112
+ * @returns The delivery attempt, also listed in the delivery history:
5113
+ * ```jsonc
5114
+ * {
5115
+ * "resource": "activity_dispatching_history",
5116
+ * "id": "1052b3c4d5e6f7a8b9c0d1e2f3a4",
5117
+ * "event": "webhook_test",
5118
+ * "activity_id": 8240001,
5119
+ * "endpoint_id": "1052b0e1f2a3b4c5d6e7f8a9b0c1",
5120
+ * "endpoint": "https://hooks.example.com/assinafy",
5121
+ * "payload": { // the event as delivered
5122
+ * "id": 8240001, "event": "webhook_test", "payload": null, "origin": null,
5123
+ * "account_id": "acc_example", "subject": { "type": "ActivityEventSubscription" }
5124
+ * },
5125
+ * "delivered": true,
5126
+ * "webhook_id": "msg_2v9TQ0a7",
5127
+ * "attempt": 1,
5128
+ * "kind": "manual",
5129
+ * "will_retry": false,
5130
+ * "duration_ms": 182,
5131
+ * "http_status": 200,
5132
+ * "response_body": "ok",
5133
+ * "error": null,
5134
+ * "created_at": "2026-11-11T14:00:00Z",
5135
+ * "updated_at": "2026-11-11T14:00:00Z"
5136
+ * }
5137
+ * ```
5138
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is available.
5139
+ * @throws {ApiError} `404` for an unknown endpoint, `429` past 10 tests in 10 minutes.
5140
+ *
5141
+ * @example
5142
+ * ```ts
5143
+ * const attempt = await client.webhooks.testEndpoint(endpoint.id);
5144
+ * if (!attempt.delivered) console.warn(attempt.http_status, attempt.error);
5145
+ * ```
5146
+ */
5147
+ async testEndpoint(endpointId, accountId) {
5148
+ const path2 = `${this.endpointPath(endpointId, accountId)}/test`;
5149
+ return this.call("Failed to send webhook test delivery", () => this.http.post(path2));
4798
5150
  }
4799
5151
  endpointsPath(accountId) {
4800
5152
  const id = this.pathSegment(this.accountId(accountId), "Account ID");
@@ -6081,7 +6433,10 @@ var OAuthResource = class extends BaseResource {
6081
6433
  * `['documents:read', 'documents:write', 'offline_access']`. Ask for the
6082
6434
  * minimum: the user approves all of them or none. Add `offline_access` to
6083
6435
  * receive a refresh token and `openid` to receive an `id_token`.
6084
- * `webhooks:write` permits subscription updates and inactivation.
6436
+ * `account:read` reads the workspace profile, theme, logo, KPIs, webhook
6437
+ * subscription and endpoints, and its signing features; `webhooks:write`
6438
+ * changes the subscription, manages endpoints, re-sends and tests
6439
+ * deliveries, and can obtain a new signing secret (signing on, or rotation).
6085
6440
  * @param options.authorizationEndpoint - Skip discovery by supplying the
6086
6441
  * endpoint yourself. Defaults to the discovered
6087
6442
  * `authorization_endpoint`.
@@ -6307,6 +6662,8 @@ var OAuthResource = class extends BaseResource {
6307
6662
  * @throws {OAuthError} `invalid_grant` for a spent, expired, replayed or
6308
6663
  * mismatched code; `invalid_client` for a bad `client_id`/`client_secret`;
6309
6664
  * `invalid_target` for a `resource` mismatch.
6665
+ * @throws {ApiError} `429` when the caller's IP is rate limited; token calls
6666
+ * are never retried automatically, so wait `rateLimit.retryAfter` seconds.
6310
6667
  *
6311
6668
  * @example
6312
6669
  * ```ts
@@ -6381,6 +6738,8 @@ var OAuthResource = class extends BaseResource {
6381
6738
  * @throws {OAuthError} `invalid_grant` when the refresh token was already
6382
6739
  * used, expired, or the user reconnected with different permissions — ask
6383
6740
  * the user to reconnect. `invalid_client` for bad client credentials.
6741
+ * @throws {ApiError} `429` when the caller's IP is rate limited (not retried
6742
+ * automatically: a replayed refresh token ends the connection).
6384
6743
  *
6385
6744
  * @example
6386
6745
  * ```ts
@@ -6665,6 +7024,11 @@ function toSearchParams(params) {
6665
7024
 
6666
7025
  // src/resources/fields.ts
6667
7026
  var FieldsResource = class extends BaseResource {
7027
+ signerHttp;
7028
+ constructor(http, defaultAccountId, logger, publicHttp) {
7029
+ super(http, defaultAccountId, logger);
7030
+ this.signerHttp = withoutCredentials(publicHttp ?? http);
7031
+ }
6668
7032
  /**
6669
7033
  * Create a field definition (`POST /accounts/{accountId}/fields`).
6670
7034
  *
@@ -6916,9 +7280,9 @@ var FieldsResource = class extends BaseResource {
6916
7280
  * Validate a single value against a field definition
6917
7281
  * (`POST /accounts/{accountId}/fields/{fieldId}/validate`).
6918
7282
  *
6919
- * The operation uses the client's API-key/Bearer authentication.
6920
- * `signerAccessCode` is a compatibility query and is sent as
6921
- * `signer-access-code` when supplied.
7283
+ * Without `signerAccessCode` the call uses the workspace credentials. With
7284
+ * it, the code is sent as the `signer-access-code` query on the
7285
+ * credential-free transport, as a custom signing UI does.
6922
7286
  *
6923
7287
  * Request body (`application/json`):
6924
7288
  * ```jsonc
@@ -6930,9 +7294,9 @@ var FieldsResource = class extends BaseResource {
6930
7294
  * @param fieldId - The field definition to validate against.
6931
7295
  * @param value - The value to check (validated against the field's
6932
7296
  * type/regex). Sent as `{ value }` in the request body.
6933
- * @param options - Account override and optional legacy `signerAccessCode`.
7297
+ * @param options - Account override and optional `signerAccessCode`.
6934
7298
  * @param options.accountId - Override the client's default workspace.
6935
- * @param options.signerAccessCode - Legacy signer code sent as a query parameter.
7299
+ * @param options.signerAccessCode - Authenticate as the signer instead of the workspace.
6936
7300
  * @returns The validation result. Response shape:
6937
7301
  * ```jsonc
6938
7302
  * {
@@ -6943,7 +7307,9 @@ var FieldsResource = class extends BaseResource {
6943
7307
  * ```
6944
7308
  * @throws {ValidationError} If `fieldId` or the account ID is missing, or
6945
7309
  * `value` is `undefined`.
6946
- * @throws {ApiError} If the API rejects the request.
7310
+ * @throws {ApiError} `400` for a malformed request, `403` when the code or
7311
+ * credentials cannot reach the workspace, `404` for a field outside it, `410`
7312
+ * when the signer's access code is closed.
6947
7313
  *
6948
7314
  * @example
6949
7315
  * ```ts
@@ -6965,7 +7331,7 @@ var FieldsResource = class extends BaseResource {
6965
7331
  const params = options.signerAccessCode ? { "signer-access-code": options.signerAccessCode } : void 0;
6966
7332
  return this.call(
6967
7333
  "Failed to validate field value",
6968
- () => this.http.post(
7334
+ () => this.transportFor(options.signerAccessCode).post(
6969
7335
  `/accounts/${this.pathSegment(id, "Account ID")}/fields/${this.pathSegment(fid, "Field ID")}/validate`,
6970
7336
  { value },
6971
7337
  { params }
@@ -6977,9 +7343,8 @@ var FieldsResource = class extends BaseResource {
6977
7343
  * (`POST /accounts/{accountId}/fields/validate-multiple`).
6978
7344
  *
6979
7345
  * The request body is the array of `{ field_id, value }` entries itself
6980
- * (not wrapped in an object). The optional `signerAccessCode` query is the
6981
- * same compatibility extension described on
6982
- * {@link FieldsResource.validate}.
7346
+ * (not wrapped in an object). `signerAccessCode` authenticates as described
7347
+ * on {@link FieldsResource.validate}.
6983
7348
  *
6984
7349
  * Request body (`application/json`):
6985
7350
  * ```jsonc
@@ -6992,9 +7357,9 @@ var FieldsResource = class extends BaseResource {
6992
7357
  * ```
6993
7358
  *
6994
7359
  * @param entries - Non-empty array of `{ field_id, value }` pairs.
6995
- * @param options - Account override and optional legacy `signerAccessCode`.
7360
+ * @param options - Account override and optional `signerAccessCode`.
6996
7361
  * @param options.accountId - Override the client's default workspace.
6997
- * @param options.signerAccessCode - Legacy signer code sent as a query parameter.
7362
+ * @param options.signerAccessCode - Authenticate as the signer instead of the workspace.
6998
7363
  * @returns One validation result per entry. Response shape:
6999
7364
  * ```jsonc
7000
7365
  * [
@@ -7003,7 +7368,7 @@ var FieldsResource = class extends BaseResource {
7003
7368
  * ]
7004
7369
  * ```
7005
7370
  * @throws {ValidationError} If `entries` is empty or the account ID is missing.
7006
- * @throws {ApiError} If the API rejects the request.
7371
+ * @throws {ApiError} `400`, `403`, `404` or `410`, as for {@link FieldsResource.validate}.
7007
7372
  *
7008
7373
  * @example
7009
7374
  * ```ts
@@ -7031,7 +7396,7 @@ var FieldsResource = class extends BaseResource {
7031
7396
  }));
7032
7397
  return this.call(
7033
7398
  "Failed to validate field values",
7034
- () => this.http.post(
7399
+ () => this.transportFor(options.signerAccessCode).post(
7035
7400
  `/accounts/${this.pathSegment(id, "Account ID")}/fields/validate-multiple`,
7036
7401
  body,
7037
7402
  { params }
@@ -7065,6 +7430,10 @@ var FieldsResource = class extends BaseResource {
7065
7430
  async listTypes() {
7066
7431
  return this.call("Failed to list field types", () => this.http.get("/field-types"));
7067
7432
  }
7433
+ /** A signer access code must never travel with the workspace credentials. */
7434
+ transportFor(signerAccessCode) {
7435
+ return signerAccessCode === void 0 ? this.http : this.signerHttp;
7436
+ }
7068
7437
  };
7069
7438
  function validateFieldPayload(payload) {
7070
7439
  if (payload.regex !== void 0 && payload.regex !== null && typeof payload.regex !== "string") {
@@ -7097,11 +7466,17 @@ var SignerDocumentsResource = class extends BaseResource {
7097
7466
  * (`GET /signers/{signer_id}/document?signer-access-code=…`).
7098
7467
  *
7099
7468
  * The signer-side counterpart of {@link DocumentResource.details}, authorised
7100
- * by the signer's access code rather than the workspace API key.
7469
+ * by the signer's access code rather than the workspace API key. Unlike
7470
+ * {@link SignerDocumentsResource.getAssignment} it does not record a view and
7471
+ * answers before a certificate or identity-check signer confirms their data,
7472
+ * so a link learns its envelope here.
7101
7473
  *
7102
7474
  * @param signerId - The signer whose current document is fetched.
7103
7475
  * @param signerAccessCode - The signer's access code, from their signing link.
7104
- * @returns The document in the full {@link IDocumentDetailsResponse} shape:
7476
+ * @param options - `expand: ['envelope']` adds the code's envelope (`{ id, name }`, or `null`).
7477
+ * @returns The {@link ISigningDocument}. Once the code is closed (30 minutes
7478
+ * after the signer is done) only `id`, `name`, `status`, `current_signer`,
7479
+ * `certified_copy` and `envelope` remain, with `is_signer_access_closed: true`:
7105
7480
  * ```jsonc
7106
7481
  * {
7107
7482
  * "resource": "document",
@@ -7124,26 +7499,38 @@ var SignerDocumentsResource = class extends BaseResource {
7124
7499
  * { "id": "103acccd5c73...", "number": 1, "height": 1651, "width": 1275,
7125
7500
  * "download_url": "https://api.assinafy.com.br/v1/documents/103acccd.../pages/103acccd5c73.../download" }
7126
7501
  * ],
7502
+ * "current_signer": {
7503
+ * "id": "19e6b92e7895332ed9708535d8c",
7504
+ * "full_name": "Example Signer",
7505
+ * "email": "signer@example.com",
7506
+ * "verification_method": "Email",
7507
+ * "notification_methods": ["Email"],
7508
+ * "completed": false
7509
+ * },
7510
+ * "is_signer_access_closed": false,
7511
+ * "certified_copy": { "available": false, "notification_method": "Email", "resends_left": null },
7512
+ * "envelope": { "id": "1052a1f0c3d4e5f6a7b8c9d0e1f2", "name": "Admission kit" }, // with expand
7127
7513
  * "created_at": "2026-07-19T14:56:54Z",
7128
7514
  * "updated_at": "2026-07-19T14:56:56Z"
7129
7515
  * }
7130
7516
  * ```
7131
7517
  * @throws {ValidationError} If `signerId` or `signerAccessCode` is missing.
7132
- * @throws {ApiError} If the access code is invalid or expired.
7518
+ * @throws {ApiError} `400` while the signer's step has not started, `401` for an
7519
+ * invalid code, `404` for an unknown signer.
7133
7520
  *
7134
7521
  * @example
7135
7522
  * ```ts
7136
- * const doc = await client.signerDocuments.getCurrent(signerId, accessCode);
7137
- * console.log(doc.status, doc.pages.length);
7523
+ * const doc = await client.signerDocuments.getCurrent(signerId, accessCode, { expand: ['envelope'] });
7524
+ * if (doc.is_signer_access_closed) console.log(doc.certified_copy.available);
7138
7525
  * ```
7139
7526
  */
7140
- async getCurrent(signerId, signerAccessCode) {
7527
+ async getCurrent(signerId, signerAccessCode, options = {}) {
7141
7528
  const sid = this.requireId(signerId, "Signer ID");
7142
7529
  const code = this.requireId(signerAccessCode, "signer-access-code");
7143
7530
  return this.call(
7144
7531
  "Failed to fetch current signer document",
7145
7532
  () => this.http.get(`/signers/${this.pathSegment(sid, "Signer ID")}/document`, {
7146
- params: { "signer-access-code": code }
7533
+ params: { "signer-access-code": code, ...signingReadParams(options) }
7147
7534
  })
7148
7535
  );
7149
7536
  }
@@ -7158,9 +7545,10 @@ var SignerDocumentsResource = class extends BaseResource {
7158
7545
  *
7159
7546
  * @param signerId - The signer whose documents are listed.
7160
7547
  * @param signerAccessCode - The signer's access code, from their signing link.
7161
- * @param params - Pagination: `page`, `per-page` (also accepts `per_page`).
7162
- * @returns Matching documents in the compact {@link IDocumentListItem} shape,
7163
- * with pagination in `meta`:
7548
+ * @param params - `envelope_id` (only that envelope's documents) and pagination:
7549
+ * `page`, `per-page` (also accepts `per_page`).
7550
+ * @returns Matching documents with pagination in `meta`. Each carries its
7551
+ * `assignment` (without `signing_urls` when read with a code) and `pages`:
7164
7552
  * ```jsonc
7165
7553
  * {
7166
7554
  * "data": [
@@ -7184,11 +7572,13 @@ var SignerDocumentsResource = class extends BaseResource {
7184
7572
  * }
7185
7573
  * ```
7186
7574
  * @throws {ValidationError} If `signerId` or `signerAccessCode` is missing.
7187
- * @throws {ApiError} If the access code is invalid or expired.
7575
+ * @throws {ApiError} `400` for a non-text `envelope_id` or a pending step,
7576
+ * `403` for another signer's code, `410` once the code is closed.
7188
7577
  *
7189
7578
  * @example
7190
7579
  * ```ts
7191
7580
  * const { data, meta } = await client.signerDocuments.list(signerId, accessCode, {
7581
+ * envelope_id: envelopeId,
7192
7582
  * 'per-page': 20,
7193
7583
  * });
7194
7584
  * ```
@@ -7215,8 +7605,8 @@ var SignerDocumentsResource = class extends BaseResource {
7215
7605
  * @param signerId - The signer whose documents are searched.
7216
7606
  * @param signerAccessCode - The signer's access code, from their signing link.
7217
7607
  * @param search - Free-text term matched against the document name.
7218
- * @returns Matching documents for that signer, in the compact
7219
- * {@link IDocumentListItem} shape, with pagination in `meta`:
7608
+ * @param params - `envelope_id`: only that envelope's documents.
7609
+ * @returns Matching documents for that signer, with pagination in `meta`:
7220
7610
  * ```jsonc
7221
7611
  * {
7222
7612
  * "data": [
@@ -7240,7 +7630,7 @@ var SignerDocumentsResource = class extends BaseResource {
7240
7630
  * }
7241
7631
  * ```
7242
7632
  * @throws {ValidationError} If `signerId` or `signerAccessCode` is missing.
7243
- * @throws {ApiError} If the access code is invalid or expired.
7633
+ * @throws {ApiError} `400`, `403` or `410`, as for {@link SignerDocumentsResource.list}.
7244
7634
  *
7245
7635
  * @example
7246
7636
  * ```ts
@@ -7251,16 +7641,13 @@ var SignerDocumentsResource = class extends BaseResource {
7251
7641
  * );
7252
7642
  * ```
7253
7643
  */
7254
- async search(signerId, signerAccessCode, search) {
7644
+ async search(signerId, signerAccessCode, search, params = {}) {
7255
7645
  const sid = this.requireId(signerId, "Signer ID");
7256
7646
  const code = this.requireId(signerAccessCode, "signer-access-code");
7257
- if (search !== void 0 && typeof search !== "string") {
7258
- throw new ValidationError("search must be a string");
7259
- }
7260
7647
  return this.callList(
7261
7648
  "Failed to search signer documents",
7262
7649
  () => this.http.get(`/signers/${this.pathSegment(sid, "Signer ID")}/documents/search`, {
7263
- params: cleanParams({ "signer-access-code": code, search })
7650
+ params: { "signer-access-code": code, ...searchParams(search, params) }
7264
7651
  })
7265
7652
  );
7266
7653
  }
@@ -7273,8 +7660,8 @@ var SignerDocumentsResource = class extends BaseResource {
7273
7660
  * code. No `signer-access-code` is sent.
7274
7661
  *
7275
7662
  * @param signerId - The signer whose documents are listed.
7276
- * @param params - Pagination: `page`, `per-page` (also accepts `per_page`).
7277
- * @returns Documents in the compact {@link IDocumentListItem} shape, with
7663
+ * @param params - `envelope_id` and pagination: `page`, `per-page` (also accepts `per_page`).
7664
+ * @returns Documents in the {@link IDocumentListItem} shape, with
7278
7665
  * pagination in `meta` (same shape as {@link SignerDocumentsResource.list}):
7279
7666
  * ```jsonc
7280
7667
  * {
@@ -7283,7 +7670,8 @@ var SignerDocumentsResource = class extends BaseResource {
7283
7670
  * }
7284
7671
  * ```
7285
7672
  * @throws {ValidationError} If `signerId` is missing.
7286
- * @throws {ApiError} `401` if the workspace credentials are rejected.
7673
+ * @throws {ApiError} `401` if the workspace credentials are rejected, `403` when a
7674
+ * role or OAuth scope refuses it, `404` for a signer outside the workspace.
7287
7675
  *
7288
7676
  * @example
7289
7677
  * ```ts
@@ -7292,11 +7680,11 @@ var SignerDocumentsResource = class extends BaseResource {
7292
7680
  */
7293
7681
  async listAsWorkspace(signerId, params = {}) {
7294
7682
  const sid = this.pathSegment(signerId, "Signer ID");
7683
+ const query = cleanListParams(params);
7684
+ delete query["signer-access-code"];
7295
7685
  return this.callList(
7296
7686
  "Failed to list signer documents",
7297
- () => this.workspaceHttp.get(`/signers/${sid}/documents`, {
7298
- params: cleanListParams(params)
7299
- })
7687
+ () => this.workspaceHttp.get(`/signers/${sid}/documents`, { params: query })
7300
7688
  );
7301
7689
  }
7302
7690
  /**
@@ -7309,53 +7697,45 @@ var SignerDocumentsResource = class extends BaseResource {
7309
7697
  *
7310
7698
  * @param signerId - The signer whose documents are searched.
7311
7699
  * @param search - Free-text term matched against the document name.
7700
+ * @param params - `envelope_id`: only that envelope's documents.
7312
7701
  * @returns Matching documents with pagination in `meta`, as
7313
7702
  * {@link SignerDocumentsResource.listAsWorkspace} returns.
7314
7703
  * @throws {ValidationError} If `signerId` is missing or `search` is not a string.
7315
- * @throws {ApiError} `401` if the workspace credentials are rejected.
7704
+ * @throws {ApiError} `401`, `403` or `404`, as for {@link SignerDocumentsResource.listAsWorkspace}.
7316
7705
  *
7317
7706
  * @example
7318
7707
  * ```ts
7319
7708
  * const { data } = await client.signerDocuments.searchAsWorkspace(signerId, 'agreement');
7320
7709
  * ```
7321
7710
  */
7322
- async searchAsWorkspace(signerId, search) {
7711
+ async searchAsWorkspace(signerId, search, params = {}) {
7323
7712
  const sid = this.pathSegment(signerId, "Signer ID");
7324
- if (search !== void 0 && typeof search !== "string") {
7325
- throw new ValidationError("search must be a string");
7326
- }
7327
7713
  return this.callList(
7328
7714
  "Failed to search signer documents",
7329
7715
  () => this.workspaceHttp.get(`/signers/${sid}/documents/search`, {
7330
- params: cleanParams({ search })
7716
+ params: searchParams(search, params)
7331
7717
  })
7332
7718
  );
7333
7719
  }
7334
7720
  /**
7335
- * Download one of a signer's document artifacts as raw bytes
7336
- * (`GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`).
7721
+ * Download the original PDF a signer is asked to sign
7722
+ * (`GET /signers/{signer_id}/documents/{document_id}/download/original`).
7337
7723
  *
7338
- * The signer-side counterpart of {@link DocumentResource.download}: same
7339
- * artifact names, exposed by the API as a public signer-link endpoint. The
7340
- * optional access-code argument is retained for compatibility with deployed
7341
- * environments that still accept or require the legacy query parameter. The
7342
- * `certificated` and `bundle` exist only once the document is fully signed.
7343
- * `pades` exists only when the document had a Digital Certificate signer.
7344
- * A bundle contains original, certificated, and certificate-page artifacts,
7345
- * plus PAdES when present.
7724
+ * Only `original` is available with an access code; the certified copy is
7725
+ * sent to the signer instead (see {@link SignerDocumentsResource.resendCertifiedCopy}).
7726
+ * The API redirects a request it cannot serve to its expired-link page, so
7727
+ * the SDK does not follow redirects here: that case throws instead of
7728
+ * returning the page's HTML.
7346
7729
  *
7347
7730
  * @param signerId - The signer requesting the download.
7348
7731
  * @param documentId - The document to download.
7349
- * @param artifactName - Which artifact to fetch (`original`, `certificated`,
7350
- * `certificate-page`, `pades`, or `bundle`).
7351
- * @param signerAccessCode - Optional legacy signer access code. Omit it for
7352
- * the official public request shape.
7353
- * @returns The raw artifact bytes as a Node `Buffer` (PDF except for the
7354
- * ZIP `bundle`).
7355
- * @throws {ValidationError} If `signerId` or `documentId` is missing,
7356
- * `artifactName` is not one of the five documented names, or an explicitly
7357
- * supplied legacy `signerAccessCode` is blank.
7358
- * @throws {ApiError} `404` if the artifact does not exist yet.
7732
+ * @param artifactName - `original`, the only artifact a signer can download.
7733
+ * @param signerAccessCode - The signer's access code, from their signing link.
7734
+ * @returns The PDF bytes as a Node `Buffer`.
7735
+ * @throws {ValidationError} If an ID or the code is missing, or the artifact is not `original`.
7736
+ * @throws {ApiError} `302` when the code is missing or closed, `400` while the
7737
+ * signer's step has not started, `403` for another artifact, `404` for a
7738
+ * document the code does not reach, `410` once the code is closed.
7359
7739
  *
7360
7740
  * @example
7361
7741
  * ```ts
@@ -7363,6 +7743,7 @@ var SignerDocumentsResource = class extends BaseResource {
7363
7743
  * signerId,
7364
7744
  * documentId,
7365
7745
  * 'original',
7746
+ * accessCode,
7366
7747
  * );
7367
7748
  * await fs.promises.writeFile('to-sign.pdf', pdf);
7368
7749
  * ```
@@ -7370,16 +7751,15 @@ var SignerDocumentsResource = class extends BaseResource {
7370
7751
  async download(signerId, documentId, artifactName, signerAccessCode) {
7371
7752
  const sid = this.requireId(signerId, "Signer ID");
7372
7753
  const did = this.requireId(documentId, "Document ID");
7373
- assertDocumentArtifactName(artifactName);
7374
- const code = signerAccessCode === void 0 ? void 0 : this.requireId(signerAccessCode, "signer-access-code");
7754
+ if (artifactName !== "original") {
7755
+ throw new ValidationError("A signer can download only the original artifact");
7756
+ }
7757
+ const code = this.requireId(signerAccessCode, "signer-access-code");
7375
7758
  return this.callBinary(
7376
7759
  "Failed to download signer document",
7377
7760
  () => this.http.get(
7378
- `/signers/${this.pathSegment(sid, "Signer ID")}/documents/${this.pathSegment(did, "Document ID")}/download/${this.pathSegment(artifactName, "Artifact name")}`,
7379
- code === void 0 ? { responseType: "arraybuffer" } : {
7380
- responseType: "arraybuffer",
7381
- params: { "signer-access-code": code }
7382
- }
7761
+ `/signers/${this.pathSegment(sid, "Signer ID")}/documents/${this.pathSegment(did, "Document ID")}/download/original`,
7762
+ { ...BINARY_NO_REDIRECT, params: { "signer-access-code": code } }
7383
7763
  )
7384
7764
  );
7385
7765
  }
@@ -7625,10 +8005,15 @@ var SignerDocumentsResource = class extends BaseResource {
7625
8005
  * flag.
7626
8006
  *
7627
8007
  * @param signerAccessCode - The signer's access code, from their signing link.
7628
- * @returns Resolves when the API acknowledges the operation. The response
7629
- * envelope has no `data` field and is intentionally discarded.
8008
+ * @returns The signer's acceptance state, or `null` from deployments that
8009
+ * acknowledge without data:
8010
+ * ```jsonc
8011
+ * { "full_name": "Example Signer", "email": "signer@example.com", "has_accepted_terms": true }
8012
+ * ```
7630
8013
  * @throws {ValidationError} If `signerAccessCode` is missing.
7631
- * @throws {ApiError} If the access code is invalid or expired.
8014
+ * @throws {ApiError} `400` while the signer's verification is not done (e.g.
8015
+ * the e-mail code) or their step has not started, `401` for an invalid code,
8016
+ * `410` once the code is closed.
7632
8017
  *
7633
8018
  * @example
7634
8019
  * ```ts
@@ -7638,12 +8023,13 @@ var SignerDocumentsResource = class extends BaseResource {
7638
8023
  */
7639
8024
  async acceptTerms(signerAccessCode) {
7640
8025
  const code = this.requireId(signerAccessCode, "signer-access-code");
7641
- return this.callVoid(
8026
+ const data = await this.call(
7642
8027
  "Failed to accept terms",
7643
8028
  () => this.http.put("/signers/accept-terms", void 0, {
7644
8029
  params: { "signer-access-code": code }
7645
8030
  })
7646
8031
  );
8032
+ return data ?? null;
7647
8033
  }
7648
8034
  /**
7649
8035
  * Verify the signer's email or WhatsApp one-time password
@@ -7694,12 +8080,56 @@ var SignerDocumentsResource = class extends BaseResource {
7694
8080
  )
7695
8081
  );
7696
8082
  }
8083
+ /**
8084
+ * Confirm the signer's contact data before signing
8085
+ * (`PUT /documents/{documentId}/signers/confirm-data?signer-access-code=…`).
8086
+ *
8087
+ * Send the contact the signer's channel needs: `email` for e-mail
8088
+ * verification or notification, `whatsapp_phone_number` for WhatsApp. Each
8089
+ * is saved when the signer has none; otherwise it must be theirs, so it
8090
+ * cannot change the record. `has_accepted_terms: true` also records the
8091
+ * terms, which opens `getAssignment()` for a `DigitalCertificate` signer.
8092
+ * With an envelope code it acts on the document the route names. Only the
8093
+ * fields provided are sent.
8094
+ *
8095
+ * Request body (`application/json`):
8096
+ * ```jsonc
8097
+ * {
8098
+ * "email": "signer@example.com",
8099
+ * "has_accepted_terms": true
8100
+ * }
8101
+ * ```
8102
+ *
8103
+ * @param documentId - The document the signer is confirming data for.
8104
+ * @param signerAccessCode - The signer's access code, from their signing link.
8105
+ * @param payload - `email`, `whatsapp_phone_number` and `has_accepted_terms`.
8106
+ * `full_name`/`government_id` are forwarded only for older deployments.
8107
+ * @returns `null` on production, which answers `data: []`; older deployments
8108
+ * return the signer:
8109
+ * ```jsonc
8110
+ * { "resource": "signer", "id": "19e6b92e7895332ed9708535d8c", "full_name": "Example Signer",
8111
+ * "email": "signer@example.com", "whatsapp_phone_number": null, "has_accepted_terms": true }
8112
+ * ```
8113
+ * @throws {ValidationError} If `documentId` or `signerAccessCode` is missing,
8114
+ * or a supplied value is malformed.
8115
+ * @throws {ApiError} `400` when a contact the signer's methods need is missing,
8116
+ * invalid or not theirs, or their step has not started; `404` for a document
8117
+ * the code does not reach; `410` once the code is closed.
8118
+ *
8119
+ * @example
8120
+ * ```ts
8121
+ * await client.signerDocuments.confirmData(documentId, accessCode, {
8122
+ * email: 'signer@example.com',
8123
+ * has_accepted_terms: true,
8124
+ * });
8125
+ * ```
8126
+ */
7697
8127
  async confirmData(documentId, signerAccessCode, payload) {
7698
8128
  assertRecord(payload, "signer confirmation payload");
7699
8129
  validateConfirmDataPayload(payload);
7700
8130
  const did = this.requireId(documentId, "Document ID");
7701
8131
  const code = this.requireId(signerAccessCode, "signer-access-code");
7702
- return this.call(
8132
+ const data = await this.call(
7703
8133
  "Failed to confirm signer data",
7704
8134
  () => this.http.put(
7705
8135
  `/documents/${this.pathSegment(did, "Document ID")}/signers/confirm-data`,
@@ -7713,6 +8143,7 @@ var SignerDocumentsResource = class extends BaseResource {
7713
8143
  { params: { "signer-access-code": code } }
7714
8144
  )
7715
8145
  );
8146
+ return data !== null && typeof data === "object" && !Array.isArray(data) ? data : null;
7716
8147
  }
7717
8148
  async uploadSignature(signerAccessCode, image, options = {}) {
7718
8149
  const code = this.requireId(signerAccessCode, "signer-access-code");
@@ -7793,14 +8224,17 @@ var SignerDocumentsResource = class extends BaseResource {
7793
8224
  * the SDK never automatically replays this particular `GET` after a `429`.
7794
8225
  *
7795
8226
  * @param signerAccessCode - The signer's access code, from their signing link.
7796
- * @param hasAcceptedTerms - Maps to the `has_accepted_terms` query param
7797
- * (server default `false`); pass `true` once the signer has accepted terms.
7798
- * `false`/`undefined` is omitted only when `undefined` (an explicit `false`
7799
- * is still sent).
7800
- * @returns The document to sign, including its `assignment` (the
7801
- * {@link IAssignment} shape: `signers`, `items`, `summary`, `signing_urls`)
7802
- * from which the `itemId` / `fieldId` / `pageId` values for
7803
- * {@link SignerDocumentsResource.sign} are read:
8227
+ * @param options - `true`/`false` (the `has_accepted_terms` query, kept for
8228
+ * existing calls) or an options object:
8229
+ * `hasAcceptedTerms` (an explicit `false` is still sent), `expand:
8230
+ * ['envelope']` (adds the code's envelope), and `documentId` (with an
8231
+ * envelope code, open another document of that envelope the signer is on).
8232
+ * @returns The {@link ISigningDocument}. Its `assignment` carries only this
8233
+ * signer's items — no other signers, `signing_urls`, copy receivers or
8234
+ * `summary` — from which the `itemId` / `fieldId` / `pageId` values for
8235
+ * {@link SignerDocumentsResource.sign} are read. A closed code returns
8236
+ * only `id`, `name`, `status`, `current_signer`, `certified_copy` and
8237
+ * `envelope`, with `is_signer_access_closed: true`:
7804
8238
  * ```jsonc
7805
8239
  * {
7806
8240
  * "resource": "document",
@@ -7831,9 +8265,12 @@ var SignerDocumentsResource = class extends BaseResource {
7831
8265
  * { "id": "item-1", "page": { "id": "page-1", "number": 1, "height": 1651, "width": 1275,
7832
8266
  * "download_url": "https://..." }, "signer": { "id": "19e6b92e..." },
7833
8267
  * "field": { "id": "field-1", "type": "signature" }, "value": null, "completed": false }
7834
- * ],
7835
- * "summary": { "signer_count": 1, "completed_count": 0, "signers": [] }
8268
+ * ]
7836
8269
  * },
8270
+ * "current_signer": { "id": "19e6b92e7895332ed9708535d8c", "verification_method": "Email",
8271
+ * "notification_methods": ["Email"], "completed": false },
8272
+ * "is_signer_access_closed": false,
8273
+ * "certified_copy": { "available": false, "notification_method": "Email", "resends_left": null },
7837
8274
  * "pages": [
7838
8275
  * { "id": "103acccd5c73...", "number": 1, "height": 1651, "width": 1275,
7839
8276
  * "download_url": "https://api.assinafy.com.br/v1/documents/103acccd.../pages/103acccd5c73.../download" }
@@ -7842,75 +8279,233 @@ var SignerDocumentsResource = class extends BaseResource {
7842
8279
  * "updated_at": "2026-07-19T14:56:56Z"
7843
8280
  * }
7844
8281
  * ```
7845
- * @throws {ValidationError} If `signerAccessCode` is missing.
7846
- * @throws {ApiError} `400` when DigitalCertificate identity/terms are not
7847
- * confirmed; `401`/`403` if the access code is invalid or expired; `409`
7848
- * while the document is still being prepared.
8282
+ * @throws {ValidationError} If `signerAccessCode` is missing or an option is malformed.
8283
+ * @throws {ApiError} `400` when a DigitalCertificate signer has not confirmed
8284
+ * data and terms, the signer's step has not started, or `documentId` is
8285
+ * not an ID; `401` for an invalid code; `404` when `documentId` is outside
8286
+ * the code's envelope; `409` (`DocumentNotReady`) while the document is
8287
+ * still being prepared.
7849
8288
  *
7850
8289
  * @example
7851
8290
  * ```ts
7852
- * // query → ?signer-access-code=<code>&has_accepted_terms=true
7853
- * const assignment = await client.signerDocuments.getAssignment(accessCode, true);
8291
+ * // query → ?signer-access-code=<code>&has_accepted_terms=true&expand=envelope
8292
+ * const doc = await client.signerDocuments.getAssignment(accessCode, {
8293
+ * hasAcceptedTerms: true,
8294
+ * expand: ['envelope'],
8295
+ * });
7854
8296
  * ```
7855
8297
  */
7856
- async getAssignment(signerAccessCode, hasAcceptedTerms) {
8298
+ async getAssignment(signerAccessCode, options) {
7857
8299
  const code = this.requireId(signerAccessCode, "signer-access-code");
7858
- if (hasAcceptedTerms !== void 0 && typeof hasAcceptedTerms !== "boolean") {
8300
+ const read = typeof options === "object" && options !== null ? options : options === void 0 ? {} : { hasAcceptedTerms: options };
8301
+ assertRecord(read, "signing read options");
8302
+ if (read.hasAcceptedTerms !== void 0 && typeof read.hasAcceptedTerms !== "boolean") {
7859
8303
  throw new ValidationError("hasAcceptedTerms must be a boolean");
7860
8304
  }
8305
+ if (read.documentId !== void 0) this.requireId(read.documentId, "documentId");
7861
8306
  return this.call(
7862
8307
  "Failed to fetch signer assignment",
7863
8308
  () => this.http.get("/sign", {
7864
8309
  params: cleanParams({
7865
8310
  "signer-access-code": code,
7866
- has_accepted_terms: hasAcceptedTerms
8311
+ has_accepted_terms: read.hasAcceptedTerms,
8312
+ document_id: read.documentId,
8313
+ ...signingReadParams(read)
7867
8314
  })
7868
8315
  })
7869
8316
  );
7870
8317
  }
7871
8318
  /**
7872
- * Submit the signer's field values to sign an assignment
7873
- * (`POST /documents/{documentId}/assignments/{assignmentId}?signer-access-code=…`).
8319
+ * Read the sending workspace's brand for the signing page (`GET /sign/theme`).
7874
8320
  *
7875
- * The precise, field-by-field counterpart of
7876
- * {@link SignerDocumentsResource.signMultiple}: the `entries` array is sent as
7877
- * the request body, each entry addressing one item resolved from
7878
- * {@link SignerDocumentsResource.getAssignment}. The access code
7879
- * authenticates via the `signer-access-code` query param.
7880
- * Virtual signers must call {@link SignerDocumentsResource.confirmData}
7881
- * first. Digital Certificate signers cannot use this endpoint; use the
7882
- * certificate start/complete API flow instead.
8321
+ * Available before verification and after the document is deleted.
8322
+ * `primary_color` is the button background and `secondary_color` its text
8323
+ * (6-digit hex without `#`). The `logo` URL carries no access code: fetch it
8324
+ * with {@link SignerDocumentsResource.downloadLogo}.
7883
8325
  *
7884
- * Request body (`application/json`):
8326
+ * @param signerAccessCode - The signer's access code, from their signing link.
8327
+ * @returns The brand:
7885
8328
  * ```jsonc
7886
- * [
7887
- * {
7888
- * "itemId": "item_example",
7889
- * "fieldId": "field_example",
7890
- * "pageId": "page_example",
7891
- * "value": "Example Signer"
7892
- * }
7893
- * ]
8329
+ * {
8330
+ * "account_name": "Example Ltda",
8331
+ * "primary_color": "1F6FEB",
8332
+ * "secondary_color": "FFFFFF",
8333
+ * "logo": "https://api.assinafy.com.br/v1/sign/logo" // null when the account has none
8334
+ * }
7894
8335
  * ```
7895
- *
7896
- * @param documentId - The document being signed.
7897
- * @param assignmentId - The assignment within that document.
7898
- * @param signerAccessCode - The signer's access code, from their signing link.
7899
- * @param entries - Non-empty array of {@link ISignFieldEntry}
7900
- * (`itemId`, `fieldId`, `pageId`, `value`) — the body sent to the API.
7901
- * @returns The API's signing result object. Its keys are operation-specific,
7902
- * so the SDK preserves them as a {@link Record} without inventing fields.
7903
- * @throws {ValidationError} If any of `documentId`, `assignmentId`, or
7904
- * `signerAccessCode` is missing, or `entries` is empty.
7905
- * @throws {ApiError} `400`/`409` if a value fails validation or the assignment
7906
- * is no longer signable; `401`/`403` if the access code is invalid/expired.
8336
+ * @throws {ValidationError} If `signerAccessCode` is missing.
8337
+ * @throws {ApiError} `400` while the signer's step has not started, `401` for an invalid code.
7907
8338
  *
7908
8339
  * @example
7909
8340
  * ```ts
7910
- * // body → [{ itemId, fieldId, pageId, value: 'Example Signer' }]
7911
- * await client.signerDocuments.sign(documentId, assignmentId, accessCode, [
7912
- * { itemId: 'item-1', fieldId: 'field-1', pageId: 'page-1', value: 'Example Signer' },
7913
- * ]);
8341
+ * const theme = await client.signerDocuments.getTheme(accessCode);
8342
+ * ```
8343
+ */
8344
+ async getTheme(signerAccessCode) {
8345
+ const code = this.requireId(signerAccessCode, "signer-access-code");
8346
+ return this.call(
8347
+ "Failed to fetch signing theme",
8348
+ () => this.http.get("/sign/theme", { params: { "signer-access-code": code } })
8349
+ );
8350
+ }
8351
+ /**
8352
+ * Download the sending workspace's logo for the signing page (`GET /sign/logo`).
8353
+ *
8354
+ * @param signerAccessCode - The signer's access code, from their signing link.
8355
+ * @returns The image bytes (`image/*`).
8356
+ * @throws {ValidationError} If `signerAccessCode` is missing.
8357
+ * @throws {ApiError} `400` while the signer's step has not started, `401` for an
8358
+ * invalid code, `404` when the workspace has no logo.
8359
+ *
8360
+ * @example
8361
+ * ```ts
8362
+ * const logo = await client.signerDocuments.downloadLogo(accessCode);
8363
+ * ```
8364
+ */
8365
+ async downloadLogo(signerAccessCode) {
8366
+ const code = this.requireId(signerAccessCode, "signer-access-code");
8367
+ return this.callBinary(
8368
+ "Failed to download signing logo",
8369
+ () => this.http.get("/sign/logo", {
8370
+ responseType: "arraybuffer",
8371
+ params: { "signer-access-code": code }
8372
+ })
8373
+ );
8374
+ }
8375
+ /**
8376
+ * Send the signer their certified copy again (`POST /sign/certified-copy`).
8377
+ *
8378
+ * The copy goes, with a download link valid for 30 minutes, on the signature
8379
+ * request's channel and only to the contact the signing messages went to.
8380
+ * Works after the signer signed, also once the code is closed. E-mail: once
8381
+ * every 2 minutes and 10 times a day; WhatsApp: once per request.
8382
+ * `certified_copy` on {@link SignerDocumentsResource.getAssignment} says
8383
+ * whether it is available.
8384
+ *
8385
+ * @param signerAccessCode - The signer's access code, from their signing link.
8386
+ * @param documentId - With an envelope code, another document of that envelope.
8387
+ * @returns What was sent:
8388
+ * ```jsonc
8389
+ * { "available": true, "notification_method": "Email", "resends_left": null, "sent_to": "j***@example.com" }
8390
+ * ```
8391
+ * @throws {ValidationError} If the code or `documentId` is blank.
8392
+ * @throws {ApiError} `400` while the signer's step has not started, `404` for a
8393
+ * document outside the envelope, `409` when the signer has not signed or the
8394
+ * document is not certified, `429` within the resend limits, `500` when the
8395
+ * message could not be sent (nothing used up; ask again).
8396
+ *
8397
+ * @example
8398
+ * ```ts
8399
+ * const { sent_to } = await client.signerDocuments.resendCertifiedCopy(accessCode);
8400
+ * ```
8401
+ */
8402
+ async resendCertifiedCopy(signerAccessCode, documentId) {
8403
+ const code = this.requireId(signerAccessCode, "signer-access-code");
8404
+ const body = documentId === void 0 ? {} : { document_id: this.requireId(documentId, "documentId") };
8405
+ return this.call(
8406
+ "Failed to resend certified copy",
8407
+ () => this.http.post("/sign/certified-copy", body, { params: { "signer-access-code": code } })
8408
+ );
8409
+ }
8410
+ /**
8411
+ * Download the certified copy from a sent link (`GET /signers/downloads/{token}`).
8412
+ *
8413
+ * The token is the last path segment of the link in the completion and
8414
+ * re-send messages; it is a credential. Links last 7 days (completion) or
8415
+ * 30 minutes (re-send). An expired or unknown link redirects to the
8416
+ * expired-link page; the SDK does not follow it and throws instead.
8417
+ *
8418
+ * @param token - Link token.
8419
+ * @param artifact - `pades` for the PAdES version, when the document has one.
8420
+ * @returns The PDF bytes.
8421
+ * @throws {ValidationError} If `token` is blank or `artifact` is not `pades`.
8422
+ * @throws {ApiError} `302` for an expired or unknown link (ask for a new one
8423
+ * with {@link SignerDocumentsResource.resendCertifiedCopyFromLink}), `404`
8424
+ * for `pades` on a document without it.
8425
+ *
8426
+ * @example
8427
+ * ```ts
8428
+ * const pdf = await client.signerDocuments.downloadCertifiedCopy(token);
8429
+ * ```
8430
+ */
8431
+ async downloadCertifiedCopy(token, artifact) {
8432
+ if (artifact !== void 0 && artifact !== "pades") {
8433
+ throw new ValidationError("artifact must be pades when given");
8434
+ }
8435
+ const path2 = `/signers/downloads/${this.pathSegment(token, "Download token")}`;
8436
+ return this.callBinary(
8437
+ "Failed to download certified copy",
8438
+ () => this.http.get(artifact ? `${path2}/pades` : path2, BINARY_NO_REDIRECT)
8439
+ );
8440
+ }
8441
+ /**
8442
+ * Send the certified copy again from an expired link
8443
+ * (`POST /signers/downloads/{token}/resend`).
8444
+ *
8445
+ * Works with the link's token after it expired, on the same terms as
8446
+ * {@link SignerDocumentsResource.resendCertifiedCopy}.
8447
+ *
8448
+ * @param token - Link token, from the expired link.
8449
+ * @returns What was sent, as {@link SignerDocumentsResource.resendCertifiedCopy} returns.
8450
+ * @throws {ValidationError} If `token` is blank.
8451
+ * @throws {ApiError} `404` for an unknown link, `409` when nothing can be sent
8452
+ * from it (copy receiver, Bypass signer, no contact, not certified), `429`
8453
+ * within the resend limits.
8454
+ *
8455
+ * @example
8456
+ * ```ts
8457
+ * await client.signerDocuments.resendCertifiedCopyFromLink(token);
8458
+ * ```
8459
+ */
8460
+ async resendCertifiedCopyFromLink(token) {
8461
+ return this.call(
8462
+ "Failed to resend certified copy",
8463
+ () => this.http.post(`/signers/downloads/${this.pathSegment(token, "Download token")}/resend`)
8464
+ );
8465
+ }
8466
+ /**
8467
+ * Submit the signer's field values to sign an assignment
8468
+ * (`POST /documents/{documentId}/assignments/{assignmentId}?signer-access-code=…`).
8469
+ *
8470
+ * The precise, field-by-field counterpart of
8471
+ * {@link SignerDocumentsResource.signMultiple}: the `entries` array is sent as
8472
+ * the request body, each entry addressing one item resolved from
8473
+ * {@link SignerDocumentsResource.getAssignment}. The access code
8474
+ * authenticates via the `signer-access-code` query param.
8475
+ * Virtual signers must call {@link SignerDocumentsResource.confirmData}
8476
+ * first. Digital Certificate signers cannot use this endpoint; use the
8477
+ * certificate start/complete API flow instead.
8478
+ *
8479
+ * Request body (`application/json`):
8480
+ * ```jsonc
8481
+ * [
8482
+ * {
8483
+ * "itemId": "item_example",
8484
+ * "fieldId": "field_example",
8485
+ * "pageId": "page_example",
8486
+ * "value": "Example Signer"
8487
+ * }
8488
+ * ]
8489
+ * ```
8490
+ *
8491
+ * @param documentId - The document being signed.
8492
+ * @param assignmentId - The assignment within that document.
8493
+ * @param signerAccessCode - The signer's access code, from their signing link.
8494
+ * @param entries - Non-empty array of {@link ISignFieldEntry}
8495
+ * (`itemId`, `fieldId`, `pageId`, `value`) — the body sent to the API.
8496
+ * @returns The API's signing result object. Its keys are operation-specific,
8497
+ * so the SDK preserves them as a {@link Record} without inventing fields.
8498
+ * @throws {ValidationError} If any of `documentId`, `assignmentId`, or
8499
+ * `signerAccessCode` is missing, or `entries` is empty.
8500
+ * @throws {ApiError} `400`/`409` if a value fails validation or the assignment
8501
+ * is no longer signable; `401`/`403` if the access code is invalid/expired.
8502
+ *
8503
+ * @example
8504
+ * ```ts
8505
+ * // body → [{ itemId, fieldId, pageId, value: 'Example Signer' }]
8506
+ * await client.signerDocuments.sign(documentId, assignmentId, accessCode, [
8507
+ * { itemId: 'item-1', fieldId: 'field-1', pageId: 'page-1', value: 'Example Signer' },
8508
+ * ]);
7914
8509
  * ```
7915
8510
  */
7916
8511
  async sign(documentId, assignmentId, signerAccessCode, entries) {
@@ -7998,6 +8593,19 @@ function assertDocumentIds(documentIds) {
7998
8593
  throw new ValidationError("documentIds must be a non-empty array of non-empty IDs");
7999
8594
  }
8000
8595
  }
8596
+ var BINARY_NO_REDIRECT = { responseType: "arraybuffer", maxRedirects: 0 };
8597
+ var SIGNING_EXPANSIONS = /* @__PURE__ */ new Set(["envelope"]);
8598
+ function signingReadParams(options) {
8599
+ assertRecord(options, "signing read options");
8600
+ return expandParam(options.expand, SIGNING_EXPANSIONS);
8601
+ }
8602
+ function searchParams(search, params) {
8603
+ if (search !== void 0 && typeof search !== "string") {
8604
+ throw new ValidationError("search must be a string");
8605
+ }
8606
+ assertRecord(params, "search params");
8607
+ return cleanParams({ search, envelope_id: params.envelope_id });
8608
+ }
8001
8609
  function assertDeclineReason(declineReason) {
8002
8610
  if (typeof declineReason !== "string" || !declineReason.trim()) {
8003
8611
  throw new ValidationError("declineReason is required");
@@ -8219,12 +8827,70 @@ var UserResource = class extends BaseResource {
8219
8827
  * ```
8220
8828
  */
8221
8829
  async updateNotificationPreferences(preferences) {
8222
- validateNotificationPreferences(preferences);
8830
+ assertBooleanMap(preferences, "notification preferences", NOTIFICATION_PREFERENCE_KEYS);
8223
8831
  return this.call(
8224
8832
  "Failed to update notification preferences",
8225
8833
  () => this.http.put("/users/self/notification-preferences", preferences)
8226
8834
  );
8227
8835
  }
8836
+ /**
8837
+ * Read which document alerts reach the user as push notifications
8838
+ * (`GET /users/self/push-preferences`).
8839
+ *
8840
+ * Separate from the e-mail preferences. Every key is returned and defaults
8841
+ * to `true`; new keys may be added. Not available to third-party OAuth
8842
+ * applications (`403`).
8843
+ *
8844
+ * @returns The push preferences:
8845
+ * ```jsonc
8846
+ * {
8847
+ * "SignerViewed": true,
8848
+ * "SignerSigned": true,
8849
+ * "DocumentCompleted": true,
8850
+ * "SignerDeclined": true,
8851
+ * "DocumentAboutToExpire": true,
8852
+ * "DocumentExpired": true,
8853
+ * "SignerIdentityReviewRequired": true, // the review e-mail is always sent
8854
+ * "SignerWhatsappFailed": true
8855
+ * }
8856
+ * ```
8857
+ * @throws {ApiError} `401` for invalid credentials, `403` for an OAuth application token.
8858
+ *
8859
+ * @example
8860
+ * ```ts
8861
+ * const push = await client.users.getPushPreferences();
8862
+ * ```
8863
+ */
8864
+ async getPushPreferences() {
8865
+ return this.call(
8866
+ "Failed to fetch push preferences",
8867
+ () => this.http.get("/users/self/push-preferences")
8868
+ );
8869
+ }
8870
+ /**
8871
+ * Change which document alerts reach the user as push notifications
8872
+ * (`PUT /users/self/push-preferences`).
8873
+ *
8874
+ * Merges the keys sent; `false` stops that push in every workspace the user
8875
+ * belongs to. E-mail is not affected.
8876
+ *
8877
+ * @param preferences - Keys to change, e.g. `{ SignerViewed: false }`.
8878
+ * @returns The full map, as {@link UserResource.getPushPreferences} returns.
8879
+ * @throws {ValidationError} If the map is empty or a value is not a boolean.
8880
+ * @throws {ApiError} `400` for an unknown code, `403` for an OAuth application token.
8881
+ *
8882
+ * @example
8883
+ * ```ts
8884
+ * await client.users.updatePushPreferences({ SignerViewed: false });
8885
+ * ```
8886
+ */
8887
+ async updatePushPreferences(preferences) {
8888
+ assertBooleanMap(preferences, "push preferences");
8889
+ return this.call(
8890
+ "Failed to update push preferences",
8891
+ () => this.http.put("/users/self/push-preferences", { ...preferences })
8892
+ );
8893
+ }
8228
8894
  /**
8229
8895
  * List the user's enrolled two-factor methods (`GET /users/self/mfa`).
8230
8896
  *
@@ -8420,21 +9086,6 @@ var NOTIFICATION_PREFERENCE_KEYS = /* @__PURE__ */ new Set([
8420
9086
  "ContractExpired",
8421
9087
  "ContractRenewed"
8422
9088
  ]);
8423
- function validateNotificationPreferences(preferences) {
8424
- assertRecord(preferences, "notification preferences");
8425
- const entries = Object.entries(preferences);
8426
- if (entries.length === 0) {
8427
- throw new ValidationError("at least one notification preference is required");
8428
- }
8429
- for (const [key, value] of entries) {
8430
- if (!NOTIFICATION_PREFERENCE_KEYS.has(key)) {
8431
- throw new ValidationError(`unknown notification preference: ${key}`);
8432
- }
8433
- if (typeof value !== "boolean") {
8434
- throw new ValidationError(`${key} must be a boolean`);
8435
- }
8436
- }
8437
- }
8438
9089
 
8439
9090
  // src/resources/contracts.ts
8440
9091
  var CONTRACT_STATUSES = /* @__PURE__ */ new Set(["draft", "active", "expired", "terminated"]);
@@ -8564,14 +9215,14 @@ var ContractResource = class extends BaseResource {
8564
9215
  * }
8565
9216
  * ```
8566
9217
  * @throws {ValidationError} If an ID is missing or invalid.
8567
- * @throws {ApiError} `401` for invalid credentials, `404` when the document
8568
- * has no tracked terms, or `500` on a server error.
9218
+ * @throws {ApiError} `401` for invalid credentials, `404` (`code:
9219
+ * 'NoContractTerms'` when the document exists without terms), or `500`.
8569
9220
  *
8570
9221
  * @example
8571
9222
  * ```ts
8572
9223
  * const contract = await client.contracts.get(document.id);
8573
- * if (contract.resource === 'document_contract_amendment') {
8574
- * console.log(contract.parent_document_id);
9224
+ * if ('parent_document_id' in contract) {
9225
+ * console.log(contract.parent_document_id); // an amendment, renewal or termination
8575
9226
  * }
8576
9227
  * ```
8577
9228
  */
@@ -8630,9 +9281,10 @@ var ContractResource = class extends BaseResource {
8630
9281
  * }
8631
9282
  * ```
8632
9283
  * @throws {ValidationError} If the payload or an ID is malformed.
8633
- * @throws {ApiError} `400` for invalid terms, `403` when the plan does not
8634
- * include tracking, `404` for an unknown document, `409` after a concurrent
8635
- * change, or `500` on a server error.
9284
+ * @throws {ApiError} `400` for invalid terms (each in `fieldErrors`), `403`
9285
+ * (`PlanRestricted`) when the plan does not include tracking, `404` for an
9286
+ * unknown document or a `parent_document_id` outside the workspace, `409`
9287
+ * (`ContractChanged`) after a concurrent change, or `500` on a server error.
8636
9288
  *
8637
9289
  * @example
8638
9290
  * ```ts
@@ -8662,6 +9314,7 @@ var ContractResource = class extends BaseResource {
8662
9314
  *
8663
9315
  * @param documentId - Any document in the contract family.
8664
9316
  * @param accountId - Override the client's default account ID.
9317
+ * @param params - `expand: 'document'` embeds the root contract's document.
8665
9318
  * @returns The root contract and ordered instruments:
8666
9319
  * ```jsonc
8667
9320
  * {
@@ -8713,10 +9366,15 @@ var ContractResource = class extends BaseResource {
8713
9366
  * const family = await client.contracts.listRelated(amendmentDocument.id);
8714
9367
  * ```
8715
9368
  */
8716
- async listRelated(documentId, accountId) {
9369
+ async listRelated(documentId, accountId, params = {}) {
9370
+ assertRecord(params, "related contract params");
9371
+ if (params.expand !== void 0 && params.expand !== "document") {
9372
+ throw new ValidationError("expand must be document");
9373
+ }
9374
+ const config = params.expand === void 0 ? {} : { params: { expand: params.expand } };
8717
9375
  return this.call(
8718
9376
  "Failed to fetch related contracts",
8719
- () => this.http.get(`${this.contractPath(documentId, accountId)}/related`)
9377
+ () => this.http.get(`${this.contractPath(documentId, accountId)}/related`, config)
8720
9378
  );
8721
9379
  }
8722
9380
  /**
@@ -9019,15 +9677,708 @@ function validateExternalReferences(value) {
9019
9677
  }
9020
9678
  }
9021
9679
 
9680
+ // src/resources/envelopes.ts
9681
+ var EnvelopeResource = class extends BaseResource {
9682
+ /**
9683
+ * List the workspace's envelopes, most recent first
9684
+ * (`GET /accounts/{accountId}/envelopes`).
9685
+ *
9686
+ * @param params - Optional filters and pagination.
9687
+ * @param params.search - Part of the envelope name.
9688
+ * @param params.status - `open` (a document is still open) or `closed`
9689
+ * (every document signed, declined, cancelled, expired or failed).
9690
+ * @param params.page - One-based page number.
9691
+ * @param params.per-page - Page size: 20 by default, at most 50.
9692
+ * @param accountId - Override the client's default account ID.
9693
+ * @returns Envelopes and pagination metadata:
9694
+ * ```jsonc
9695
+ * {
9696
+ * "data": [{
9697
+ * "id": "1052a1f0c3d4e5f6a7b8c9d0e1f2",
9698
+ * "name": "Admission kit",
9699
+ * "message": "Please sign the documents below.",
9700
+ * "documents": [{
9701
+ * "id": "1052a1e9b8c7d6e5f4a3b2c1d0e9",
9702
+ * "position": 1,
9703
+ * "name": "contract.pdf",
9704
+ * "status": "pending_signature",
9705
+ * "artifacts": {
9706
+ * "original": "https://api.assinafy.com.br/v1/documents/1052a1e9b8c7d6e5f4a3b2c1d0e9/download/original",
9707
+ * "thumbnail": "https://api.assinafy.com.br/v1/documents/1052a1e9b8c7d6e5f4a3b2c1d0e9/thumbnail"
9708
+ * },
9709
+ * "signers": [{
9710
+ * "id": "1052a1d4c3b2a1f0e9d8c7b6a5f4",
9711
+ * "full_name": "Ana Souza",
9712
+ * "email": "ana@example.com",
9713
+ * "whatsapp_phone_number": null,
9714
+ * "completed": false,
9715
+ * "signed_at": null
9716
+ * }]
9717
+ * }],
9718
+ * "counts": { "pending_signature": 1 }, // documents per status; no envelope-level status
9719
+ * "signing_urls": [{
9720
+ * "signer_id": "1052a1d4c3b2a1f0e9d8c7b6a5f4",
9721
+ * "url": "https://app.assinafy.com.br/sign/1052a1e9b8c7d6e5f4a3b2c1d0e9?email=ana%40example.com",
9722
+ * "embedded": false
9723
+ * }],
9724
+ * "created_at": "2026-11-11T14:00:00Z"
9725
+ * }],
9726
+ * "meta": { "current_page": 1, "per_page": 20, "total": 1, "last_page": 1 }
9727
+ * }
9728
+ * ```
9729
+ * @throws {ValidationError} If no account ID is available.
9730
+ * @throws {ApiError} `400` for a filter of the wrong type, `403` for a token
9731
+ * without `documents:read`, `401` for invalid credentials.
9732
+ *
9733
+ * @example
9734
+ * ```ts
9735
+ * const { data: open } = await client.envelopes.list({ status: 'open' });
9736
+ * ```
9737
+ */
9738
+ async list(params = {}, accountId) {
9739
+ assertRecord(params, "envelope list params");
9740
+ if (params.status !== void 0 && params.status !== "open" && params.status !== "closed") {
9741
+ throw new ValidationError("status must be open or closed");
9742
+ }
9743
+ return this.callList(
9744
+ "Failed to list envelopes",
9745
+ () => this.http.get(this.envelopesPath(accountId), { params: cleanListParams(params) })
9746
+ );
9747
+ }
9748
+ /**
9749
+ * Read one envelope (`GET /accounts/{accountId}/envelopes/{envelopeId}`).
9750
+ *
9751
+ * @param envelopeId - Envelope ID.
9752
+ * @param accountId - Override the client's default account ID.
9753
+ * @returns The envelope: its documents in order (`position`), each with its
9754
+ * status and signers, the per-status `counts` and one `signing_urls` entry
9755
+ * per signer. Same shape as each item of {@link EnvelopeResource.list}.
9756
+ * @throws {ValidationError} If an ID is missing or invalid.
9757
+ * @throws {ApiError} `403` for a token without `documents:read`, `404` for an
9758
+ * unknown envelope.
9759
+ *
9760
+ * @example
9761
+ * ```ts
9762
+ * const envelope = await client.envelopes.get(envelopeId);
9763
+ * const pending = envelope.documents.filter((doc) => doc.status === 'pending_signature');
9764
+ * ```
9765
+ */
9766
+ async get(envelopeId, accountId) {
9767
+ return this.call(
9768
+ "Failed to fetch envelope",
9769
+ () => this.http.get(this.envelopePath(envelopeId, accountId))
9770
+ );
9771
+ }
9772
+ /**
9773
+ * Send several documents to the same signers at once
9774
+ * (`POST /accounts/{accountId}/envelopes`).
9775
+ *
9776
+ * Every document must be uploaded, `metadata_ready` and unassigned; every
9777
+ * signer must be on at least one document. Signers all sign at once (no
9778
+ * `step`); a `DigitalCertificate` signer signs only `virtual` documents and
9779
+ * is alone on each. One invitation goes to each signer, and `200` means the
9780
+ * envelope exists even when a send fails (see each signer's
9781
+ * `notification_history`). The envelope is charged as one document, each
9782
+ * signer's notification and identity check once, and each certificate
9783
+ * signature on every document it is made on. A refused request creates and
9784
+ * charges nothing. Pass an `idempotencyKey` to retry safely after a lost
9785
+ * response; the SDK then also replays a `429`.
9786
+ *
9787
+ * @param payload - Envelope definition.
9788
+ * @param payload.name - 1–255 characters without `<`; invitations use it in
9789
+ * place of document names.
9790
+ * @param payload.message - Optional message for every signer.
9791
+ * @param payload.max_total_credits - Refuse with `409 CreditCeilingExceeded`
9792
+ * above this many credits.
9793
+ * @param payload.signers - 1–20 `{ id, verification_method?, notification_methods?, embedded? }`.
9794
+ * @param payload.documents - 1–20 `{ id, signer_ids, method?, entries?, expires_at?, copy_receiver_ids? }`,
9795
+ * in envelope order. `collect` documents need `entries` whose signers are
9796
+ * exactly `signer_ids`.
9797
+ * @param options - `idempotencyKey`: new for each envelope you mean to create.
9798
+ * @param accountId - Override the client's default account ID.
9799
+ * @returns The created envelope (see {@link EnvelopeResource.list}). An
9800
+ * embedded or WhatsApp-only signer has `url: null` in `signing_urls`.
9801
+ * @throws {ValidationError} If the payload is malformed, a signer's channels
9802
+ * do not pair, or a `collect` document has no `entries`.
9803
+ * @throws {ApiError} `400` with `fieldErrors` naming each field at fault, `403`
9804
+ * (`PlanRestricted` or `InsufficientScope`), `409` (`CreditCeilingExceeded`,
9805
+ * or `IdempotencyKeyInUse` while the first request with that key runs).
9806
+ *
9807
+ * @example
9808
+ * ```ts
9809
+ * const envelope = await client.envelopes.create({
9810
+ * name: 'Admission kit',
9811
+ * signers: [{ id: signerId }],
9812
+ * documents: [
9813
+ * { id: contractId, signer_ids: [signerId] },
9814
+ * { id: policyId, signer_ids: [signerId], expires_at: '2026-12-31' },
9815
+ * ],
9816
+ * }, { idempotencyKey: crypto.randomUUID() });
9817
+ * ```
9818
+ */
9819
+ async create(payload, options = {}, accountId) {
9820
+ const body = buildEnvelopePayload(payload);
9821
+ assertRecord(options, "envelope options");
9822
+ const config = idempotencyConfig(options.idempotencyKey);
9823
+ this.logger.info("Creating envelope", {
9824
+ signerCount: body["signers"].length,
9825
+ documentCount: body["documents"].length
9826
+ });
9827
+ return this.call(
9828
+ "Failed to create envelope",
9829
+ () => this.http.post(this.envelopesPath(accountId), body, config)
9830
+ );
9831
+ }
9832
+ /**
9833
+ * Estimate what creating an envelope would cost
9834
+ * (`POST /accounts/{accountId}/envelopes/estimate-cost`).
9835
+ *
9836
+ * Takes the creation body and checks it the same way, creating and charging
9837
+ * nothing; `max_total_credits` is ignored. The envelope counts as one
9838
+ * document, each signer's notification and identity check once, and each
9839
+ * certificate signature per document.
9840
+ *
9841
+ * @param payload - The body {@link EnvelopeResource.create} would send.
9842
+ * @param accountId - Override the client's default account ID.
9843
+ * @returns A cost estimate:
9844
+ * ```jsonc
9845
+ * {
9846
+ * "documents": 1,
9847
+ * "credits": 1.45,
9848
+ * "needs_extra_document": false,
9849
+ * "extra_document_cost": 1,
9850
+ * "total_credits": 1.45,
9851
+ * "breakdown": [
9852
+ * { "code": "NotificationWhatsapp", "name": "WhatsApp notification", "cost": 0.45, "quantity": 1, "unit_cost": 0.45 },
9853
+ * { "code": "SignatureDigitalCertificate", "name": "Digital certificate signature", "cost": 1, "quantity": 2, "unit_cost": 0.5 }
9854
+ * ],
9855
+ * "document_balance": 97, // null when documents are not limited
9856
+ * "credit_balance": 10, // null when credits are not limited
9857
+ * "has_sufficient_resources": true,
9858
+ * "blocking_reason": null,
9859
+ * "message": null
9860
+ * }
9861
+ * ```
9862
+ * @throws {ValidationError} If the payload is malformed or a signer's channels do not pair.
9863
+ * @throws {ApiError} `400` for fields at fault, `403` (`PlanRestricted` or
9864
+ * `InsufficientScope`).
9865
+ *
9866
+ * @example
9867
+ * ```ts
9868
+ * const estimate = await client.envelopes.estimateCost(envelopeBody);
9869
+ * if (!estimate.has_sufficient_resources) console.warn(estimate.blocking_reason);
9870
+ * ```
9871
+ */
9872
+ async estimateCost(payload, accountId) {
9873
+ const body = buildEnvelopePayload(payload);
9874
+ return this.call(
9875
+ "Failed to estimate envelope cost",
9876
+ () => this.http.post(`${this.envelopesPath(accountId)}/estimate-cost`, body)
9877
+ );
9878
+ }
9879
+ /**
9880
+ * Rename an envelope, change its message or reorder its documents
9881
+ * (`PATCH /accounts/{accountId}/envelopes/{envelopeId}`).
9882
+ *
9883
+ * Send only what changes. Nothing is sent to anyone; later reminders,
9884
+ * cancellations and additions use the new values. Works on closed envelopes.
9885
+ *
9886
+ * @param envelopeId - Envelope ID.
9887
+ * @param payload - At least one change.
9888
+ * @param payload.name - 1–255 characters without `<`.
9889
+ * @param payload.message - New message, or `null` for none.
9890
+ * @param payload.document_ids - Every document of the envelope, each once, in the new order.
9891
+ * @param accountId - Override the client's default account ID.
9892
+ * @returns The updated envelope (see {@link EnvelopeResource.list}).
9893
+ * @throws {ValidationError} If nothing would change or a value is malformed.
9894
+ * @throws {ApiError} `400` for fields at fault, `403` for a token without
9895
+ * `documents:write`, `404` for an unknown envelope.
9896
+ *
9897
+ * @example
9898
+ * ```ts
9899
+ * await client.envelopes.update(envelopeId, { name: 'Admission kit 2026', message: null });
9900
+ * ```
9901
+ */
9902
+ async update(envelopeId, payload, accountId) {
9903
+ const body = buildUpdatePayload(payload);
9904
+ return this.call(
9905
+ "Failed to update envelope",
9906
+ () => this.http.patch(this.envelopePath(envelopeId, accountId), body)
9907
+ );
9908
+ }
9909
+ /**
9910
+ * Delete a closed envelope (`DELETE /accounts/{accountId}/envelopes/{envelopeId}`).
9911
+ *
9912
+ * Allowed once every document is certificated, declined, cancelled, expired
9913
+ * or failed; cancel it first otherwise. Its documents remain as ordinary
9914
+ * documents, and its `Idempotency-Key` no longer answers it.
9915
+ *
9916
+ * @param envelopeId - Envelope ID.
9917
+ * @param accountId - Override the client's default account ID.
9918
+ * @throws {ValidationError} If an ID is missing or invalid.
9919
+ * @throws {ApiError} `403` for a token without `documents:write`, `404` for an
9920
+ * unknown envelope, `409` (`EnvelopeOpen`) while a document is still open.
9921
+ *
9922
+ * @example
9923
+ * ```ts
9924
+ * await client.envelopes.cancel(envelopeId);
9925
+ * await client.envelopes.delete(envelopeId);
9926
+ * ```
9927
+ */
9928
+ async delete(envelopeId, accountId) {
9929
+ return this.callVoid(
9930
+ "Failed to delete envelope",
9931
+ () => this.http.delete(this.envelopePath(envelopeId, accountId))
9932
+ );
9933
+ }
9934
+ /**
9935
+ * Cancel every document that can still be cancelled
9936
+ * (`PUT /accounts/{accountId}/envelopes/{envelopeId}/cancel`).
9937
+ *
9938
+ * Each owner, signer and copy receiver is told once for the whole envelope.
9939
+ * Documents already closed, fully signed or being certificated are left as
9940
+ * they are. Safe to repeat: a second call cancels nothing.
9941
+ *
9942
+ * @param envelopeId - Envelope ID.
9943
+ * @param accountId - Override the client's default account ID.
9944
+ * @returns What happened to each document:
9945
+ * ```jsonc
9946
+ * [
9947
+ * { "id": "1052a1e9b8c7d6e5f4a3b2c1d0e9", "status": "cancelled", "cancelled": true },
9948
+ * { "id": "1052a1eaf9e8d7c6b5a4f3e2d1c0", "status": "certificated", "cancelled": false }
9949
+ * ]
9950
+ * ```
9951
+ * @throws {ValidationError} If an ID is missing or invalid.
9952
+ * @throws {ApiError} `403` for a token without `documents:write`, `404` for an
9953
+ * unknown envelope.
9954
+ *
9955
+ * @example
9956
+ * ```ts
9957
+ * const results = await client.envelopes.cancel(envelopeId);
9958
+ * ```
9959
+ */
9960
+ async cancel(envelopeId, accountId) {
9961
+ return this.call(
9962
+ "Failed to cancel envelope",
9963
+ () => this.http.put(`${this.envelopePath(envelopeId, accountId)}/cancel`)
9964
+ );
9965
+ }
9966
+ /**
9967
+ * Read the envelope's activity trail, newest first
9968
+ * (`GET /accounts/{accountId}/envelopes/{envelopeId}/activities`).
9969
+ *
9970
+ * Includes every document the envelope has had, including ones taken out;
9971
+ * each entry is a document activity that also names its document.
9972
+ *
9973
+ * @param envelopeId - Envelope ID.
9974
+ * @param params - `sort` (`-id`, the default, or `id` for oldest first),
9975
+ * `page`, and `per-page` (20 by default, at most 50).
9976
+ * @param accountId - Override the client's default account ID.
9977
+ * @returns Activity entries and pagination metadata:
9978
+ * ```jsonc
9979
+ * {
9980
+ * "data": [{
9981
+ * "id": 7731204,
9982
+ * "event": "signer_signed_document",
9983
+ * "message": "Ana Souza signed the document",
9984
+ * "payload": { "signer": { "id": "1052a1d4c3b2a1f0e9d8c7b6a5f4" } }, // same keys as that event's webhook
9985
+ * "origin": { "ip": "203.0.113.10", "user-agent": "Mozilla/5.0" },
9986
+ * "document_id": "1052a1e9b8c7d6e5f4a3b2c1d0e9",
9987
+ * "document_name": "contract.pdf",
9988
+ * "created_at": "2026-11-11T14:05:00Z"
9989
+ * }],
9990
+ * "meta": { "current_page": 1, "per_page": 20, "total": 1, "last_page": 1 }
9991
+ * }
9992
+ * ```
9993
+ * @throws {ValidationError} If an ID is missing or invalid.
9994
+ * @throws {ApiError} `403` for a token without `documents:read`, `404` for an
9995
+ * unknown envelope.
9996
+ *
9997
+ * @example
9998
+ * ```ts
9999
+ * const { data } = await client.envelopes.listActivities(envelopeId, { sort: 'id' });
10000
+ * ```
10001
+ */
10002
+ async listActivities(envelopeId, params = {}, accountId) {
10003
+ return this.callList(
10004
+ "Failed to fetch envelope activities",
10005
+ () => this.http.get(`${this.envelopePath(envelopeId, accountId)}/activities`, {
10006
+ params: cleanListParams(params)
10007
+ })
10008
+ );
10009
+ }
10010
+ /**
10011
+ * Download one artifact of every document as a zip
10012
+ * (`GET /accounts/{accountId}/envelopes/{envelopeId}/download/{artifactName}`).
10013
+ *
10014
+ * Files are named after their position (`1 - contract.pdf`); `bundle` gives
10015
+ * each document a folder. `certificated`, `certificate-page`, `pades` and
10016
+ * `bundle` include only the documents certified so far.
10017
+ *
10018
+ * @param envelopeId - Envelope ID.
10019
+ * @param artifactName - `original`, `certificated`, `certificate-page`, `pades` or `bundle`.
10020
+ * @param accountId - Override the client's default account ID.
10021
+ * @returns The zip archive bytes.
10022
+ * @throws {ValidationError} If an ID or the artifact name is invalid.
10023
+ * @throws {ApiError} `403` for a token without `documents:read`, `404` when no
10024
+ * document has the artifact.
10025
+ *
10026
+ * @example
10027
+ * ```ts
10028
+ * import { writeFile } from 'node:fs/promises';
10029
+ * await writeFile('envelope.zip', await client.envelopes.download(envelopeId, 'certificated'));
10030
+ * ```
10031
+ */
10032
+ async download(envelopeId, artifactName, accountId) {
10033
+ assertDocumentArtifactName(artifactName);
10034
+ return this.callBinary(
10035
+ "Failed to download envelope artifacts",
10036
+ () => this.http.get(
10037
+ `${this.envelopePath(envelopeId, accountId)}/download/${this.pathSegment(artifactName, "Artifact name")}`,
10038
+ { responseType: "arraybuffer" }
10039
+ )
10040
+ );
10041
+ }
10042
+ /**
10043
+ * Add a document to an open envelope for some of its signers
10044
+ * (`POST /accounts/{accountId}/envelopes/{envelopeId}/documents`).
10045
+ *
10046
+ * The document is checked as on creation and goes last. Only its
10047
+ * certificate signatures are charged; the chosen signers receive the
10048
+ * envelope invitation again, now listing it. No new signer can join, and an
10049
+ * envelope holds at most 20 documents.
10050
+ *
10051
+ * @param envelopeId - Envelope ID.
10052
+ * @param payload - `{ id, signer_ids, method?, entries?, expires_at?, copy_receiver_ids?, max_total_credits? }`.
10053
+ * @param accountId - Override the client's default account ID.
10054
+ * @returns The updated envelope (see {@link EnvelopeResource.list}).
10055
+ * @throws {ValidationError} If the document definition is malformed.
10056
+ * @throws {ApiError} `400` for fields at fault, `403` (`PlanRestricted` or
10057
+ * `InsufficientScope`), `409` (`EnvelopeClosed`, `CreditCeilingExceeded`).
10058
+ *
10059
+ * @example
10060
+ * ```ts
10061
+ * await client.envelopes.addDocument(envelopeId, { id: annexId, signer_ids: [signerId] });
10062
+ * ```
10063
+ */
10064
+ async addDocument(envelopeId, payload, accountId) {
10065
+ const body = buildEnvelopeDocument(payload, "document");
10066
+ assertCreditCeiling(payload.max_total_credits);
10067
+ if (payload.max_total_credits !== void 0) body["max_total_credits"] = payload.max_total_credits;
10068
+ return this.call(
10069
+ "Failed to add document to envelope",
10070
+ () => this.http.post(`${this.envelopePath(envelopeId, accountId)}/documents`, body)
10071
+ );
10072
+ }
10073
+ /**
10074
+ * Take an open document out of the envelope
10075
+ * (`DELETE /accounts/{accountId}/envelopes/{envelopeId}/documents/{documentId}`).
10076
+ *
10077
+ * The document is cancelled and its people are told; the other documents
10078
+ * carry on, and links sent from it keep opening them.
10079
+ *
10080
+ * @param envelopeId - Envelope ID.
10081
+ * @param documentId - Document to take out.
10082
+ * @param accountId - Override the client's default account ID.
10083
+ * @returns The updated envelope (see {@link EnvelopeResource.list}).
10084
+ * @throws {ValidationError} If an ID is missing or invalid.
10085
+ * @throws {ApiError} `403` for a token without `documents:write`, `404` when the
10086
+ * document is not in the envelope, `409` (`DocumentClosed`) when it can no
10087
+ * longer be cancelled.
10088
+ *
10089
+ * @example
10090
+ * ```ts
10091
+ * await client.envelopes.removeDocument(envelopeId, documentId);
10092
+ * ```
10093
+ */
10094
+ async removeDocument(envelopeId, documentId, accountId) {
10095
+ return this.call(
10096
+ "Failed to remove document from envelope",
10097
+ () => this.http.delete(
10098
+ `${this.envelopePath(envelopeId, accountId)}/documents/${this.pathSegment(documentId, "Document ID")}`
10099
+ )
10100
+ );
10101
+ }
10102
+ /**
10103
+ * Remind a signer of the whole envelope
10104
+ * (`PUT /accounts/{accountId}/envelopes/{envelopeId}/signers/{signerId}/resend`).
10105
+ *
10106
+ * One message from their first link, listing the documents still to sign;
10107
+ * paid channels are charged once. A document's own reminder
10108
+ * (`assignments.resendNotification`) still goes per document.
10109
+ *
10110
+ * @param envelopeId - Envelope ID.
10111
+ * @param signerId - Signer of the envelope.
10112
+ * @param accountId - Override the client's default account ID.
10113
+ * @returns Delivery acknowledgement:
10114
+ * ```jsonc
10115
+ * { "is_sent": true, "envelope_id": "1052a1f0c3d4e5f6a7b8c9d0e1f2", "signer_id": "1052a1d4c3b2a1f0e9d8c7b6a5f4" }
10116
+ * ```
10117
+ * @throws {ValidationError} If an ID is missing or invalid.
10118
+ * @throws {ApiError} `400` when the signer has nothing left to sign or credits
10119
+ * are short, `404` when the signer is not on the envelope, `409`
10120
+ * (`EnvelopeClosed`).
10121
+ *
10122
+ * @example
10123
+ * ```ts
10124
+ * await client.envelopes.resendNotification(envelopeId, signerId);
10125
+ * ```
10126
+ */
10127
+ async resendNotification(envelopeId, signerId, accountId) {
10128
+ return this.call(
10129
+ "Failed to remind envelope signer",
10130
+ () => this.http.put(
10131
+ `${this.envelopePath(envelopeId, accountId)}/signers/${this.pathSegment(signerId, "Signer ID")}/resend`
10132
+ )
10133
+ );
10134
+ }
10135
+ envelopesPath(accountId) {
10136
+ return `/accounts/${this.pathSegment(this.accountId(accountId), "Account ID")}/envelopes`;
10137
+ }
10138
+ envelopePath(envelopeId, accountId) {
10139
+ return `${this.envelopesPath(accountId)}/${this.pathSegment(envelopeId, "Envelope ID")}`;
10140
+ }
10141
+ };
10142
+ function buildEnvelopePayload(payload) {
10143
+ assertRecord(payload, "envelope payload");
10144
+ assertNonEmptyString(payload.name, "name");
10145
+ assertMessage(payload.message);
10146
+ assertCreditCeiling(payload.max_total_credits);
10147
+ const signers = records(payload.signers, "signers").map((signer, index) => {
10148
+ const label = `signers[${index}]`;
10149
+ assertNonEmptyString(signer["id"], `${label}.id`);
10150
+ validateAssignmentSignerOptions(signer, label);
10151
+ const projected = { id: signer["id"] };
10152
+ for (const key of ["verification_method", "notification_methods", "embedded", "step"]) {
10153
+ if (signer[key] !== void 0) projected[key] = signer[key];
10154
+ }
10155
+ return projected;
10156
+ });
10157
+ const documents = records(payload.documents, "documents").map((document, index) => buildEnvelopeDocument(document, `documents[${index}]`));
10158
+ const body = { name: payload.name, signers, documents };
10159
+ if (payload.message !== void 0) body["message"] = payload.message;
10160
+ if (payload.max_total_credits !== void 0) body["max_total_credits"] = payload.max_total_credits;
10161
+ return body;
10162
+ }
10163
+ function buildEnvelopeDocument(document, label) {
10164
+ assertRecord(document, label);
10165
+ const input = document;
10166
+ assertNonEmptyString(input.id, `${label}.id`);
10167
+ const method = input.method ?? "virtual";
10168
+ if (method !== "virtual" && method !== "collect") {
10169
+ throw new ValidationError(`${label}.method must be virtual or collect`);
10170
+ }
10171
+ const entries = input.entries === void 0 ? void 0 : normaliseAssignmentEntries(input.entries);
10172
+ if (method === "collect" && !entries?.length) {
10173
+ throw new ValidationError(`${label}.entries is required for collect documents`);
10174
+ }
10175
+ if (input.expires_at !== void 0 && input.expires_at !== null) {
10176
+ assertExpirationDate(input.expires_at, `${label}.expires_at`);
10177
+ }
10178
+ const projected = {
10179
+ id: input.id,
10180
+ method,
10181
+ signer_ids: idList(input.signer_ids, `${label}.signer_ids`)
10182
+ };
10183
+ if (entries !== void 0) projected["entries"] = entries;
10184
+ if (input.expires_at !== void 0) projected["expires_at"] = input.expires_at;
10185
+ if (input.copy_receiver_ids !== void 0) {
10186
+ projected["copy_receiver_ids"] = idList(input.copy_receiver_ids, `${label}.copy_receiver_ids`);
10187
+ }
10188
+ return projected;
10189
+ }
10190
+ function buildUpdatePayload(payload) {
10191
+ assertRecord(payload, "envelope update");
10192
+ const body = {};
10193
+ if (payload.name !== void 0) {
10194
+ assertNonEmptyString(payload.name, "name");
10195
+ body["name"] = payload.name;
10196
+ }
10197
+ if (payload.message !== void 0) {
10198
+ assertMessage(payload.message);
10199
+ body["message"] = payload.message;
10200
+ }
10201
+ if (payload.document_ids !== void 0) {
10202
+ body["document_ids"] = idList(payload.document_ids, "document_ids");
10203
+ }
10204
+ if (Object.keys(body).length === 0) {
10205
+ throw new ValidationError("envelope update must change name, message or document_ids");
10206
+ }
10207
+ return body;
10208
+ }
10209
+ function assertMessage(message) {
10210
+ if (message !== void 0 && message !== null && typeof message !== "string") {
10211
+ throw new ValidationError("message must be a string or null");
10212
+ }
10213
+ }
10214
+ function records(value, label) {
10215
+ if (!Array.isArray(value)) throw new ValidationError(`${label} must be an array`);
10216
+ value.forEach((item, index) => assertRecord(item, `${label}[${index}]`));
10217
+ return value;
10218
+ }
10219
+ function idList(value, label) {
10220
+ if (!Array.isArray(value) || value.some((id) => typeof id !== "string" || !id.trim())) {
10221
+ throw new ValidationError(`${label} must be an array of IDs`);
10222
+ }
10223
+ return [...value];
10224
+ }
10225
+
10226
+ // src/resources/embed.ts
10227
+ var EmbedResource = class extends BaseResource {
10228
+ /**
10229
+ * List the origins allowed to embed signing pages, oldest first
10230
+ * (`GET /accounts/{accountId}/embed-origins`).
10231
+ *
10232
+ * @param accountId - Override the client's default account ID.
10233
+ * @returns Registered origins:
10234
+ * ```jsonc
10235
+ * [{ "id": "1052c7d8e9f0a1b2c3d4e5f6a7b8", "origin": "https://app.example.com", "created_at": "2026-11-04T12:05:00Z" }]
10236
+ * ```
10237
+ * @throws {ValidationError} If no account ID is available.
10238
+ * @throws {ApiError} `403` (`PlanRestricted`, or an OAuth application token).
10239
+ *
10240
+ * @example
10241
+ * ```ts
10242
+ * const origins = await client.embed.listOrigins();
10243
+ * ```
10244
+ */
10245
+ async listOrigins(accountId) {
10246
+ return this.call("Failed to list embed origins", () => this.http.get(this.originsPath(accountId)));
10247
+ }
10248
+ /**
10249
+ * Allow one more origin to embed signing pages
10250
+ * (`POST /accounts/{accountId}/embed-origins`).
10251
+ *
10252
+ * An origin is an exact `https://host[:port]` (`http` only for `localhost`
10253
+ * and `127.0.0.1`) without path, query, fragment, credentials or wildcard;
10254
+ * the API lowercases the host and drops a default port. Up to 10 per account.
10255
+ *
10256
+ * @param origin - Origin of the page that will host the iframe.
10257
+ * @param accountId - Override the client's default account ID.
10258
+ * @returns The stored origin, e.g.
10259
+ * `{ "id": "1052c7d8e9f0a1b2c3d4e5f6a7b8", "origin": "https://app.example.com", "created_at": "2026-11-04T12:05:00Z" }`.
10260
+ * @throws {ValidationError} If `origin` is blank.
10261
+ * @throws {ApiError} `400` when it is invalid, already registered, or the
10262
+ * account has 10; `403` (`PlanRestricted`, or an OAuth application token).
10263
+ *
10264
+ * @example
10265
+ * ```ts
10266
+ * await client.embed.addOrigin('https://app.example.com');
10267
+ * ```
10268
+ */
10269
+ async addOrigin(origin, accountId) {
10270
+ assertNonEmptyString(origin, "origin");
10271
+ return this.call(
10272
+ "Failed to add embed origin",
10273
+ () => this.http.post(this.originsPath(accountId), { origin })
10274
+ );
10275
+ }
10276
+ /**
10277
+ * Replace an allowed origin, keeping its ID
10278
+ * (`PUT /accounts/{accountId}/embed-origins/{originId}`).
10279
+ *
10280
+ * @param originId - Embed origin ID.
10281
+ * @param origin - New origin, with the rules of {@link EmbedResource.addOrigin}.
10282
+ * @param accountId - Override the client's default account ID.
10283
+ * @returns The updated origin.
10284
+ * @throws {ValidationError} If an ID or the origin is blank.
10285
+ * @throws {ApiError} `400` for an invalid or duplicate origin, `403`, `404` for
10286
+ * an unknown origin ID.
10287
+ *
10288
+ * @example
10289
+ * ```ts
10290
+ * await client.embed.updateOrigin(originId, 'https://sign.example.com');
10291
+ * ```
10292
+ */
10293
+ async updateOrigin(originId, origin, accountId) {
10294
+ assertNonEmptyString(origin, "origin");
10295
+ return this.call(
10296
+ "Failed to update embed origin",
10297
+ () => this.http.put(this.originPath(originId, accountId), { origin })
10298
+ );
10299
+ }
10300
+ /**
10301
+ * Stop allowing an origin (`DELETE /accounts/{accountId}/embed-origins/{originId}`).
10302
+ *
10303
+ * Removing the last origin disables embedding: new sessions answer `409`
10304
+ * (`embed_origins_missing`).
10305
+ *
10306
+ * @param originId - Embed origin ID.
10307
+ * @param accountId - Override the client's default account ID.
10308
+ * @throws {ValidationError} If an ID is missing or invalid.
10309
+ * @throws {ApiError} `403`, or `404` for an unknown origin ID.
10310
+ *
10311
+ * @example
10312
+ * ```ts
10313
+ * await client.embed.deleteOrigin(originId);
10314
+ * ```
10315
+ */
10316
+ async deleteOrigin(originId, accountId) {
10317
+ return this.callVoid(
10318
+ "Failed to remove embed origin",
10319
+ () => this.http.delete(this.originPath(originId, accountId))
10320
+ );
10321
+ }
10322
+ /**
10323
+ * Mint a single-use embed URL for an `embedded` signer
10324
+ * (`POST /documents/{documentId}/assignments/{assignmentId}/signers/{signerId}/embed-sessions`).
10325
+ *
10326
+ * Load the URL in an iframe on a registered origin within 5 minutes;
10327
+ * opening it spends the token, so mint a new one each time the frame is
10328
+ * shown, including reloads. Treat it as a credential: hand it only to that
10329
+ * signer's page and never store or log it. Limited to 30 sessions per signer
10330
+ * per hour. For an envelope signer, mint on any of their documents still
10331
+ * waiting for them; the frame lists every document they still have to sign.
10332
+ * Frame events are UI hints: confirm the outcome from webhooks.
10333
+ *
10334
+ * @param documentId - Document ID.
10335
+ * @param assignmentId - Assignment ID.
10336
+ * @param signerId - Signer created with `embedded: true`.
10337
+ * @returns The session:
10338
+ * ```jsonc
10339
+ * {
10340
+ * "url": "https://app.assinafy.com.br/embed/3b1f0c7e9a2d4c58b6e1f4a07d93c2e85a1b0f6d4c7e2a9183b5d6f0e4c8a712",
10341
+ * "expires_at": "2026-11-04T12:05:00Z"
10342
+ * }
10343
+ * ```
10344
+ * @throws {ValidationError} If an ID is missing or invalid.
10345
+ * @throws {ApiError} `400` (`embed_not_enabled_for_signer`), `403`
10346
+ * (`PlanRestricted`), `404` for an unknown document, assignment or signer,
10347
+ * `409` (`already_signed`, `document_not_ready` — retry shortly,
10348
+ * `document_unavailable`, `embed_origins_missing`), `429` past 30 per hour.
10349
+ *
10350
+ * @example
10351
+ * ```ts
10352
+ * const { url } = await client.embed.createSession(document.id, assignment.id, signer.id);
10353
+ * response.json({ url }); // to the signer's browser only
10354
+ * ```
10355
+ */
10356
+ async createSession(documentId, assignmentId, signerId) {
10357
+ return this.call(
10358
+ "Failed to create embed session",
10359
+ () => this.http.post(
10360
+ `/documents/${this.pathSegment(documentId, "Document ID")}/assignments/${this.pathSegment(assignmentId, "Assignment ID")}/signers/${this.pathSegment(signerId, "Signer ID")}/embed-sessions`
10361
+ )
10362
+ );
10363
+ }
10364
+ originsPath(accountId) {
10365
+ return `/accounts/${this.pathSegment(this.accountId(accountId), "Account ID")}/embed-origins`;
10366
+ }
10367
+ originPath(originId, accountId) {
10368
+ return `${this.originsPath(accountId)}/${this.pathSegment(originId, "Embed origin ID")}`;
10369
+ }
10370
+ };
10371
+
9022
10372
  // src/support/webhook-verifier.ts
9023
10373
  import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
9024
10374
  var DEFAULT_TOLERANCE_SECONDS = 300;
9025
10375
  var WebhookVerifier = class {
9026
10376
  webhookSecret;
9027
10377
  /**
9028
- * @param webhookSecret - The endpoint's `whsec_…` secret from
9029
- * `webhooks.getEndpointSecret()`. Omit it to keep verification disabled
9030
- * (every check returns `false`).
10378
+ * @param webhookSecret - The endpoint's `whsec_…` secret, as returned by
10379
+ * `webhooks.createEndpoint()` / `updateEndpoint()` when signing turns on,
10380
+ * `rotateEndpointSecret()`, or (API key only) `getEndpointSecret()`. Omit it
10381
+ * to keep verification disabled (every check returns `false`).
9031
10382
  *
9032
10383
  * @example
9033
10384
  * ```ts
@@ -9080,6 +10431,7 @@ var WebhookVerifier = class {
9080
10431
  const [version, signature] = entry.split(",", 2);
9081
10432
  if (version !== "v1" || !signature) return false;
9082
10433
  const actual = Buffer.from(signature, "base64");
10434
+ if (actual.toString("base64") !== signature) return false;
9083
10435
  return actual.length === expected.length && timingSafeEqual2(actual, expected);
9084
10436
  });
9085
10437
  }
@@ -9207,6 +10559,8 @@ var AssinafyClient = class _AssinafyClient {
9207
10559
  signerDocuments;
9208
10560
  users;
9209
10561
  contracts;
10562
+ envelopes;
10563
+ embed;
9210
10564
  webhookVerifier;
9211
10565
  /**
9212
10566
  * Create a client. Supply `apiKey` (preferred, sent as `X-Api-Key`) or a
@@ -9316,7 +10670,12 @@ var AssinafyClient = class _AssinafyClient {
9316
10670
  this.logger,
9317
10671
  this.publicAxiosInstance
9318
10672
  );
9319
- this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
10673
+ this.fields = new FieldsResource(
10674
+ this.axiosInstance,
10675
+ this.defaultAccountId,
10676
+ this.logger,
10677
+ this.publicAxiosInstance
10678
+ );
9320
10679
  this.signerDocuments = new SignerDocumentsResource(
9321
10680
  this.axiosInstance,
9322
10681
  this.defaultAccountId,
@@ -9329,6 +10688,8 @@ var AssinafyClient = class _AssinafyClient {
9329
10688
  this.defaultAccountId,
9330
10689
  this.logger
9331
10690
  );
10691
+ this.envelopes = new EnvelopeResource(this.axiosInstance, this.defaultAccountId, this.logger);
10692
+ this.embed = new EmbedResource(this.axiosInstance, this.defaultAccountId, this.logger);
9332
10693
  this.webhookVerifier = new WebhookVerifier(this.webhookSecret);
9333
10694
  }
9334
10695
  /**
@@ -9501,7 +10862,7 @@ var AssinafyClient = class _AssinafyClient {
9501
10862
  * });
9502
10863
  * console.log(document.status); // usually 'pending_signature'
9503
10864
  * console.log(signer_ids.length); // 2
9504
- * console.log(assignment.signing_urls?.length); // one protected link per signer
10865
+ * console.log(assignment.signing_urls?.length); // one entry per notified signer; url is null for embedded or WhatsApp-only signers
9505
10866
  * ```
9506
10867
  */
9507
10868
  async uploadAndRequestSignatures(options) {
@@ -9759,6 +11120,8 @@ export {
9759
11120
  DEFAULT_WEBHOOK_EVENTS,
9760
11121
  DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD,
9761
11122
  DocumentResource,
11123
+ EmbedResource,
11124
+ EnvelopeResource,
9762
11125
  FieldsResource,
9763
11126
  MAX_LIST_PAGE_SIZE,
9764
11127
  MAX_UPLOAD_BYTES,