@assinafy/sdk 2.9.1 → 2.11.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/CHANGELOG.md CHANGED
@@ -7,6 +7,52 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.11.0] - 2026-11-02
11
+
12
+ ### Added
13
+
14
+ - Template document creation accepts either an existing signer `id` or an
15
+ `email` that reuses or creates the signer, with optional `name` and E.164
16
+ `whatsapp_phone_number`.
17
+ - Template creation and cost estimation support `DigitalCertificate` for
18
+ templates without placed signer fields; templates that produce `collect`
19
+ assignments remain rejected by the API.
20
+ - Webhook endpoint and delivery types expose hold state, attempt identity,
21
+ attempt kind, and whether another retry will follow. Endpoint updates expose
22
+ a newly generated signing secret when they turn signing on.
23
+
24
+ ### Changed
25
+
26
+ - Assignment deadlines accept date-only values, date-times interpreted as UTC
27
+ when no offset is present, and offset-aware date-times.
28
+ - New or changed webhook endpoint URLs require HTTPS. OAuth applications with
29
+ `webhooks:write` can rotate a signing secret, while reading it remains
30
+ API-key-only.
31
+ - Webhook delivery guidance covers the six-attempt retry policy, endpoint hold
32
+ probes, oldest-first recovery, and seven-day history retention.
33
+
34
+ ### Fixed
35
+
36
+ - Signer decline reasons count Unicode characters rather than UTF-16 code
37
+ units, allowing the documented 2,000-character limit for astral characters.
38
+ - Development tooling resolves `minimatch` 11.0.3, which prevents unbounded
39
+ glob-part amplification on attacker-controlled patterns.
40
+
41
+ ## [2.10.0] - 2026-10-29
42
+
43
+ ### Added
44
+
45
+ - `documents.listActivities(documentId, params?)` returns activity entries
46
+ with pagination metadata from the response headers. Use it to read the full
47
+ production history; sandbox responses omit metadata while still unpaged.
48
+
49
+ ### Fixed
50
+
51
+ - `documents.activities(documentId, params?)` accepts `page`, `per-page`
52
+ (or `per_page`), and `sort`, allowing callers to fetch beyond production's
53
+ default 20 activity entries. Existing calls still return an array; sandbox
54
+ responses remain compatible with its unpaged activity log.
55
+
10
56
  ## [2.9.1] - 2026-10-28
11
57
 
12
58
  ### Fixed
@@ -880,7 +926,11 @@ signer fields with `cpf` and `whatsapp_phone_number`.
880
926
  - High-level `uploadAndRequestSignatures` helper on `AssinafyClient`.
881
927
  - `PaginatedResult<T>` with parsed `X-Pagination-*` header meta.
882
928
 
883
- [Unreleased]: https://github.com/assinafy/typescript-sdk/compare/v2.8.1...HEAD
929
+ [Unreleased]: https://github.com/assinafy/typescript-sdk/compare/v2.11.0...HEAD
930
+ [2.11.0]: https://github.com/assinafy/typescript-sdk/compare/v2.10.0...v2.11.0
931
+ [2.10.0]: https://github.com/assinafy/typescript-sdk/compare/v2.9.1...v2.10.0
932
+ [2.9.1]: https://github.com/assinafy/typescript-sdk/compare/v2.9.0...v2.9.1
933
+ [2.9.0]: https://github.com/assinafy/typescript-sdk/compare/v2.8.1...v2.9.0
884
934
  [2.8.1]: https://github.com/assinafy/typescript-sdk/compare/v2.8.0...v2.8.1
885
935
  [2.8.0]: https://github.com/assinafy/typescript-sdk/releases/tag/v2.8.0
886
936
  [2.7.1]: https://github.com/assinafy/typescript-sdk/compare/v2.7.0...v2.7.1
package/README.en.md CHANGED
@@ -347,7 +347,7 @@ ledger is in [docs/API_COVERAGE.md](docs/API_COVERAGE.md).
347
347
 
348
348
  | Resource | Endpoints |
349
349
  | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
