@assinafy/sdk 2.8.1 → 2.9.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.js CHANGED
@@ -35,6 +35,7 @@ __export(index_exports, {
35
35
  AssinafyClient: () => AssinafyClient,
36
36
  AssinafyError: () => AssinafyError,
37
37
  AuthenticationResource: () => AuthenticationResource,
38
+ ContractResource: () => ContractResource,
38
39
  DEFAULT_WEBHOOK_EVENTS: () => DEFAULT_WEBHOOK_EVENTS,
39
40
  DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD: () => DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD,
40
41
  DocumentResource: () => DocumentResource,
@@ -689,8 +690,8 @@ var import_axios2 = __toESM(require("axios"));
689
690
  // package.json
690
691
  var package_default = {
691
692
  name: "@assinafy/sdk",
692
- version: "2.8.1",
693
- packageManager: "bun@1.4.0",
693
+ version: "2.9.0",
694
+ packageManager: "bun@1.4.4",
694
695
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
695
696
  type: "commonjs",
696
697
  main: "dist/index.js",
@@ -733,6 +734,8 @@ var package_default = {
733
734
  "digital-signature",
734
735
  "electronic-signature",
735
736
  "signature",
737
+ "contract-lifecycle-management",
738
+ "gestao-de-contratos",
736
739
  "pdf",
737
740
  "webhook",
738
741
  "sdk",
@@ -756,20 +759,21 @@ var package_default = {
756
759
  devDependencies: {
757
760
  "@arethetypeswrong/cli": "^0.18.5",
758
761
  "@eslint/js": "^10.0.1",
759
- "@types/bun": "^1.4.0",
760
- "@types/node": "^22.20.1",
762
+ "@types/bun": "^1.4.4",
763
+ "@types/node": "^22.20.5",
761
764
  "@typescript/native": "npm:typescript@^7.0.2",
762
- eslint: "^10.9.1",
763
- publint: "^0.3.24",
765
+ eslint: "^10.13.0",
766
+ publint: "^0.3.25",
764
767
  tsup: "^8.5.1",
765
768
  typescript: "^6.0.3",
766
- "typescript-eslint": "^8.68.0"
769
+ "typescript-eslint": "^8.72.1"
767
770
  },
768
771
  dependencies: {
769
- axios: "^1.20.0"
772
+ axios: "^1.21.0"
770
773
  },
771
774
  overrides: {
772
775
  esbuild: "0.28.2",
776
+ "follow-redirects": "1.16.2",
773
777
  "brace-expansion": "5.0.12"
774
778
  },
775
779
  files: [
@@ -8054,7 +8058,7 @@ var UserResource = class extends BaseResource {
8054
8058
  *
8055
8059
  * Request body: none. Authentication: `X-Api-Key` or Bearer token.
8056
8060
  *
8057
- * @returns The complete nine-key preference map:
8061
+ * @returns The complete thirteen-key preference map:
8058
8062
  * ```json
8059
8063
  * {
8060
8064
  * "DocumentCompleted": true,
@@ -8065,7 +8069,11 @@ var UserResource = class extends BaseResource {
8065
8069
  * "DocumentExpirationReset": true,
8066
8070
  * "DocumentProcessingFailed": true,
8067
8071
  * "TemplateProcessingFailed": true,
8068
- * "SignerWhatsappFailed": true
8072
+ * "SignerWhatsappFailed": true,
8073
+ * "ContractRenewalNotice": true,
8074
+ * "ContractExpiring": true,
8075
+ * "ContractExpired": true,
8076
+ * "ContractRenewed": true
8069
8077
  * }
8070
8078
  * ```
8071
8079
  * @throws {ApiError} `401` when credentials are missing/invalid, or `500`
@@ -8098,16 +8106,33 @@ var UserResource = class extends BaseResource {
8098
8106
  * "DocumentExpirationReset": true,
8099
8107
  * "DocumentProcessingFailed": true,
8100
8108
  * "TemplateProcessingFailed": true,
8101
- * "SignerWhatsappFailed": true
8109
+ * "SignerWhatsappFailed": true,
8110
+ * "ContractRenewalNotice": true,
8111
+ * "ContractExpiring": true,
8112
+ * "ContractExpired": true,
8113
+ * "ContractRenewed": true
8102
8114
  * }
8103
8115
  * ```
8104
8116
  *
8105
- * @param preferences - One or more of the nine documented keys, each with
8117
+ * @param preferences - One or more of the thirteen documented keys, each with
8106
8118
  * a boolean value. Request example:
8107
8119
  * ```json
8108
8120
  * { "DocumentCompleted": true, "SignerDeclined": false }
8109
8121
  * ```
8110
- * @returns The complete updated nine-key preference map:
8122
+ * @param preferences.DocumentCompleted - Notify when a document completes.
8123
+ * @param preferences.SignerDeclined - Notify when a signer declines.
8124
+ * @param preferences.DocumentCancelled - Notify when a document is cancelled.
8125
+ * @param preferences.DocumentAboutToExpire - Notify before signature expiry.
8126
+ * @param preferences.DocumentExpired - Notify after signature expiry.
8127
+ * @param preferences.DocumentExpirationReset - Notify after resetting expiry.
8128
+ * @param preferences.DocumentProcessingFailed - Notify after document processing fails.
8129
+ * @param preferences.TemplateProcessingFailed - Notify after template processing fails.
8130
+ * @param preferences.SignerWhatsappFailed - Notify after WhatsApp delivery fails.
8131
+ * @param preferences.ContractRenewalNotice - Notify when the contract notice period starts.
8132
+ * @param preferences.ContractExpiring - Notify before a tracked contract ends.
8133
+ * @param preferences.ContractExpired - Notify when a tracked contract expires.
8134
+ * @param preferences.ContractRenewed - Notify when a tracked contract renews.
8135
+ * @returns The complete updated thirteen-key preference map:
8111
8136
  * ```json
8112
8137
  * {
8113
8138
  * "DocumentCompleted": true,
@@ -8118,7 +8143,11 @@ var UserResource = class extends BaseResource {
8118
8143
  * "DocumentExpirationReset": true,
8119
8144
  * "DocumentProcessingFailed": true,
8120
8145
  * "TemplateProcessingFailed": true,
8121
- * "SignerWhatsappFailed": true
8146
+ * "SignerWhatsappFailed": true,
8147
+ * "ContractRenewalNotice": true,
8148
+ * "ContractExpiring": true,
8149
+ * "ContractExpired": true,
8150
+ * "ContractRenewed": true
8122
8151
  * }
8123
8152
  * ```
8124
8153
  * @throws {ValidationError} Before requesting when the map is empty, has an
@@ -8330,7 +8359,11 @@ var NOTIFICATION_PREFERENCE_KEYS = /* @__PURE__ */ new Set([
8330
8359
  "DocumentExpirationReset",
8331
8360
  "DocumentProcessingFailed",
8332
8361
  "TemplateProcessingFailed",
8333
- "SignerWhatsappFailed"
8362
+ "SignerWhatsappFailed",
8363
+ "ContractRenewalNotice",
8364
+ "ContractExpiring",
8365
+ "ContractExpired",
8366
+ "ContractRenewed"
8334
8367
  ]);
8335
8368
  function validateNotificationPreferences(preferences) {
8336
8369
  assertRecord(preferences, "notification preferences");
@@ -8348,6 +8381,589 @@ function validateNotificationPreferences(preferences) {
8348
8381
  }
8349
8382
  }
8350
8383
 
8384
+ // src/resources/contracts.ts
8385
+ var CONTRACT_STATUSES = /* @__PURE__ */ new Set(["draft", "active", "expired", "terminated"]);
8386
+ var RELATION_TYPES = /* @__PURE__ */ new Set(["amendment", "renewal", "termination"]);
8387
+ var CONTRACT_INPUT_KEYS = [
8388
+ "status",
8389
+ "counterparty_name",
8390
+ "counterparty_taxpayer_id",
8391
+ "value",
8392
+ "currency",
8393
+ "start_date",
8394
+ "end_date",
8395
+ "auto_renew",
8396
+ "renewal_term_months",
8397
+ "notice_period_days",
8398
+ "owner_id",
8399
+ "metadata",
8400
+ "external_references",
8401
+ "parent_document_id",
8402
+ "relation_type",
8403
+ "updated_at"
8404
+ ];
8405
+ var ContractResource = class extends BaseResource {
8406
+ /**
8407
+ * List the workspace's tracked contracts (`GET /accounts/{accountId}/contracts`).
8408
+ *
8409
+ * Results are ordered by `-updated_at` unless `sort` is supplied. Use
8410
+ * `updated_at` to catch up after a missed webhook; `ending_within_days` is
8411
+ * evaluated by the API in the Brasília calendar day. OAuth tokens need
8412
+ * `documents:read`.
8413
+ *
8414
+ * @param params - Optional filters, expansion, sorting, and pagination.
8415
+ * @param params.status - Contract states to match; sent comma-separated.
8416
+ * @param params.counterparty - Part of the name, or an exact CPF/CNPJ.
8417
+ * @param params.search - Part of the document name.
8418
+ * @param params.end_date_from - Earliest end date (`YYYY-MM-DD`).
8419
+ * @param params.end_date_to - Latest end date (`YYYY-MM-DD`).
8420
+ * @param params.ending_within_days - Inclusive 0–3650 day window from today.
8421
+ * @param params.external_system - External-reference system.
8422
+ * @param params.external_id - External-reference ID.
8423
+ * @param params.sort - `end_date` / `updated_at`, optionally prefixed by `-`.
8424
+ * @param params.expand - Pass `document` to embed each document.
8425
+ * @param params.page - One-based page number.
8426
+ * @param params.per_page - Alias normalized to the API's `per-page` spelling.
8427
+ * @param params.per-page - Page size; the deployed API returns at most 50.
8428
+ * @param accountId - Override the client's default account ID.
8429
+ * @returns Contract rows and pagination metadata:
8430
+ * ```jsonc
8431
+ * {
8432
+ * "data": [{
8433
+ * "document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8434
+ * "status": "active",
8435
+ * "counterparty_name": "Example Ltda",
8436
+ * "counterparty_taxpayer_id": "11222333000181",
8437
+ * "value": 120000.5,
8438
+ * "currency": "BRL",
8439
+ * "start_date": "2026-11-01",
8440
+ * "end_date": "2027-10-31",
8441
+ * "auto_renew": true,
8442
+ * "renewal_term_months": 12,
8443
+ * "notice_period_days": 30,
8444
+ * "term": 1,
8445
+ * "owner_id": "d6zqpbyog2v3xvxerwn8la94",
8446
+ * "metadata": { "crm_stage": "won" },
8447
+ * "external_references": [{ "system": "crm", "id": "98765" }],
8448
+ * "created_at": "2026-10-23T12:00:00Z",
8449
+ * "updated_at": "2026-10-23T12:00:00Z"
8450
+ * }],
8451
+ * "meta": { "current_page": 1, "per_page": 20, "total": 1, "last_page": 1 }
8452
+ * }
8453
+ * ```
8454
+ * @throws {ValidationError} If a filter is malformed or no account ID is available.
8455
+ * @throws {ApiError} `400` for invalid filters, `401` for invalid credentials,
8456
+ * or `500` when the API cannot list contracts.
8457
+ *
8458
+ * @example
8459
+ * ```ts
8460
+ * const contracts = await client.contracts.list({
8461
+ * status: ['active'],
8462
+ * ending_within_days: 30,
8463
+ * expand: 'document',
8464
+ * });
8465
+ * ```
8466
+ */
8467
+ async list(params = {}, accountId) {
8468
+ const query = buildListParams(params);
8469
+ const id = this.accountId(accountId);
8470
+ return this.callList(
8471
+ "Failed to list contracts",
8472
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}/contracts`, {
8473
+ params: query
8474
+ })
8475
+ );
8476
+ }
8477
+ /**
8478
+ * Read a document's contract terms or amendment link
8479
+ * (`GET /accounts/{accountId}/documents/{documentId}/contract`).
8480
+ *
8481
+ * A root contract includes its `amendments`; a document that is itself an
8482
+ * instrument returns the `document_contract_amendment` shape. Reads remain
8483
+ * available if the workspace's plan no longer includes contract tracking.
8484
+ *
8485
+ * @param documentId - Contract or amendment document ID.
8486
+ * @param accountId - Override the client's default account ID.
8487
+ * @returns The root contract or amendment. Root-contract response:
8488
+ * ```jsonc
8489
+ * {
8490
+ * "resource": "document_contract",
8491
+ * "document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8492
+ * "status": "active",
8493
+ * "counterparty_name": "Example Ltda",
8494
+ * "counterparty_taxpayer_id": "11222333000181",
8495
+ * "value": 130000,
8496
+ * "currency": "BRL",
8497
+ * "start_date": "2026-11-01",
8498
+ * "end_date": "2028-06-30",
8499
+ * "auto_renew": true,
8500
+ * "renewal_term_months": 12,
8501
+ * "notice_period_days": 30,
8502
+ * "term": 2,
8503
+ * "owner_id": null,
8504
+ * "metadata": null,
8505
+ * "external_references": [],
8506
+ * "amendments": [],
8507
+ * "created_at": "2026-10-23T12:00:00Z",
8508
+ * "updated_at": "2027-05-12T18:20:00Z"
8509
+ * }
8510
+ * ```
8511
+ * @throws {ValidationError} If an ID is missing or invalid.
8512
+ * @throws {ApiError} `401` for invalid credentials, `404` when the document
8513
+ * has no tracked terms, or `500` on a server error.
8514
+ *
8515
+ * @example
8516
+ * ```ts
8517
+ * const contract = await client.contracts.get(document.id);
8518
+ * if (contract.resource === 'document_contract_amendment') {
8519
+ * console.log(contract.parent_document_id);
8520
+ * }
8521
+ * ```
8522
+ */
8523
+ async get(documentId, accountId) {
8524
+ return this.call(
8525
+ "Failed to fetch contract terms",
8526
+ () => this.http.get(this.contractPath(documentId, accountId))
8527
+ );
8528
+ }
8529
+ /**
8530
+ * Create or partially update contract terms
8531
+ * (`PUT /accounts/{accountId}/documents/{documentId}/contract`).
8532
+ *
8533
+ * Only supplied fields are sent. `external_references` replaces the list;
8534
+ * `parent_document_id` links this document as an instrument. Pass the
8535
+ * `updated_at` previously read to reject concurrent changes with `409`.
8536
+ * OAuth tokens need `documents:write`; writes require a contract-tracking plan.
8537
+ *
8538
+ * @param documentId - Document whose terms or amendment link will change.
8539
+ * @param payload - At least one contract attribute.
8540
+ * @param payload.status - `draft`, `active`, `expired`, or `terminated`.
8541
+ * @param payload.counterparty_name - Counterparty name; null clears it.
8542
+ * @param payload.counterparty_taxpayer_id - CPF/CNPJ; null clears it.
8543
+ * @param payload.value - Non-negative contract value; null clears it.
8544
+ * @param payload.currency - Three-letter currency; null resets as documented.
8545
+ * @param payload.start_date - Start date (`YYYY-MM-DD`), or null.
8546
+ * @param payload.end_date - End date (`YYYY-MM-DD`), or null.
8547
+ * @param payload.auto_renew - Whether the hourly lifecycle starts a new term.
8548
+ * @param payload.renewal_term_months - 1–600 months, or null for the default.
8549
+ * @param payload.notice_period_days - 0–3650 days, or null to disable notice.
8550
+ * @param payload.owner_id - Active workspace member ID, or null.
8551
+ * @param payload.metadata - Up to 50 string fields, or null.
8552
+ * @param payload.external_references - Up to 20 `{ system, id }` entries; null/[] clears.
8553
+ * @param payload.parent_document_id - Parent contract document, or null to unlink pending.
8554
+ * @param payload.relation_type - `amendment`, `renewal`, or `termination`.
8555
+ * @param payload.updated_at - Optimistic-concurrency timestamp, or null for last-write-wins.
8556
+ * @param accountId - Override the client's default account ID.
8557
+ * @returns The saved contract or amendment link. Amendment response:
8558
+ * ```jsonc
8559
+ * {
8560
+ * "resource": "document_contract_amendment",
8561
+ * "document_id": "7c3d1e2f4a5b6c7d8e9f0a1b",
8562
+ * "document_name": "Amendment 1.pdf",
8563
+ * "parent_document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8564
+ * "relation_type": "amendment",
8565
+ * "number": null,
8566
+ * "status": "pending",
8567
+ * "document_status": "pending_signature",
8568
+ * "apply_error": null,
8569
+ * "currency": "BRL",
8570
+ * "terms": { "value": 130000, "end_date": "2028-06-30" },
8571
+ * "changes": { "value": { "from": 120000.5, "to": 130000 } },
8572
+ * "applied_at": null,
8573
+ * "created_at": "2027-05-10T15:00:00Z",
8574
+ * "updated_at": "2027-05-10T15:00:00Z"
8575
+ * }
8576
+ * ```
8577
+ * @throws {ValidationError} If the payload or an ID is malformed.
8578
+ * @throws {ApiError} `400` for invalid terms, `403` when the plan does not
8579
+ * include tracking, `404` for an unknown document, `409` after a concurrent
8580
+ * change, or `500` on a server error.
8581
+ *
8582
+ * @example
8583
+ * ```ts
8584
+ * const contract = await client.contracts.set(document.id, {
8585
+ * status: 'active',
8586
+ * counterparty_name: 'Example Ltda',
8587
+ * value: 120000.50,
8588
+ * currency: 'BRL',
8589
+ * start_date: '2026-11-01',
8590
+ * end_date: '2027-10-31',
8591
+ * });
8592
+ * ```
8593
+ */
8594
+ async set(documentId, payload, accountId) {
8595
+ const body = buildContractInput(payload);
8596
+ return this.call(
8597
+ "Failed to set contract terms",
8598
+ () => this.http.put(this.contractPath(documentId, accountId), body)
8599
+ );
8600
+ }
8601
+ /**
8602
+ * Read a document's complete contract family
8603
+ * (`GET /accounts/{accountId}/documents/{documentId}/contract/related`).
8604
+ *
8605
+ * The document may be the root or any linked instrument; the response is
8606
+ * always the root contract with every amendment, renewal, and termination.
8607
+ *
8608
+ * @param documentId - Any document in the contract family.
8609
+ * @param accountId - Override the client's default account ID.
8610
+ * @returns The root contract and ordered instruments:
8611
+ * ```jsonc
8612
+ * {
8613
+ * "resource": "document_contract",
8614
+ * "document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8615
+ * "status": "active",
8616
+ * "counterparty_name": "Example Ltda",
8617
+ * "counterparty_taxpayer_id": "11222333000181",
8618
+ * "value": 130000,
8619
+ * "currency": "BRL",
8620
+ * "start_date": "2026-11-01",
8621
+ * "end_date": "2028-06-30",
8622
+ * "auto_renew": true,
8623
+ * "renewal_term_months": 12,
8624
+ * "notice_period_days": 30,
8625
+ * "term": 2,
8626
+ * "owner_id": null,
8627
+ * "metadata": null,
8628
+ * "external_references": [],
8629
+ * "amendments": [{
8630
+ * "document_id": "7c3d1e2f4a5b6c7d8e9f0a1b",
8631
+ * "document_name": "Amendment 1.pdf",
8632
+ * "parent_document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8633
+ * "relation_type": "amendment",
8634
+ * "status": "applied",
8635
+ * "number": 1,
8636
+ * "document_status": "certificated",
8637
+ * "apply_error": null,
8638
+ * "currency": "BRL",
8639
+ * "terms": { "value": 130000, "end_date": "2028-06-30" },
8640
+ * "changes": {
8641
+ * "value": { "from": 120000.5, "to": 130000 },
8642
+ * "end_date": { "from": "2027-10-31", "to": "2028-06-30" }
8643
+ * },
8644
+ * "applied_at": "2027-05-12T18:20:00Z",
8645
+ * "created_at": "2027-05-10T15:00:00Z",
8646
+ * "updated_at": "2027-05-12T18:20:00Z"
8647
+ * }],
8648
+ * "created_at": "2026-10-23T12:00:00Z",
8649
+ * "updated_at": "2027-05-12T18:20:00Z"
8650
+ * }
8651
+ * ```
8652
+ * @throws {ValidationError} If an ID is missing or invalid.
8653
+ * @throws {ApiError} `401` for invalid credentials, `404` when no contract
8654
+ * family exists, or `500` on a server error.
8655
+ *
8656
+ * @example
8657
+ * ```ts
8658
+ * const family = await client.contracts.listRelated(amendmentDocument.id);
8659
+ * ```
8660
+ */
8661
+ async listRelated(documentId, accountId) {
8662
+ return this.call(
8663
+ "Failed to fetch related contracts",
8664
+ () => this.http.get(`${this.contractPath(documentId, accountId)}/related`)
8665
+ );
8666
+ }
8667
+ /**
8668
+ * Start a contract's next term
8669
+ * (`POST /accounts/{accountId}/documents/{documentId}/contract/renew`).
8670
+ *
8671
+ * Supply the current `term` to make a by-term renewal safe to repeat, or an
8672
+ * explicit later `end_date`. `updated_at` rejects concurrent changes. A
8673
+ * renewal reopens an expired contract but cannot reopen a terminated one.
8674
+ *
8675
+ * @param documentId - Root contract document ID.
8676
+ * @param payload - Renewal precondition and optional new date/value.
8677
+ * @param payload.end_date - Explicit new end date, or null to renew by term.
8678
+ * @param payload.value - New value; omitted keeps it and null clears it.
8679
+ * @param payload.term - Current term, required by the API when no date is sent.
8680
+ * @param payload.updated_at - Optional optimistic-concurrency timestamp.
8681
+ * @param accountId - Override the client's default account ID.
8682
+ * @returns The renewed contract:
8683
+ * ```jsonc
8684
+ * {
8685
+ * "resource": "document_contract",
8686
+ * "document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8687
+ * "status": "active",
8688
+ * "counterparty_name": "Example Ltda",
8689
+ * "counterparty_taxpayer_id": "11222333000181",
8690
+ * "value": 130000,
8691
+ * "currency": "BRL",
8692
+ * "start_date": "2026-11-01",
8693
+ * "end_date": "2029-06-30",
8694
+ * "auto_renew": true,
8695
+ * "renewal_term_months": 12,
8696
+ * "notice_period_days": 30,
8697
+ * "term": 2,
8698
+ * "owner_id": null,
8699
+ * "metadata": null,
8700
+ * "external_references": [],
8701
+ * "created_at": "2026-10-23T12:00:00Z",
8702
+ * "updated_at": "2027-10-15T09:30:00Z"
8703
+ * }
8704
+ * ```
8705
+ * @throws {ValidationError} If the payload or an ID is malformed.
8706
+ * @throws {ApiError} `400` for an invalid renewal, `403` when tracking is
8707
+ * unavailable, `404` when terms do not exist, `409` after a concurrent
8708
+ * change, or `500` on a server error.
8709
+ *
8710
+ * @example
8711
+ * ```ts
8712
+ * const renewed = await client.contracts.renew(document.id, {
8713
+ * term: contract.term,
8714
+ * value: 130000,
8715
+ * updated_at: contract.updated_at,
8716
+ * });
8717
+ * ```
8718
+ */
8719
+ async renew(documentId, payload, accountId) {
8720
+ const body = buildRenewPayload(payload);
8721
+ return this.call(
8722
+ "Failed to renew contract",
8723
+ () => this.http.post(`${this.contractPath(documentId, accountId)}/renew`, body)
8724
+ );
8725
+ }
8726
+ /**
8727
+ * Close a contract (`POST /accounts/{accountId}/documents/{documentId}/contract/terminate`).
8728
+ *
8729
+ * Termination stops lifecycle alerts and records the optional reason in the
8730
+ * document activity. Pass `updated_at` to reject concurrent changes.
8731
+ *
8732
+ * @param documentId - Root contract document ID.
8733
+ * @param payload - Optional reason and concurrency precondition.
8734
+ * @param payload.reason - Activity reason (up to 500 characters), or null.
8735
+ * @param payload.updated_at - Optional optimistic-concurrency timestamp.
8736
+ * @param accountId - Override the client's default account ID.
8737
+ * @returns The terminated contract:
8738
+ * ```jsonc
8739
+ * {
8740
+ * "resource": "document_contract",
8741
+ * "document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8742
+ * "status": "terminated",
8743
+ * "counterparty_name": "Example Ltda",
8744
+ * "counterparty_taxpayer_id": "11222333000181",
8745
+ * "value": 120000.5,
8746
+ * "currency": "BRL",
8747
+ * "start_date": "2026-11-01",
8748
+ * "end_date": "2027-10-31",
8749
+ * "auto_renew": false,
8750
+ * "renewal_term_months": 12,
8751
+ * "notice_period_days": 30,
8752
+ * "term": 1,
8753
+ * "owner_id": null,
8754
+ * "metadata": null,
8755
+ * "external_references": [],
8756
+ * "created_at": "2026-10-23T12:00:00Z",
8757
+ * "updated_at": "2027-03-02T14:00:00Z"
8758
+ * }
8759
+ * ```
8760
+ * @throws {ValidationError} If the payload or an ID is malformed.
8761
+ * @throws {ApiError} `400` for invalid state/input, `403` when tracking is
8762
+ * unavailable, `404` when terms do not exist, `409` after a concurrent
8763
+ * change, or `500` on a server error.
8764
+ *
8765
+ * @example
8766
+ * ```ts
8767
+ * await client.contracts.terminate(document.id, {
8768
+ * reason: 'Replaced by a new agreement',
8769
+ * updated_at: contract.updated_at,
8770
+ * });
8771
+ * ```
8772
+ */
8773
+ async terminate(documentId, payload = {}, accountId) {
8774
+ const body = buildTerminatePayload(payload);
8775
+ return this.call(
8776
+ "Failed to terminate contract",
8777
+ () => this.http.post(`${this.contractPath(documentId, accountId)}/terminate`, body)
8778
+ );
8779
+ }
8780
+ contractPath(documentId, accountId) {
8781
+ const id = this.accountId(accountId);
8782
+ return `/accounts/${this.pathSegment(id, "Account ID")}/documents/${this.pathSegment(documentId, "Document ID")}/contract`;
8783
+ }
8784
+ };
8785
+ function buildListParams(params) {
8786
+ assertRecord(params, "contract list params");
8787
+ const query = {};
8788
+ if (params.status !== void 0) {
8789
+ if (!Array.isArray(params.status) || params.status.length === 0 || params.status.some((status) => !CONTRACT_STATUSES.has(status))) {
8790
+ throw new ValidationError("status must be a non-empty array of contract statuses");
8791
+ }
8792
+ query["status"] = params.status.join(",");
8793
+ }
8794
+ for (const key of ["counterparty", "search", "external_system", "external_id"]) {
8795
+ if (params[key] !== void 0) assertOptionalString(params[key], key);
8796
+ if (params[key] !== void 0) query[key] = params[key];
8797
+ }
8798
+ for (const key of ["end_date_from", "end_date_to"]) {
8799
+ if (params[key] !== void 0) assertDate(params[key], key);
8800
+ if (params[key] !== void 0) query[key] = params[key];
8801
+ }
8802
+ if (params.ending_within_days !== void 0 && (!Number.isSafeInteger(params.ending_within_days) || params.ending_within_days < 0 || params.ending_within_days > 3650)) {
8803
+ throw new ValidationError("ending_within_days must be an integer from 0 to 3650");
8804
+ }
8805
+ if (params.ending_within_days !== void 0) {
8806
+ query["ending_within_days"] = params.ending_within_days;
8807
+ }
8808
+ if (params.sort !== void 0 && !["end_date", "-end_date", "updated_at", "-updated_at"].includes(params.sort)) {
8809
+ throw new ValidationError("sort must be end_date or updated_at, optionally prefixed by -");
8810
+ }
8811
+ if (params.sort !== void 0) query["sort"] = params.sort;
8812
+ if (params.expand !== void 0 && params.expand !== "document") {
8813
+ throw new ValidationError("expand must be document");
8814
+ }
8815
+ if (params.expand !== void 0) query["expand"] = params.expand;
8816
+ for (const key of ["page", "per_page", "per-page"]) {
8817
+ if (params[key] !== void 0 && (!Number.isSafeInteger(params[key]) || params[key] <= 0)) {
8818
+ throw new ValidationError(`${key} must be a positive safe integer`);
8819
+ }
8820
+ if (params[key] !== void 0) query[key] = params[key];
8821
+ }
8822
+ return cleanListParams(query);
8823
+ }
8824
+ function buildContractInput(payload) {
8825
+ assertRecord(payload, "contract payload");
8826
+ if (payload.status !== void 0 && !CONTRACT_STATUSES.has(payload.status)) {
8827
+ throw new ValidationError("status must be draft, active, expired, or terminated");
8828
+ }
8829
+ for (const key of ["counterparty_name", "counterparty_taxpayer_id", "owner_id"]) {
8830
+ assertNullableString(payload[key], key);
8831
+ }
8832
+ if (typeof payload.counterparty_name === "string" && [...payload.counterparty_name].length > 255) {
8833
+ throw new ValidationError("counterparty_name must be at most 255 characters");
8834
+ }
8835
+ validateMoney(payload.value, "value");
8836
+ if (payload.currency !== void 0 && payload.currency !== null && (typeof payload.currency !== "string" || !/^[A-Za-z]{3}$/u.test(payload.currency))) {
8837
+ throw new ValidationError("currency must be a three-letter code or null");
8838
+ }
8839
+ for (const key of ["start_date", "end_date"]) {
8840
+ if (payload[key] !== void 0 && payload[key] !== null) assertDate(payload[key], key);
8841
+ }
8842
+ if (typeof payload.start_date === "string" && typeof payload.end_date === "string" && payload.end_date < payload.start_date) {
8843
+ throw new ValidationError("end_date must be on or after start_date");
8844
+ }
8845
+ if (payload.auto_renew !== void 0 && typeof payload.auto_renew !== "boolean") {
8846
+ throw new ValidationError("auto_renew must be a boolean");
8847
+ }
8848
+ validateNullableInteger(payload.renewal_term_months, "renewal_term_months", 1, 600);
8849
+ validateNullableInteger(payload.notice_period_days, "notice_period_days", 0, 3650);
8850
+ validateMetadata(payload.metadata);
8851
+ validateExternalReferences(payload.external_references);
8852
+ assertNullableString(payload.parent_document_id, "parent_document_id");
8853
+ if (payload.relation_type !== void 0 && !RELATION_TYPES.has(payload.relation_type)) {
8854
+ throw new ValidationError("relation_type must be amendment, renewal, or termination");
8855
+ }
8856
+ if (payload.updated_at !== void 0 && payload.updated_at !== null) {
8857
+ assertDateTime(payload.updated_at, "updated_at");
8858
+ }
8859
+ const body = {};
8860
+ for (const key of CONTRACT_INPUT_KEYS) {
8861
+ if (payload[key] !== void 0) body[key] = payload[key];
8862
+ }
8863
+ if (Array.isArray(payload.external_references)) {
8864
+ body["external_references"] = payload.external_references.map(({ system, id }) => ({
8865
+ system,
8866
+ id
8867
+ }));
8868
+ }
8869
+ if (Object.keys(body).length === 0) {
8870
+ throw new ValidationError("contract payload must include at least one attribute");
8871
+ }
8872
+ return body;
8873
+ }
8874
+ function buildRenewPayload(payload) {
8875
+ assertRecord(payload, "contract renewal payload");
8876
+ const hasExplicitEndDate = payload.end_date !== void 0 && payload.end_date !== null && payload.end_date !== "";
8877
+ if (hasExplicitEndDate) {
8878
+ assertDate(payload.end_date, "end_date");
8879
+ }
8880
+ validateMoney(payload.value, "value");
8881
+ if (payload.term !== void 0 && (!Number.isSafeInteger(payload.term) || payload.term < 1)) {
8882
+ throw new ValidationError("term must be a positive safe integer");
8883
+ }
8884
+ if (!hasExplicitEndDate && payload.term === void 0) {
8885
+ throw new ValidationError("term is required when end_date is absent, empty, or null");
8886
+ }
8887
+ if (payload.updated_at !== void 0) assertDateTime(payload.updated_at, "updated_at");
8888
+ const body = {};
8889
+ for (const key of ["end_date", "value", "term", "updated_at"]) {
8890
+ if (payload[key] !== void 0) body[key] = payload[key];
8891
+ }
8892
+ return body;
8893
+ }
8894
+ function buildTerminatePayload(payload) {
8895
+ assertRecord(payload, "contract termination payload");
8896
+ if (payload.reason !== void 0 && payload.reason !== null && (typeof payload.reason !== "string" || [...payload.reason].length > 500)) {
8897
+ throw new ValidationError("reason must be a string of at most 500 characters or null");
8898
+ }
8899
+ if (payload.updated_at !== void 0) assertDateTime(payload.updated_at, "updated_at");
8900
+ const body = {};
8901
+ if (payload.reason !== void 0) body["reason"] = payload.reason;
8902
+ if (payload.updated_at !== void 0) body["updated_at"] = payload.updated_at;
8903
+ return body;
8904
+ }
8905
+ function assertDate(value, label) {
8906
+ if (typeof value !== "string") throw new ValidationError(`${label} must use YYYY-MM-DD`);
8907
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/u.exec(value);
8908
+ if (!match) throw new ValidationError(`${label} must use YYYY-MM-DD`);
8909
+ const year = Number(match[1]);
8910
+ const month = Number(match[2]);
8911
+ const day = Number(match[3]);
8912
+ const date = new Date(Date.UTC(year, month - 1, day));
8913
+ if (year < 1e3 || date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
8914
+ throw new ValidationError(`${label} must be a valid date from year 1000`);
8915
+ }
8916
+ }
8917
+ function assertOptionalString(value, label) {
8918
+ if (typeof value !== "string") throw new ValidationError(`${label} must be a string`);
8919
+ }
8920
+ function assertNullableString(value, label) {
8921
+ if (value !== void 0 && value !== null && typeof value !== "string") {
8922
+ throw new ValidationError(`${label} must be a string or null`);
8923
+ }
8924
+ }
8925
+ function validateMoney(value, label) {
8926
+ if (value !== void 0 && value !== null && (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 999999999999999e-2 || Number(value.toFixed(2)) !== value)) {
8927
+ throw new ValidationError(
8928
+ `${label} must be a finite non-negative amount with at most two decimals or null`
8929
+ );
8930
+ }
8931
+ }
8932
+ function validateNullableInteger(value, label, minimum, maximum) {
8933
+ if (value !== void 0 && value !== null && (!Number.isSafeInteger(value) || value < minimum || value > maximum)) {
8934
+ throw new ValidationError(`${label} must be an integer from ${minimum} to ${maximum}, or null`);
8935
+ }
8936
+ }
8937
+ function validateMetadata(value) {
8938
+ if (value === void 0 || value === null) return;
8939
+ assertRecord(value, "metadata");
8940
+ const entries = Object.entries(value);
8941
+ if (entries.length > 50) throw new ValidationError("metadata must have at most 50 keys");
8942
+ for (const [key, item] of entries) {
8943
+ if (!/^[A-Za-z0-9_.-]{1,40}$/u.test(key)) {
8944
+ throw new ValidationError("metadata keys must use 1-40 letters, digits, _, -, or .");
8945
+ }
8946
+ if (typeof item !== "string" || [...item].length > 500) {
8947
+ throw new ValidationError(`metadata.${key} must be a string of at most 500 characters`);
8948
+ }
8949
+ }
8950
+ }
8951
+ function validateExternalReferences(value) {
8952
+ if (value === void 0 || value === null) return;
8953
+ if (!Array.isArray(value) || value.length > 20) {
8954
+ throw new ValidationError("external_references must be an array of at most 20 entries or null");
8955
+ }
8956
+ for (const reference of value) {
8957
+ assertRecord(reference, "external reference");
8958
+ if (typeof reference["system"] !== "string" || !/^[A-Za-z0-9_.-]{1,64}$/u.test(reference["system"])) {
8959
+ throw new ValidationError("external reference system is invalid");
8960
+ }
8961
+ if (typeof reference["id"] !== "string" || reference["id"].length === 0 || [...reference["id"]].length > 255 || /[\u{10000}-\u{10FFFF}]/u.test(reference["id"])) {
8962
+ throw new ValidationError("external reference id must be 1-255 three-byte characters");
8963
+ }
8964
+ }
8965
+ }
8966
+
8351
8967
  // src/support/webhook-verifier.ts
8352
8968
  var import_node_crypto2 = require("crypto");
8353
8969
  var DEFAULT_TOLERANCE_SECONDS = 300;
@@ -8440,11 +9056,7 @@ var WebhookVerifier = class {
8440
9056
  if (!/^[\da-f]{64}$/i.test(provided)) return false;
8441
9057
  const expected = (0, import_node_crypto2.createHmac)("sha256", this.webhookSecret).update(buf).digest();
8442
9058
  const actual = Buffer.from(provided, "hex");
8443
- try {
8444
- return (0, import_node_crypto2.timingSafeEqual)(expected, actual);
8445
- } catch {
8446
- return false;
8447
- }
9059
+ return (0, import_node_crypto2.timingSafeEqual)(expected, actual);
8448
9060
  }
8449
9061
  /**
8450
9062
  * Parse the raw webhook body into a JSON object. Both the rich envelope and
@@ -8539,6 +9151,7 @@ var AssinafyClient = class _AssinafyClient {
8539
9151
  fields;
8540
9152
  signerDocuments;
8541
9153
  users;
9154
+ contracts;
8542
9155
  webhookVerifier;
8543
9156
  /**
8544
9157
  * Create a client. Supply `apiKey` (preferred, sent as `X-Api-Key`) or a
@@ -8656,6 +9269,11 @@ var AssinafyClient = class _AssinafyClient {
8656
9269
  this.publicAxiosInstance
8657
9270
  );
8658
9271
  this.users = new UserResource(this.axiosInstance, void 0, this.logger);
9272
+ this.contracts = new ContractResource(
9273
+ this.axiosInstance,
9274
+ this.defaultAccountId,
9275
+ this.logger
9276
+ );
8659
9277
  this.webhookVerifier = new WebhookVerifier(this.webhookSecret);
8660
9278
  }
8661
9279
  /**
@@ -9082,6 +9700,7 @@ function hasIdempotencyKey(headers) {
9082
9700
  AssinafyClient,
9083
9701
  AssinafyError,
9084
9702
  AuthenticationResource,
9703
+ ContractResource,
9085
9704
  DEFAULT_WEBHOOK_EVENTS,
9086
9705
  DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD,
9087
9706
  DocumentResource,