@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.mjs CHANGED
@@ -628,8 +628,8 @@ import axios2 from "axios";
628
628
  // package.json
629
629
  var package_default = {
630
630
  name: "@assinafy/sdk",
631
- version: "2.8.1",
632
- packageManager: "bun@1.4.0",
631
+ version: "2.9.0",
632
+ packageManager: "bun@1.4.4",
633
633
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
634
634
  type: "commonjs",
635
635
  main: "dist/index.js",
@@ -672,6 +672,8 @@ var package_default = {
672
672
  "digital-signature",
673
673
  "electronic-signature",
674
674
  "signature",
675
+ "contract-lifecycle-management",
676
+ "gestao-de-contratos",
675
677
  "pdf",
676
678
  "webhook",
677
679
  "sdk",
@@ -695,20 +697,21 @@ var package_default = {
695
697
  devDependencies: {
696
698
  "@arethetypeswrong/cli": "^0.18.5",
697
699
  "@eslint/js": "^10.0.1",
698
- "@types/bun": "^1.4.0",
699
- "@types/node": "^22.20.1",
700
+ "@types/bun": "^1.4.4",
701
+ "@types/node": "^22.20.5",
700
702
  "@typescript/native": "npm:typescript@^7.0.2",
701
- eslint: "^10.9.1",
702
- publint: "^0.3.24",
703
+ eslint: "^10.13.0",
704
+ publint: "^0.3.25",
703
705
  tsup: "^8.5.1",
704
706
  typescript: "^6.0.3",
705
- "typescript-eslint": "^8.68.0"
707
+ "typescript-eslint": "^8.72.1"
706
708
  },
707
709
  dependencies: {
708
- axios: "^1.20.0"
710
+ axios: "^1.21.0"
709
711
  },
710
712
  overrides: {
711
713
  esbuild: "0.28.2",
714
+ "follow-redirects": "1.16.2",
712
715
  "brace-expansion": "5.0.12"
713
716
  },
714
717
  files: [
@@ -7993,7 +7996,7 @@ var UserResource = class extends BaseResource {
7993
7996
  *
7994
7997
  * Request body: none. Authentication: `X-Api-Key` or Bearer token.
7995
7998
  *
7996
- * @returns The complete nine-key preference map:
7999
+ * @returns The complete thirteen-key preference map:
7997
8000
  * ```json
7998
8001
  * {
7999
8002
  * "DocumentCompleted": true,
@@ -8004,7 +8007,11 @@ var UserResource = class extends BaseResource {
8004
8007
  * "DocumentExpirationReset": true,
8005
8008
  * "DocumentProcessingFailed": true,
8006
8009
  * "TemplateProcessingFailed": true,
8007
- * "SignerWhatsappFailed": true
8010
+ * "SignerWhatsappFailed": true,
8011
+ * "ContractRenewalNotice": true,
8012
+ * "ContractExpiring": true,
8013
+ * "ContractExpired": true,
8014
+ * "ContractRenewed": true
8008
8015
  * }
8009
8016
  * ```
8010
8017
  * @throws {ApiError} `401` when credentials are missing/invalid, or `500`
@@ -8037,16 +8044,33 @@ var UserResource = class extends BaseResource {
8037
8044
  * "DocumentExpirationReset": true,
8038
8045
  * "DocumentProcessingFailed": true,
8039
8046
  * "TemplateProcessingFailed": true,
8040
- * "SignerWhatsappFailed": true
8047
+ * "SignerWhatsappFailed": true,
8048
+ * "ContractRenewalNotice": true,
8049
+ * "ContractExpiring": true,
8050
+ * "ContractExpired": true,
8051
+ * "ContractRenewed": true
8041
8052
  * }
8042
8053
  * ```
8043
8054
  *
8044
- * @param preferences - One or more of the nine documented keys, each with
8055
+ * @param preferences - One or more of the thirteen documented keys, each with
8045
8056
  * a boolean value. Request example:
8046
8057
  * ```json
8047
8058
  * { "DocumentCompleted": true, "SignerDeclined": false }
8048
8059
  * ```
8049
- * @returns The complete updated nine-key preference map:
8060
+ * @param preferences.DocumentCompleted - Notify when a document completes.
8061
+ * @param preferences.SignerDeclined - Notify when a signer declines.
8062
+ * @param preferences.DocumentCancelled - Notify when a document is cancelled.
8063
+ * @param preferences.DocumentAboutToExpire - Notify before signature expiry.
8064
+ * @param preferences.DocumentExpired - Notify after signature expiry.
8065
+ * @param preferences.DocumentExpirationReset - Notify after resetting expiry.
8066
+ * @param preferences.DocumentProcessingFailed - Notify after document processing fails.
8067
+ * @param preferences.TemplateProcessingFailed - Notify after template processing fails.
8068
+ * @param preferences.SignerWhatsappFailed - Notify after WhatsApp delivery fails.
8069
+ * @param preferences.ContractRenewalNotice - Notify when the contract notice period starts.
8070
+ * @param preferences.ContractExpiring - Notify before a tracked contract ends.
8071
+ * @param preferences.ContractExpired - Notify when a tracked contract expires.
8072
+ * @param preferences.ContractRenewed - Notify when a tracked contract renews.
8073
+ * @returns The complete updated thirteen-key preference map:
8050
8074
  * ```json
8051
8075
  * {
8052
8076
  * "DocumentCompleted": true,
@@ -8057,7 +8081,11 @@ var UserResource = class extends BaseResource {
8057
8081
  * "DocumentExpirationReset": true,
8058
8082
  * "DocumentProcessingFailed": true,
8059
8083
  * "TemplateProcessingFailed": true,
8060
- * "SignerWhatsappFailed": true
8084
+ * "SignerWhatsappFailed": true,
8085
+ * "ContractRenewalNotice": true,
8086
+ * "ContractExpiring": true,
8087
+ * "ContractExpired": true,
8088
+ * "ContractRenewed": true
8061
8089
  * }
8062
8090
  * ```
8063
8091
  * @throws {ValidationError} Before requesting when the map is empty, has an
@@ -8269,7 +8297,11 @@ var NOTIFICATION_PREFERENCE_KEYS = /* @__PURE__ */ new Set([
8269
8297
  "DocumentExpirationReset",
8270
8298
  "DocumentProcessingFailed",
8271
8299
  "TemplateProcessingFailed",
8272
- "SignerWhatsappFailed"
8300
+ "SignerWhatsappFailed",
8301
+ "ContractRenewalNotice",
8302
+ "ContractExpiring",
8303
+ "ContractExpired",
8304
+ "ContractRenewed"
8273
8305
  ]);
8274
8306
  function validateNotificationPreferences(preferences) {
8275
8307
  assertRecord(preferences, "notification preferences");
@@ -8287,6 +8319,589 @@ function validateNotificationPreferences(preferences) {
8287
8319
  }
8288
8320
  }
8289
8321
 
8322
+ // src/resources/contracts.ts
8323
+ var CONTRACT_STATUSES = /* @__PURE__ */ new Set(["draft", "active", "expired", "terminated"]);
8324
+ var RELATION_TYPES = /* @__PURE__ */ new Set(["amendment", "renewal", "termination"]);
8325
+ var CONTRACT_INPUT_KEYS = [
8326
+ "status",
8327
+ "counterparty_name",
8328
+ "counterparty_taxpayer_id",
8329
+ "value",
8330
+ "currency",
8331
+ "start_date",
8332
+ "end_date",
8333
+ "auto_renew",
8334
+ "renewal_term_months",
8335
+ "notice_period_days",
8336
+ "owner_id",
8337
+ "metadata",
8338
+ "external_references",
8339
+ "parent_document_id",
8340
+ "relation_type",
8341
+ "updated_at"
8342
+ ];
8343
+ var ContractResource = class extends BaseResource {
8344
+ /**
8345
+ * List the workspace's tracked contracts (`GET /accounts/{accountId}/contracts`).
8346
+ *
8347
+ * Results are ordered by `-updated_at` unless `sort` is supplied. Use
8348
+ * `updated_at` to catch up after a missed webhook; `ending_within_days` is
8349
+ * evaluated by the API in the Brasília calendar day. OAuth tokens need
8350
+ * `documents:read`.
8351
+ *
8352
+ * @param params - Optional filters, expansion, sorting, and pagination.
8353
+ * @param params.status - Contract states to match; sent comma-separated.
8354
+ * @param params.counterparty - Part of the name, or an exact CPF/CNPJ.
8355
+ * @param params.search - Part of the document name.
8356
+ * @param params.end_date_from - Earliest end date (`YYYY-MM-DD`).
8357
+ * @param params.end_date_to - Latest end date (`YYYY-MM-DD`).
8358
+ * @param params.ending_within_days - Inclusive 0–3650 day window from today.
8359
+ * @param params.external_system - External-reference system.
8360
+ * @param params.external_id - External-reference ID.
8361
+ * @param params.sort - `end_date` / `updated_at`, optionally prefixed by `-`.
8362
+ * @param params.expand - Pass `document` to embed each document.
8363
+ * @param params.page - One-based page number.
8364
+ * @param params.per_page - Alias normalized to the API's `per-page` spelling.
8365
+ * @param params.per-page - Page size; the deployed API returns at most 50.
8366
+ * @param accountId - Override the client's default account ID.
8367
+ * @returns Contract rows and pagination metadata:
8368
+ * ```jsonc
8369
+ * {
8370
+ * "data": [{
8371
+ * "document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8372
+ * "status": "active",
8373
+ * "counterparty_name": "Example Ltda",
8374
+ * "counterparty_taxpayer_id": "11222333000181",
8375
+ * "value": 120000.5,
8376
+ * "currency": "BRL",
8377
+ * "start_date": "2026-11-01",
8378
+ * "end_date": "2027-10-31",
8379
+ * "auto_renew": true,
8380
+ * "renewal_term_months": 12,
8381
+ * "notice_period_days": 30,
8382
+ * "term": 1,
8383
+ * "owner_id": "d6zqpbyog2v3xvxerwn8la94",
8384
+ * "metadata": { "crm_stage": "won" },
8385
+ * "external_references": [{ "system": "crm", "id": "98765" }],
8386
+ * "created_at": "2026-10-23T12:00:00Z",
8387
+ * "updated_at": "2026-10-23T12:00:00Z"
8388
+ * }],
8389
+ * "meta": { "current_page": 1, "per_page": 20, "total": 1, "last_page": 1 }
8390
+ * }
8391
+ * ```
8392
+ * @throws {ValidationError} If a filter is malformed or no account ID is available.
8393
+ * @throws {ApiError} `400` for invalid filters, `401` for invalid credentials,
8394
+ * or `500` when the API cannot list contracts.
8395
+ *
8396
+ * @example
8397
+ * ```ts
8398
+ * const contracts = await client.contracts.list({
8399
+ * status: ['active'],
8400
+ * ending_within_days: 30,
8401
+ * expand: 'document',
8402
+ * });
8403
+ * ```
8404
+ */
8405
+ async list(params = {}, accountId) {
8406
+ const query = buildListParams(params);
8407
+ const id = this.accountId(accountId);
8408
+ return this.callList(
8409
+ "Failed to list contracts",
8410
+ () => this.http.get(`/accounts/${this.pathSegment(id, "Account ID")}/contracts`, {
8411
+ params: query
8412
+ })
8413
+ );
8414
+ }
8415
+ /**
8416
+ * Read a document's contract terms or amendment link
8417
+ * (`GET /accounts/{accountId}/documents/{documentId}/contract`).
8418
+ *
8419
+ * A root contract includes its `amendments`; a document that is itself an
8420
+ * instrument returns the `document_contract_amendment` shape. Reads remain
8421
+ * available if the workspace's plan no longer includes contract tracking.
8422
+ *
8423
+ * @param documentId - Contract or amendment document ID.
8424
+ * @param accountId - Override the client's default account ID.
8425
+ * @returns The root contract or amendment. Root-contract response:
8426
+ * ```jsonc
8427
+ * {
8428
+ * "resource": "document_contract",
8429
+ * "document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8430
+ * "status": "active",
8431
+ * "counterparty_name": "Example Ltda",
8432
+ * "counterparty_taxpayer_id": "11222333000181",
8433
+ * "value": 130000,
8434
+ * "currency": "BRL",
8435
+ * "start_date": "2026-11-01",
8436
+ * "end_date": "2028-06-30",
8437
+ * "auto_renew": true,
8438
+ * "renewal_term_months": 12,
8439
+ * "notice_period_days": 30,
8440
+ * "term": 2,
8441
+ * "owner_id": null,
8442
+ * "metadata": null,
8443
+ * "external_references": [],
8444
+ * "amendments": [],
8445
+ * "created_at": "2026-10-23T12:00:00Z",
8446
+ * "updated_at": "2027-05-12T18:20:00Z"
8447
+ * }
8448
+ * ```
8449
+ * @throws {ValidationError} If an ID is missing or invalid.
8450
+ * @throws {ApiError} `401` for invalid credentials, `404` when the document
8451
+ * has no tracked terms, or `500` on a server error.
8452
+ *
8453
+ * @example
8454
+ * ```ts
8455
+ * const contract = await client.contracts.get(document.id);
8456
+ * if (contract.resource === 'document_contract_amendment') {
8457
+ * console.log(contract.parent_document_id);
8458
+ * }
8459
+ * ```
8460
+ */
8461
+ async get(documentId, accountId) {
8462
+ return this.call(
8463
+ "Failed to fetch contract terms",
8464
+ () => this.http.get(this.contractPath(documentId, accountId))
8465
+ );
8466
+ }
8467
+ /**
8468
+ * Create or partially update contract terms
8469
+ * (`PUT /accounts/{accountId}/documents/{documentId}/contract`).
8470
+ *
8471
+ * Only supplied fields are sent. `external_references` replaces the list;
8472
+ * `parent_document_id` links this document as an instrument. Pass the
8473
+ * `updated_at` previously read to reject concurrent changes with `409`.
8474
+ * OAuth tokens need `documents:write`; writes require a contract-tracking plan.
8475
+ *
8476
+ * @param documentId - Document whose terms or amendment link will change.
8477
+ * @param payload - At least one contract attribute.
8478
+ * @param payload.status - `draft`, `active`, `expired`, or `terminated`.
8479
+ * @param payload.counterparty_name - Counterparty name; null clears it.
8480
+ * @param payload.counterparty_taxpayer_id - CPF/CNPJ; null clears it.
8481
+ * @param payload.value - Non-negative contract value; null clears it.
8482
+ * @param payload.currency - Three-letter currency; null resets as documented.
8483
+ * @param payload.start_date - Start date (`YYYY-MM-DD`), or null.
8484
+ * @param payload.end_date - End date (`YYYY-MM-DD`), or null.
8485
+ * @param payload.auto_renew - Whether the hourly lifecycle starts a new term.
8486
+ * @param payload.renewal_term_months - 1–600 months, or null for the default.
8487
+ * @param payload.notice_period_days - 0–3650 days, or null to disable notice.
8488
+ * @param payload.owner_id - Active workspace member ID, or null.
8489
+ * @param payload.metadata - Up to 50 string fields, or null.
8490
+ * @param payload.external_references - Up to 20 `{ system, id }` entries; null/[] clears.
8491
+ * @param payload.parent_document_id - Parent contract document, or null to unlink pending.
8492
+ * @param payload.relation_type - `amendment`, `renewal`, or `termination`.
8493
+ * @param payload.updated_at - Optimistic-concurrency timestamp, or null for last-write-wins.
8494
+ * @param accountId - Override the client's default account ID.
8495
+ * @returns The saved contract or amendment link. Amendment response:
8496
+ * ```jsonc
8497
+ * {
8498
+ * "resource": "document_contract_amendment",
8499
+ * "document_id": "7c3d1e2f4a5b6c7d8e9f0a1b",
8500
+ * "document_name": "Amendment 1.pdf",
8501
+ * "parent_document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8502
+ * "relation_type": "amendment",
8503
+ * "number": null,
8504
+ * "status": "pending",
8505
+ * "document_status": "pending_signature",
8506
+ * "apply_error": null,
8507
+ * "currency": "BRL",
8508
+ * "terms": { "value": 130000, "end_date": "2028-06-30" },
8509
+ * "changes": { "value": { "from": 120000.5, "to": 130000 } },
8510
+ * "applied_at": null,
8511
+ * "created_at": "2027-05-10T15:00:00Z",
8512
+ * "updated_at": "2027-05-10T15:00:00Z"
8513
+ * }
8514
+ * ```
8515
+ * @throws {ValidationError} If the payload or an ID is malformed.
8516
+ * @throws {ApiError} `400` for invalid terms, `403` when the plan does not
8517
+ * include tracking, `404` for an unknown document, `409` after a concurrent
8518
+ * change, or `500` on a server error.
8519
+ *
8520
+ * @example
8521
+ * ```ts
8522
+ * const contract = await client.contracts.set(document.id, {
8523
+ * status: 'active',
8524
+ * counterparty_name: 'Example Ltda',
8525
+ * value: 120000.50,
8526
+ * currency: 'BRL',
8527
+ * start_date: '2026-11-01',
8528
+ * end_date: '2027-10-31',
8529
+ * });
8530
+ * ```
8531
+ */
8532
+ async set(documentId, payload, accountId) {
8533
+ const body = buildContractInput(payload);
8534
+ return this.call(
8535
+ "Failed to set contract terms",
8536
+ () => this.http.put(this.contractPath(documentId, accountId), body)
8537
+ );
8538
+ }
8539
+ /**
8540
+ * Read a document's complete contract family
8541
+ * (`GET /accounts/{accountId}/documents/{documentId}/contract/related`).
8542
+ *
8543
+ * The document may be the root or any linked instrument; the response is
8544
+ * always the root contract with every amendment, renewal, and termination.
8545
+ *
8546
+ * @param documentId - Any document in the contract family.
8547
+ * @param accountId - Override the client's default account ID.
8548
+ * @returns The root contract and ordered instruments:
8549
+ * ```jsonc
8550
+ * {
8551
+ * "resource": "document_contract",
8552
+ * "document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8553
+ * "status": "active",
8554
+ * "counterparty_name": "Example Ltda",
8555
+ * "counterparty_taxpayer_id": "11222333000181",
8556
+ * "value": 130000,
8557
+ * "currency": "BRL",
8558
+ * "start_date": "2026-11-01",
8559
+ * "end_date": "2028-06-30",
8560
+ * "auto_renew": true,
8561
+ * "renewal_term_months": 12,
8562
+ * "notice_period_days": 30,
8563
+ * "term": 2,
8564
+ * "owner_id": null,
8565
+ * "metadata": null,
8566
+ * "external_references": [],
8567
+ * "amendments": [{
8568
+ * "document_id": "7c3d1e2f4a5b6c7d8e9f0a1b",
8569
+ * "document_name": "Amendment 1.pdf",
8570
+ * "parent_document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8571
+ * "relation_type": "amendment",
8572
+ * "status": "applied",
8573
+ * "number": 1,
8574
+ * "document_status": "certificated",
8575
+ * "apply_error": null,
8576
+ * "currency": "BRL",
8577
+ * "terms": { "value": 130000, "end_date": "2028-06-30" },
8578
+ * "changes": {
8579
+ * "value": { "from": 120000.5, "to": 130000 },
8580
+ * "end_date": { "from": "2027-10-31", "to": "2028-06-30" }
8581
+ * },
8582
+ * "applied_at": "2027-05-12T18:20:00Z",
8583
+ * "created_at": "2027-05-10T15:00:00Z",
8584
+ * "updated_at": "2027-05-12T18:20:00Z"
8585
+ * }],
8586
+ * "created_at": "2026-10-23T12:00:00Z",
8587
+ * "updated_at": "2027-05-12T18:20:00Z"
8588
+ * }
8589
+ * ```
8590
+ * @throws {ValidationError} If an ID is missing or invalid.
8591
+ * @throws {ApiError} `401` for invalid credentials, `404` when no contract
8592
+ * family exists, or `500` on a server error.
8593
+ *
8594
+ * @example
8595
+ * ```ts
8596
+ * const family = await client.contracts.listRelated(amendmentDocument.id);
8597
+ * ```
8598
+ */
8599
+ async listRelated(documentId, accountId) {
8600
+ return this.call(
8601
+ "Failed to fetch related contracts",
8602
+ () => this.http.get(`${this.contractPath(documentId, accountId)}/related`)
8603
+ );
8604
+ }
8605
+ /**
8606
+ * Start a contract's next term
8607
+ * (`POST /accounts/{accountId}/documents/{documentId}/contract/renew`).
8608
+ *
8609
+ * Supply the current `term` to make a by-term renewal safe to repeat, or an
8610
+ * explicit later `end_date`. `updated_at` rejects concurrent changes. A
8611
+ * renewal reopens an expired contract but cannot reopen a terminated one.
8612
+ *
8613
+ * @param documentId - Root contract document ID.
8614
+ * @param payload - Renewal precondition and optional new date/value.
8615
+ * @param payload.end_date - Explicit new end date, or null to renew by term.
8616
+ * @param payload.value - New value; omitted keeps it and null clears it.
8617
+ * @param payload.term - Current term, required by the API when no date is sent.
8618
+ * @param payload.updated_at - Optional optimistic-concurrency timestamp.
8619
+ * @param accountId - Override the client's default account ID.
8620
+ * @returns The renewed contract:
8621
+ * ```jsonc
8622
+ * {
8623
+ * "resource": "document_contract",
8624
+ * "document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8625
+ * "status": "active",
8626
+ * "counterparty_name": "Example Ltda",
8627
+ * "counterparty_taxpayer_id": "11222333000181",
8628
+ * "value": 130000,
8629
+ * "currency": "BRL",
8630
+ * "start_date": "2026-11-01",
8631
+ * "end_date": "2029-06-30",
8632
+ * "auto_renew": true,
8633
+ * "renewal_term_months": 12,
8634
+ * "notice_period_days": 30,
8635
+ * "term": 2,
8636
+ * "owner_id": null,
8637
+ * "metadata": null,
8638
+ * "external_references": [],
8639
+ * "created_at": "2026-10-23T12:00:00Z",
8640
+ * "updated_at": "2027-10-15T09:30:00Z"
8641
+ * }
8642
+ * ```
8643
+ * @throws {ValidationError} If the payload or an ID is malformed.
8644
+ * @throws {ApiError} `400` for an invalid renewal, `403` when tracking is
8645
+ * unavailable, `404` when terms do not exist, `409` after a concurrent
8646
+ * change, or `500` on a server error.
8647
+ *
8648
+ * @example
8649
+ * ```ts
8650
+ * const renewed = await client.contracts.renew(document.id, {
8651
+ * term: contract.term,
8652
+ * value: 130000,
8653
+ * updated_at: contract.updated_at,
8654
+ * });
8655
+ * ```
8656
+ */
8657
+ async renew(documentId, payload, accountId) {
8658
+ const body = buildRenewPayload(payload);
8659
+ return this.call(
8660
+ "Failed to renew contract",
8661
+ () => this.http.post(`${this.contractPath(documentId, accountId)}/renew`, body)
8662
+ );
8663
+ }
8664
+ /**
8665
+ * Close a contract (`POST /accounts/{accountId}/documents/{documentId}/contract/terminate`).
8666
+ *
8667
+ * Termination stops lifecycle alerts and records the optional reason in the
8668
+ * document activity. Pass `updated_at` to reject concurrent changes.
8669
+ *
8670
+ * @param documentId - Root contract document ID.
8671
+ * @param payload - Optional reason and concurrency precondition.
8672
+ * @param payload.reason - Activity reason (up to 500 characters), or null.
8673
+ * @param payload.updated_at - Optional optimistic-concurrency timestamp.
8674
+ * @param accountId - Override the client's default account ID.
8675
+ * @returns The terminated contract:
8676
+ * ```jsonc
8677
+ * {
8678
+ * "resource": "document_contract",
8679
+ * "document_id": "66b2f0e1c3a4d5e6f7a8b9c0",
8680
+ * "status": "terminated",
8681
+ * "counterparty_name": "Example Ltda",
8682
+ * "counterparty_taxpayer_id": "11222333000181",
8683
+ * "value": 120000.5,
8684
+ * "currency": "BRL",
8685
+ * "start_date": "2026-11-01",
8686
+ * "end_date": "2027-10-31",
8687
+ * "auto_renew": false,
8688
+ * "renewal_term_months": 12,
8689
+ * "notice_period_days": 30,
8690
+ * "term": 1,
8691
+ * "owner_id": null,
8692
+ * "metadata": null,
8693
+ * "external_references": [],
8694
+ * "created_at": "2026-10-23T12:00:00Z",
8695
+ * "updated_at": "2027-03-02T14:00:00Z"
8696
+ * }
8697
+ * ```
8698
+ * @throws {ValidationError} If the payload or an ID is malformed.
8699
+ * @throws {ApiError} `400` for invalid state/input, `403` when tracking is
8700
+ * unavailable, `404` when terms do not exist, `409` after a concurrent
8701
+ * change, or `500` on a server error.
8702
+ *
8703
+ * @example
8704
+ * ```ts
8705
+ * await client.contracts.terminate(document.id, {
8706
+ * reason: 'Replaced by a new agreement',
8707
+ * updated_at: contract.updated_at,
8708
+ * });
8709
+ * ```
8710
+ */
8711
+ async terminate(documentId, payload = {}, accountId) {
8712
+ const body = buildTerminatePayload(payload);
8713
+ return this.call(
8714
+ "Failed to terminate contract",
8715
+ () => this.http.post(`${this.contractPath(documentId, accountId)}/terminate`, body)
8716
+ );
8717
+ }
8718
+ contractPath(documentId, accountId) {
8719
+ const id = this.accountId(accountId);
8720
+ return `/accounts/${this.pathSegment(id, "Account ID")}/documents/${this.pathSegment(documentId, "Document ID")}/contract`;
8721
+ }
8722
+ };
8723
+ function buildListParams(params) {
8724
+ assertRecord(params, "contract list params");
8725
+ const query = {};
8726
+ if (params.status !== void 0) {
8727
+ if (!Array.isArray(params.status) || params.status.length === 0 || params.status.some((status) => !CONTRACT_STATUSES.has(status))) {
8728
+ throw new ValidationError("status must be a non-empty array of contract statuses");
8729
+ }
8730
+ query["status"] = params.status.join(",");
8731
+ }
8732
+ for (const key of ["counterparty", "search", "external_system", "external_id"]) {
8733
+ if (params[key] !== void 0) assertOptionalString(params[key], key);
8734
+ if (params[key] !== void 0) query[key] = params[key];
8735
+ }
8736
+ for (const key of ["end_date_from", "end_date_to"]) {
8737
+ if (params[key] !== void 0) assertDate(params[key], key);
8738
+ if (params[key] !== void 0) query[key] = params[key];
8739
+ }
8740
+ if (params.ending_within_days !== void 0 && (!Number.isSafeInteger(params.ending_within_days) || params.ending_within_days < 0 || params.ending_within_days > 3650)) {
8741
+ throw new ValidationError("ending_within_days must be an integer from 0 to 3650");
8742
+ }
8743
+ if (params.ending_within_days !== void 0) {
8744
+ query["ending_within_days"] = params.ending_within_days;
8745
+ }
8746
+ if (params.sort !== void 0 && !["end_date", "-end_date", "updated_at", "-updated_at"].includes(params.sort)) {
8747
+ throw new ValidationError("sort must be end_date or updated_at, optionally prefixed by -");
8748
+ }
8749
+ if (params.sort !== void 0) query["sort"] = params.sort;
8750
+ if (params.expand !== void 0 && params.expand !== "document") {
8751
+ throw new ValidationError("expand must be document");
8752
+ }
8753
+ if (params.expand !== void 0) query["expand"] = params.expand;
8754
+ for (const key of ["page", "per_page", "per-page"]) {
8755
+ if (params[key] !== void 0 && (!Number.isSafeInteger(params[key]) || params[key] <= 0)) {
8756
+ throw new ValidationError(`${key} must be a positive safe integer`);
8757
+ }
8758
+ if (params[key] !== void 0) query[key] = params[key];
8759
+ }
8760
+ return cleanListParams(query);
8761
+ }
8762
+ function buildContractInput(payload) {
8763
+ assertRecord(payload, "contract payload");
8764
+ if (payload.status !== void 0 && !CONTRACT_STATUSES.has(payload.status)) {
8765
+ throw new ValidationError("status must be draft, active, expired, or terminated");
8766
+ }
8767
+ for (const key of ["counterparty_name", "counterparty_taxpayer_id", "owner_id"]) {
8768
+ assertNullableString(payload[key], key);
8769
+ }
8770
+ if (typeof payload.counterparty_name === "string" && [...payload.counterparty_name].length > 255) {
8771
+ throw new ValidationError("counterparty_name must be at most 255 characters");
8772
+ }
8773
+ validateMoney(payload.value, "value");
8774
+ if (payload.currency !== void 0 && payload.currency !== null && (typeof payload.currency !== "string" || !/^[A-Za-z]{3}$/u.test(payload.currency))) {
8775
+ throw new ValidationError("currency must be a three-letter code or null");
8776
+ }
8777
+ for (const key of ["start_date", "end_date"]) {
8778
+ if (payload[key] !== void 0 && payload[key] !== null) assertDate(payload[key], key);
8779
+ }
8780
+ if (typeof payload.start_date === "string" && typeof payload.end_date === "string" && payload.end_date < payload.start_date) {
8781
+ throw new ValidationError("end_date must be on or after start_date");
8782
+ }
8783
+ if (payload.auto_renew !== void 0 && typeof payload.auto_renew !== "boolean") {
8784
+ throw new ValidationError("auto_renew must be a boolean");
8785
+ }
8786
+ validateNullableInteger(payload.renewal_term_months, "renewal_term_months", 1, 600);
8787
+ validateNullableInteger(payload.notice_period_days, "notice_period_days", 0, 3650);
8788
+ validateMetadata(payload.metadata);
8789
+ validateExternalReferences(payload.external_references);
8790
+ assertNullableString(payload.parent_document_id, "parent_document_id");
8791
+ if (payload.relation_type !== void 0 && !RELATION_TYPES.has(payload.relation_type)) {
8792
+ throw new ValidationError("relation_type must be amendment, renewal, or termination");
8793
+ }
8794
+ if (payload.updated_at !== void 0 && payload.updated_at !== null) {
8795
+ assertDateTime(payload.updated_at, "updated_at");
8796
+ }
8797
+ const body = {};
8798
+ for (const key of CONTRACT_INPUT_KEYS) {
8799
+ if (payload[key] !== void 0) body[key] = payload[key];
8800
+ }
8801
+ if (Array.isArray(payload.external_references)) {
8802
+ body["external_references"] = payload.external_references.map(({ system, id }) => ({
8803
+ system,
8804
+ id
8805
+ }));
8806
+ }
8807
+ if (Object.keys(body).length === 0) {
8808
+ throw new ValidationError("contract payload must include at least one attribute");
8809
+ }
8810
+ return body;
8811
+ }
8812
+ function buildRenewPayload(payload) {
8813
+ assertRecord(payload, "contract renewal payload");
8814
+ const hasExplicitEndDate = payload.end_date !== void 0 && payload.end_date !== null && payload.end_date !== "";
8815
+ if (hasExplicitEndDate) {
8816
+ assertDate(payload.end_date, "end_date");
8817
+ }
8818
+ validateMoney(payload.value, "value");
8819
+ if (payload.term !== void 0 && (!Number.isSafeInteger(payload.term) || payload.term < 1)) {
8820
+ throw new ValidationError("term must be a positive safe integer");
8821
+ }
8822
+ if (!hasExplicitEndDate && payload.term === void 0) {
8823
+ throw new ValidationError("term is required when end_date is absent, empty, or null");
8824
+ }
8825
+ if (payload.updated_at !== void 0) assertDateTime(payload.updated_at, "updated_at");
8826
+ const body = {};
8827
+ for (const key of ["end_date", "value", "term", "updated_at"]) {
8828
+ if (payload[key] !== void 0) body[key] = payload[key];
8829
+ }
8830
+ return body;
8831
+ }
8832
+ function buildTerminatePayload(payload) {
8833
+ assertRecord(payload, "contract termination payload");
8834
+ if (payload.reason !== void 0 && payload.reason !== null && (typeof payload.reason !== "string" || [...payload.reason].length > 500)) {
8835
+ throw new ValidationError("reason must be a string of at most 500 characters or null");
8836
+ }
8837
+ if (payload.updated_at !== void 0) assertDateTime(payload.updated_at, "updated_at");
8838
+ const body = {};
8839
+ if (payload.reason !== void 0) body["reason"] = payload.reason;
8840
+ if (payload.updated_at !== void 0) body["updated_at"] = payload.updated_at;
8841
+ return body;
8842
+ }
8843
+ function assertDate(value, label) {
8844
+ if (typeof value !== "string") throw new ValidationError(`${label} must use YYYY-MM-DD`);
8845
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/u.exec(value);
8846
+ if (!match) throw new ValidationError(`${label} must use YYYY-MM-DD`);
8847
+ const year = Number(match[1]);
8848
+ const month = Number(match[2]);
8849
+ const day = Number(match[3]);
8850
+ const date = new Date(Date.UTC(year, month - 1, day));
8851
+ if (year < 1e3 || date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
8852
+ throw new ValidationError(`${label} must be a valid date from year 1000`);
8853
+ }
8854
+ }
8855
+ function assertOptionalString(value, label) {
8856
+ if (typeof value !== "string") throw new ValidationError(`${label} must be a string`);
8857
+ }
8858
+ function assertNullableString(value, label) {
8859
+ if (value !== void 0 && value !== null && typeof value !== "string") {
8860
+ throw new ValidationError(`${label} must be a string or null`);
8861
+ }
8862
+ }
8863
+ function validateMoney(value, label) {
8864
+ if (value !== void 0 && value !== null && (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 999999999999999e-2 || Number(value.toFixed(2)) !== value)) {
8865
+ throw new ValidationError(
8866
+ `${label} must be a finite non-negative amount with at most two decimals or null`
8867
+ );
8868
+ }
8869
+ }
8870
+ function validateNullableInteger(value, label, minimum, maximum) {
8871
+ if (value !== void 0 && value !== null && (!Number.isSafeInteger(value) || value < minimum || value > maximum)) {
8872
+ throw new ValidationError(`${label} must be an integer from ${minimum} to ${maximum}, or null`);
8873
+ }
8874
+ }
8875
+ function validateMetadata(value) {
8876
+ if (value === void 0 || value === null) return;
8877
+ assertRecord(value, "metadata");
8878
+ const entries = Object.entries(value);
8879
+ if (entries.length > 50) throw new ValidationError("metadata must have at most 50 keys");
8880
+ for (const [key, item] of entries) {
8881
+ if (!/^[A-Za-z0-9_.-]{1,40}$/u.test(key)) {
8882
+ throw new ValidationError("metadata keys must use 1-40 letters, digits, _, -, or .");
8883
+ }
8884
+ if (typeof item !== "string" || [...item].length > 500) {
8885
+ throw new ValidationError(`metadata.${key} must be a string of at most 500 characters`);
8886
+ }
8887
+ }
8888
+ }
8889
+ function validateExternalReferences(value) {
8890
+ if (value === void 0 || value === null) return;
8891
+ if (!Array.isArray(value) || value.length > 20) {
8892
+ throw new ValidationError("external_references must be an array of at most 20 entries or null");
8893
+ }
8894
+ for (const reference of value) {
8895
+ assertRecord(reference, "external reference");
8896
+ if (typeof reference["system"] !== "string" || !/^[A-Za-z0-9_.-]{1,64}$/u.test(reference["system"])) {
8897
+ throw new ValidationError("external reference system is invalid");
8898
+ }
8899
+ if (typeof reference["id"] !== "string" || reference["id"].length === 0 || [...reference["id"]].length > 255 || /[\u{10000}-\u{10FFFF}]/u.test(reference["id"])) {
8900
+ throw new ValidationError("external reference id must be 1-255 three-byte characters");
8901
+ }
8902
+ }
8903
+ }
8904
+
8290
8905
  // src/support/webhook-verifier.ts
8291
8906
  import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
8292
8907
  var DEFAULT_TOLERANCE_SECONDS = 300;
@@ -8379,11 +8994,7 @@ var WebhookVerifier = class {
8379
8994
  if (!/^[\da-f]{64}$/i.test(provided)) return false;
8380
8995
  const expected = createHmac("sha256", this.webhookSecret).update(buf).digest();
8381
8996
  const actual = Buffer.from(provided, "hex");
8382
- try {
8383
- return timingSafeEqual2(expected, actual);
8384
- } catch {
8385
- return false;
8386
- }
8997
+ return timingSafeEqual2(expected, actual);
8387
8998
  }
8388
8999
  /**
8389
9000
  * Parse the raw webhook body into a JSON object. Both the rich envelope and
@@ -8478,6 +9089,7 @@ var AssinafyClient = class _AssinafyClient {
8478
9089
  fields;
8479
9090
  signerDocuments;
8480
9091
  users;
9092
+ contracts;
8481
9093
  webhookVerifier;
8482
9094
  /**
8483
9095
  * Create a client. Supply `apiKey` (preferred, sent as `X-Api-Key`) or a
@@ -8595,6 +9207,11 @@ var AssinafyClient = class _AssinafyClient {
8595
9207
  this.publicAxiosInstance
8596
9208
  );
8597
9209
  this.users = new UserResource(this.axiosInstance, void 0, this.logger);
9210
+ this.contracts = new ContractResource(
9211
+ this.axiosInstance,
9212
+ this.defaultAccountId,
9213
+ this.logger
9214
+ );
8598
9215
  this.webhookVerifier = new WebhookVerifier(this.webhookSecret);
8599
9216
  }
8600
9217
  /**
@@ -9020,6 +9637,7 @@ export {
9020
9637
  AssinafyClient,
9021
9638
  AssinafyError,
9022
9639
  AuthenticationResource,
9640
+ ContractResource,
9023
9641
  DEFAULT_WEBHOOK_EVENTS,
9024
9642
  DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD,
9025
9643
  DocumentResource,