350
- | `client.documents` | list, **search**, upload, details, get, **rename**, activities, waitUntilReady, download, thumbnail, downloadPage, statuses, delete, verify, createFromTemplate, estimateCostFromTemplate, getPublic, sendToken, listTags, replaceTags, addTags, detachTag, isFullySigned, getSigningProgress |
350
+ | `client.documents` | list, **search**, upload, details, get, **rename**, activities, listActivities, waitUntilReady, download, thumbnail, downloadPage, statuses, delete, verify, createFromTemplate, estimateCostFromTemplate, getPublic, sendToken, listTags, replaceTags, addTags, detachTag, isFullySigned, getSigningProgress |
351
351
  | `client.signers` | create, get, list, update, delete, findByEmail |
352
352
  | `client.assignments` | list, create, estimateCost, resetExpiration, resendNotification, estimateResendCost, listWhatsAppNotifications, getIdentityVerification, downloadIdentityVerificationImage, reviewIdentityVerification |
353
353
  | `client.contracts` | list, get, set, listRelated, renew, terminate |
@@ -718,7 +718,10 @@ const { data, meta } = await client.documents.list({ page: 1, 'per-page': 20, so
718
718
  const hits = await client.documents.search({ search: 'agreement', status: 'pending_signature', 'per-page': 20 });
719
719
 
720
720
  await client.documents.details(doc.id);
721
- await client.documents.activities(doc.id);
721
+ // Production: page 2 of activities, oldest first; returns an array.
722
+ await client.documents.activities(doc.id, { page: 2, 'per-page': 100, sort: 'id' });
723
+ // Use listActivities for { data, meta }, including total and last_page.
724
+ await client.documents.listActivities(doc.id, { page: 2, 'per-page': 100, sort: 'id' });
722
725
  await client.documents.waitUntilReady(doc.id, { maxWaitMs: 30_000 });
723
726
 
724
727
  // Rename. The API rejects this with 400 while the document is still in
@@ -774,11 +777,22 @@ both are silent rather than errors:
774
777
  - Only the hyphenated `per-page` is read. `per_page` is accepted and ignored,
775
778
  falling back to 20 rows — so the SDK rewrites `per_page` to `per-page` on
776
779
  every list method, and an explicit `per-page` wins when both are given.
777
- - `per-page` is clamped to **50**. Asking for 100 returns 50 rows with a `200`.
778
- The exported `MAX_LIST_PAGE_SIZE` constant is that ceiling; page through with
780
+ - Document and signer lists have been observed to clamp `per-page` to **50**.
781
+ Asking for 100 returns 50 rows with a `200` on those deployments.
782
+ The exported `MAX_LIST_PAGE_SIZE` constant is that observed ceiling; page through with
779
783
  `page` rather than requesting a larger page, and trust `meta.per_page` over
780
784
  the value you asked for.
781
785
 
786
+ `documents.activities(documentId, params?)` keeps its array return type and does
787
+ not expose pagination metadata; use `documents.listActivities()` for `{ data, meta }`.
788
+ In production, these methods return **20 entries per page**
789
+ by default and documents a maximum `per-page` of **100**. Use `page` to fetch later
790
+ entries; an empty array marks the end. `sort: 'id'` returns oldest first, and
791
+ `sort: '-id'` (the default) returns newest first. Sandbox still returns the full,
792
+ unpaged log and may ignore these parameters, so do not loop through pages there.
793
+ Existing integrations that read the entire history in one request must now
794
+ request subsequent pages. See the [migration example](docs/COMPATIBILITY.md#document-activities).
795
+
782
796
  ### Contract lifecycle management (CLM)
783
797
 
784
798
  Contract lifecycle management tracks the business terms attached to an existing
@@ -976,6 +990,7 @@ await client.assignments.estimateCost(documentId, { signers: [{}] }); // default
976
990
 
977
991
  await client.assignments.resetExpiration(documentId, assignmentId, '2027-06-30T00:00:00Z');
978
992
  // The `expires_at` key is required by the contract; send `null` to remove the expiration.
993
+ // Date-only values end at 23:59 UTC; date-times without an offset are UTC.
979
994
  await client.assignments.resetExpiration(documentId, assignmentId, null);
980
995
 
981
996
  await client.assignments.resendNotification(documentId, assignmentId, signerId);
@@ -1147,11 +1162,19 @@ const signerRole = configured.roles?.find(
1147
1162
  && role.assignment_type.toLowerCase() !== 'editor',
1148
1163
  );
1149
1164
  if (!signerRole) throw new Error('Template has no signer role');
1150
- await client.documents.createFromTemplate(
1165
+ const generated = await client.documents.createFromTemplate(
1151
1166
  templateId,
1152
- [{ role_id: signerRole.id, id: signerId, verification_method: 'Email', notification_methods: ['Email'] }],
1153
- { name: 'NDA - John Doe', message: 'Please sign at your earliest convenience.' },
1167
+ [{
1168
+ role_id: signerRole.id,
1169
+ email: 'signer@example.com',
1170
+ name: 'Example Signer',
1171
+ verification_method: 'Email',
1172
+ notification_methods: ['Email'],
1173
+ }],
1174
+ { name: 'NDA - Example', message: 'Please sign at your earliest convenience.' },
1154
1175
  );
1176
+ // The response starts at status: 'uploaded' with assignment: null. Follow
1177
+ // documents.get(generated.id) or webhooks for pending_signature / failed.
1155
1178
 
1156
1179
  // Estimate the cost before creating → ICostEstimate
1157
1180
  await client.documents.estimateCostFromTemplate(templateId, [
@@ -1161,12 +1184,14 @@ await client.documents.estimateCostFromTemplate(templateId, [
1161
1184
  // has_sufficient_resources: true, blocking_reason: null, breakdown: [], … }
1162
1185
  ```
1163
1186
 
1164
- The server derives a template assignment's method from its placed fields, and
1165
- currently accepts certificate signers even when that produces an unusable
1166
- `collect` assignment. Until the API enforces the virtual-only rule atomically,
1167
- the SDK rejects `DigitalCertificate` in both `createFromTemplate()` and
1168
- `estimateCostFromTemplate()` with the same stable validation code. Create a
1169
- direct `virtual` assignment for certificate signers instead.
1187
+ Each template signer uses an existing `id` or an `email`; `id` wins when both
1188
+ are sent. An email reuses the matching account signer or creates one with the
1189
+ supplied `name` and optional E.164 `whatsapp_phone_number`.
1190
+
1191
+ The server derives the assignment method from the template. A template without
1192
+ placed signer fields supports `DigitalCertificate`; a template with placed
1193
+ fields returns `400` because it produces a `collect` assignment. The same rule
1194
+ is applied by `estimateCostFromTemplate()`.
1170
1195
 
1171
1196
  Template creation only uploads the PDF and provisions the default editor role —
1172
1197
  configure roles/fields in the Assinafy editor (or the web UI) afterwards.
@@ -1352,7 +1377,8 @@ An account has 1 webhook endpoint, or up to 3 on paid plans. Every active
1352
1377
  endpoint subscribed to an event receives it independently. OAuth tokens need
1353
1378
  `account:read` to read endpoints and `webhooks:write` to change them; the
1354
1379
  creation response includes `secret` when signing is enabled. Store it then,
1355
- including for OAuth integrations; reading or rotating it later requires an API key.
1380
+ including for OAuth integrations. Reading it later requires an API key; OAuth
1381
+ apps with `webhooks:write` can rotate a lost secret.
1356
1382
 
1357
1383
  ```ts
1358
1384
  const endpoint = await client.webhooks.createEndpoint({
@@ -1362,7 +1388,8 @@ const endpoint = await client.webhooks.createEndpoint({
1362
1388
  events: ['document_ready', 'signer_signed_document', 'signer_rejected_document'],
1363
1389
  signing_enabled: true, // sign deliveries with Standard Webhooks
1364
1390
  });
1365
- // → { id, name, url, email, events, is_active, signing_enabled, created_at, updated_at }
1391
+ // → { id, name, url, email, events, is_active, is_held, held_since,
1392
+ // signing_enabled, secret, created_at, updated_at }
1366
1393
 
1367
1394
  const secret = endpoint.secret; // 'whsec_…'; store securely at creation
1368
1395
  await client.webhooks.listEndpoints(); // IWebhookEndpoint[]
@@ -1384,14 +1411,15 @@ const history = await client.webhooks.listDispatches({
1384
1411
  const retried = await client.webhooks.retryDispatch(dispatchId); // IWebhookDispatch
1385
1412
  ```
1386
1413
 
1387
- `createEndpoint()` returns `403` once the plan's limit is reached and `400`
1414
+ New or changed webhook URLs must use HTTPS. `createEndpoint()` returns `403`
1415
+ once the plan's limit is reached and `400`
1388
1416
  when another endpoint of the workspace already uses the same `url`. When
1389
1417
  `events` is omitted or empty, the SDK sends the exported
1390
1418
  `DEFAULT_WEBHOOK_EVENTS`: `document_ready`, `document_prepared`,
1391
1419
  `signer_signed_document`, `signer_rejected_document`, and
1392
1420
  `document_processing_failed`. In
1393
1421
  `updateEndpoint()`, `signing_enabled: true` generates a secret if there is none
1394
- and `false` discards it.
1422
+ and returns that new secret once; `false` discards it.
1395
1423
 
1396
1424
  The earlier routes remain and act on the account's oldest endpoint:
1397
1425
  `register()` (create or update), `get()` (`IWebhookSubscription | null`) and
@@ -1401,11 +1429,13 @@ Assinafy delivers each event as an HTTP `POST` with
1401
1429
  `Content-Type: application/json`, `Connection: close` and the headers
1402
1430
  `webhook-id` (identical on every attempt of the same event to the same
1403
1431
  endpoint — deduplicate on it), `webhook-timestamp` and, with signing on,
1404
- `webhook-signature`. Any `2xx` is success. There are at most two attempts,
1405
- three seconds apart. After ten consecutive failed events, ordinary delivery
1406
- pauses and about 5% of later events are attempted until one succeeds; use
1407
- `retryDispatch()` for an immediate redelivery. The dispatch history retains only
1408
- the first 2,000 characters of the receiver's response body.
1432
+ `webhook-signature`. Any `2xx` is success. Connection errors, timeouts, `408`,
1433
+ `429`, and `5xx` responses receive up to six attempts about ten minutes apart;
1434
+ other statuses are final. After ten failed deliveries in a row, `is_held`
1435
+ becomes true and the oldest missed event is probed after 3, 15, and 60 minutes,
1436
+ then every six hours. Success resumes delivery and replays missed events oldest
1437
+ first. `retryDispatch()` sends once immediately, even while held. Dispatch
1438
+ history keeps the first 2,000 response characters for seven days.
1409
1439
 
1410
1440
  Each history or retry result is an `IWebhookDispatch`:
1411
1441
 
@@ -1419,6 +1449,10 @@ type WebhookDispatchShape = {
1419
1449
  endpoint: string | null;
1420
1450
  payload: IWebhookPayload | Record<string, unknown> | null;
1421
1451
  delivered: boolean;
1452
+ webhook_id?: string | null;
1453
+ attempt?: number | null;
1454
+ kind?: 'scheduled' | 'probe' | 'manual' | string;
1455
+ will_retry?: boolean;
1422
1456
  http_status: number | null;
1423
1457
  response_body: string | null;
1424
1458
  error: string | null;
@@ -1431,7 +1465,7 @@ Every delivery body uses this envelope:
1431
1465
 
1432
1466
  ```ts
1433
1467
  type WebhookPayloadShape = {
1434
- id: number; // use for idempotent processing
1468
+ id: number; // internal activity ID; deduplicate on webhook-id
1435
1469
  event: string;
1436
1470
  message: string | null;
1437
1471
  payload: Record<string, unknown> | null;
package/README.md CHANGED
@@ -332,7 +332,7 @@ As 118 operações documentadas em https://api.assinafy.com.br/v1/docs estão co
332
332
 
333
333
  | Recurso | Endpoints |
334
334
  | --- | --- |
335
- | `client.documents` | list, search, upload, details, get, rename, activities, waitUntilReady, download, thumbnail, downloadPage, statuses, delete, verify, createFromTemplate, estimateCostFromTemplate, getPublic, sendToken, listTags, replaceTags, addTags, detachTag, isFullySigned, getSigningProgress |
335
+ | `client.documents` | list, search, upload, details, get, rename, activities, listActivities, waitUntilReady, download, thumbnail, downloadPage, statuses, delete, verify, createFromTemplate, estimateCostFromTemplate, getPublic, sendToken, listTags, replaceTags, addTags, detachTag, isFullySigned, getSigningProgress |
336
336
  | `client.signers` | create, get, list, update, delete, findByEmail |
337
337
  | `client.assignments` | list, create, estimateCost, resetExpiration, resendNotification, estimateResendCost, listWhatsAppNotifications, getIdentityVerification, downloadIdentityVerificationImage, reviewIdentityVerification |
338
338
  | `client.contracts` | list, get, set, listRelated, renew, terminate |
@@ -687,7 +687,10 @@ const { data, meta } = await client.documents.list({ page: 1, 'per-page': 20, so
687
687
  const achados = await client.documents.search({ search: 'contrato', status: 'pending_signature', 'per-page': 20 });
688
688
 
689
689
  await client.documents.details(doc.id);
690
- await client.documents.activities(doc.id);
690
+ // Produção: página 2 de atividades, mais antigas primeiro; retorna um array.
691
+ await client.documents.activities(doc.id, { page: 2, 'per-page': 100, sort: 'id' });
692
+ // Use listActivities para { data, meta }, incluindo total e last_page.
693
+ await client.documents.listActivities(doc.id, { page: 2, 'per-page': 100, sort: 'id' });
691
694
  await client.documents.waitUntilReady(doc.id, { maxWaitMs: 30_000 });
692
695
 
693
696
  // Renomear. A API responde 400 enquanto o documento está em
@@ -740,10 +743,21 @@ As listagens devolvem `{ data, meta }`, com `meta` preenchido a partir dos heade
740
743
  - Só o `per-page` com hífen é lido. `per_page` é aceito e ignorado, caindo para 20 linhas — por isso
741
744
  o SDK reescreve `per_page` como `per-page` em toda listagem, e um `per-page` explícito vence
742
745
  quando os dois são enviados.
743
- - `per-page` é limitado a **50**. Pedir 100 devolve 50 linhas com `200`. A constante exportada
744
- `MAX_LIST_PAGE_SIZE` é esse teto; pagine com `page` em vez de pedir páginas maiores, e confie no
746
+ - Nas listagens de documentos e signatários, observou-se um limite de **50** para `per-page`.
747
+ Nesses ambientes, pedir 100 devolve 50 linhas com `200`. A constante exportada
748
+ `MAX_LIST_PAGE_SIZE` é esse teto observado; pagine com `page` em vez de pedir páginas maiores, e confie no
745
749
  `meta.per_page` mais do que no valor pedido.
746
750
 
751
+ `documents.activities(documentId, params?)` mantém o retorno como array; use
752
+ `documents.listActivities()` para obter `{ data, meta }` com os metadados de paginação.
753
+ Em produção, esses métodos retornam **20 entradas por página** por padrão, com
754
+ máximo documentado de **100** para `per-page`. Use `page` para buscar as próximas entradas;
755
+ um array vazio indica o fim. `sort: 'id'` retorna as mais antigas primeiro, e `sort: '-id'`
756
+ (padrão), as mais recentes. O sandbox ainda retorna o histórico completo, sem paginação,
757
+ e pode ignorar esses parâmetros; por isso, não percorra páginas em loop nesse ambiente.
758
+ Integrações que liam o histórico completo em uma requisição precisam agora buscar
759
+ as páginas seguintes. Veja o [exemplo de migração](docs/COMPATIBILITY.md#document-activities).
760
+
747
761
  ### Gestão do ciclo de vida de contratos (CLM)
748
762
 
749
763
  A gestão do ciclo de vida de contratos (CLM) acompanha os termos comerciais ligados a um documento
@@ -932,6 +946,7 @@ await client.assignments.estimateCost(documentId, { signers: [{}] }); // Email p
932
946
 
933
947
  await client.assignments.resetExpiration(documentId, assignmentId, '2027-06-30T00:00:00Z');
934
948
  // A chave `expires_at` é exigida pelo contrato; envie `null` para remover a expiração.
949
+ // Valores só com data terminam às 23:59 UTC; data/hora sem offset é UTC.
935
950
  await client.assignments.resetExpiration(documentId, assignmentId, null);
936
951
 
937
952
  await client.assignments.resendNotification(documentId, assignmentId, signerId);
@@ -1110,11 +1125,19 @@ const papelSignatario = configurado.roles?.find(
1110
1125
  && papel.assignment_type.toLowerCase() !== 'editor',
1111
1126
  );
1112
1127
  if (!papelSignatario) throw new Error('O template não tem papel de signatário');
1113
- await client.documents.createFromTemplate(
1128
+ const gerado = await client.documents.createFromTemplate(
1114
1129
  templateId,
1115
- [{ role_id: papelSignatario.id, id: signerId, verification_method: 'Email', notification_methods: ['Email'] }],
1116
- { name: 'NDA - João Silva', message: 'Por favor, assine assim que puder.' },
1130
+ [{
1131
+ role_id: papelSignatario.id,
1132
+ email: 'signatario@exemplo.com.br',
1133
+ name: 'Signatário Exemplo',
1134
+ verification_method: 'Email',
1135
+ notification_methods: ['Email'],
1136
+ }],
1137
+ { name: 'NDA - Exemplo', message: 'Por favor, assine assim que puder.' },
1117
1138
  );
1139
+ // A resposta começa com status: 'uploaded' e assignment: null. Acompanhe
1140
+ // documents.get(gerado.id) ou os webhooks até pending_signature / failed.
1118
1141
 
1119
1142
  // Estime o custo antes de criar → ICostEstimate
1120
1143
  await client.documents.estimateCostFromTemplate(templateId, [
@@ -1124,11 +1147,13 @@ await client.documents.estimateCostFromTemplate(templateId, [
1124
1147
  // has_sufficient_resources: true, blocking_reason: null, breakdown: [], … }
1125
1148
  ```
1126
1149
 
1127
- O servidor deduz o método do assignment de template a partir dos campos posicionados e hoje aceita
1128
- signatários por certificado mesmo quando isso cria um assignment `collect` impossível de concluir.
1129
- Até a API impor atomicamente a regra de método virtual, o SDK rejeita `DigitalCertificate` tanto em
1130
- `createFromTemplate()` quanto em `estimateCostFromTemplate()`, com o mesmo código estável. Para
1131
- certificados, crie diretamente um assignment `virtual`.
1150
+ Cada signatário do template usa um `id` existente ou um `email`; `id` prevalece quando ambos são
1151
+ enviados. O email reutiliza o signatário correspondente da conta ou cria um com `name` e o
1152
+ `whatsapp_phone_number` E.164 opcional.
1153
+
1154
+ O servidor deduz o método do assignment a partir do template. Um template sem campos posicionados
1155
+ para o signatário aceita `DigitalCertificate`; com campos posicionados, a API devolve `400` porque
1156
+ o assignment seria `collect`. `estimateCostFromTemplate()` aplica a mesma regra.
1132
1157
 
1133
1158
  Criar um template apenas envia o PDF e provisiona o papel de editor padrão — configure papéis e
1134
1159
  campos no editor da Assinafy depois. Os `download_url` dos objetos de página do template são URLs
@@ -1317,7 +1342,8 @@ Trocar um autenticador já confirmado exige também `password` ou `reauth_code`
1317
1342
  Uma conta tem 1 endpoint de webhook, ou até 3 nos planos pagos. Cada endpoint ativo inscrito em um
1318
1343
  evento o recebe, de forma independente. Tokens OAuth exigem `account:read` para ler endpoints e
1319
1344
  `webhooks:write` para alterá-los. Com assinatura ativa, a criação devolve `secret`: guarde-o também
1320
- nas integrações OAuth. Ler ou rotacionar esse segredo depois exige chave de API.
1345
+ nas integrações OAuth. Ler o segredo depois exige chave de API; uma aplicação OAuth com
1346
+ `webhooks:write` pode rotacionar um segredo perdido.
1321
1347
 
1322
1348
  ```ts
1323
1349
  const endpoint = await client.webhooks.createEndpoint({
@@ -1327,7 +1353,8 @@ const endpoint = await client.webhooks.createEndpoint({
1327
1353
  events: ['document_ready', 'signer_signed_document', 'signer_rejected_document'],
1328
1354
  signing_enabled: true, // assina as entregas no padrão Standard Webhooks
1329
1355
  });
1330
- // → { id, name, url, email, events, is_active, signing_enabled, created_at, updated_at }
1356
+ // → { id, name, url, email, events, is_active, is_held, held_since,
1357
+ // signing_enabled, secret, created_at, updated_at }
1331
1358
 
1332
1359
  const secret = endpoint.secret; // 'whsec_…'; guarde em armazenamento seguro na criação
1333
1360
  await client.webhooks.listEndpoints(); // IWebhookEndpoint[]
@@ -1349,11 +1376,13 @@ const historico = await client.webhooks.listDispatches({
1349
1376
  const reenviado = await client.webhooks.retryDispatch(dispatchId); // IWebhookDispatch
1350
1377
  ```
1351
1378
 
1352
- `createEndpoint()` devolve `403` quando o limite do plano foi atingido e `400` quando outro endpoint
1379
+ URLs novas ou alteradas de webhook devem usar HTTPS. `createEndpoint()` devolve `403` quando o
1380
+ limite do plano foi atingido e `400` quando outro endpoint
1353
1381
  do workspace já usa a mesma `url`. Quando `events` é omitido ou vazio, o SDK envia
1354
1382
  `DEFAULT_WEBHOOK_EVENTS` (exportado): `document_ready`, `document_prepared`,
1355
- `signer_signed_document`, `signer_rejected_document` e `document_processing_failed`. Em `updateEndpoint()`, `signing_enabled: true` gera um segredo se
1356
- ainda não houver e `false` o descarta.
1383
+ `signer_signed_document`, `signer_rejected_document` e `document_processing_failed`. Em
1384
+ `updateEndpoint()`, `signing_enabled: true` gera um segredo se ainda não houver e devolve esse novo
1385
+ segredo uma vez; `false` o descarta.
1357
1386
 
1358
1387
  As rotas anteriores continuam disponíveis e operam sobre o endpoint mais antigo da conta:
1359
1388
  `register()` (cria ou atualiza), `get()` (`IWebhookSubscription | null`) e `inactivate()`.
@@ -1361,10 +1390,12 @@ As rotas anteriores continuam disponíveis e operam sobre o endpoint mais antigo
1361
1390
  A Assinafy entrega cada evento como um `POST` HTTP com `Content-Type: application/json`,
1362
1391
  `Connection: close` e os headers `webhook-id` (igual em todas as tentativas do mesmo evento para o
1363
1392
  mesmo endpoint — use-o para deduplicar), `webhook-timestamp` e, com assinatura ativa,
1364
- `webhook-signature`. Qualquer `2xx` é sucesso. São no máximo duas tentativas, com três segundos de
1365
- intervalo. Depois de dez eventos falhos consecutivos, a entrega comum é pausada e cerca de 5% dos
1366
- eventos seguintes são tentados até um dar certo; use `retryDispatch()` para reenviar na hora. O
1367
- histórico guarda apenas os primeiros 2.000 caracteres do corpo de resposta do receptor.
1393
+ `webhook-signature`. Qualquer `2xx` é sucesso. Erros de conexão, timeouts, `408`, `429` e `5xx`
1394
+ recebem até seis tentativas, separadas por cerca de dez minutos; outros status são finais. Depois
1395
+ de dez entregas falhas seguidas, `is_held` fica verdadeiro e o evento perdido mais antigo é testado
1396
+ após 3, 15 e 60 minutos, e depois a cada seis horas. O sucesso retoma as entregas e envia os eventos
1397
+ perdidos do mais antigo para o mais novo. `retryDispatch()` envia uma vez imediatamente, mesmo
1398
+ durante a pausa. O histórico guarda os primeiros 2.000 caracteres da resposta por sete dias.
1368
1399
 
1369
1400
  Cada item do histórico (ou resultado de reenvio) é um `IWebhookDispatch`:
1370
1401
 
@@ -1378,6 +1409,10 @@ type WebhookDispatchShape = {
1378
1409
  endpoint: string | null;
1379
1410
  payload: IWebhookPayload | Record<string, unknown> | null;
1380
1411
  delivered: boolean;
1412
+ webhook_id?: string | null;
1413
+ attempt?: number | null;
1414
+ kind?: 'scheduled' | 'probe' | 'manual' | string;
1415
+ will_retry?: boolean;
1381
1416
  http_status: number | null;
1382
1417
  response_body: string | null;
1383
1418
  error: string | null;
@@ -1390,7 +1425,7 @@ Todo corpo de entrega usa este envelope:
1390
1425
 
1391
1426
  ```ts
1392
1427
  type WebhookPayloadShape = {
1393
- id: number; // use para processamento idempotente
1428
+ id: number; // atividade interna; deduplique pelo webhook-id
1394
1429
  event: string;
1395
1430
  message: string | null;
1396
1431
  payload: Record<string, unknown> | null;