@assinafy/sdk 2.7.0 → 2.7.1

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.d.ts CHANGED
@@ -868,6 +868,8 @@ interface IUpdateTemplatePayload {
868
868
  }
869
869
  /** Template list item (paginated). */
870
870
  interface ITemplateListItem {
871
+ /** Always `template`. */
872
+ resource?: string;
871
873
  id: string;
872
874
  name: string;
873
875
  document_name?: string | null;
@@ -1024,8 +1026,33 @@ interface IDocumentVerification {
1024
1026
  is_valid: boolean;
1025
1027
  message: string;
1026
1028
  }
1027
- /** Channel accepted by the `send-token` endpoint. */
1028
- type SendTokenChannel = 'email' | 'whatsapp' | AnyString;
1029
+ /** Channel accepted by the `send-token` endpoint; the contract allows only `email`. */
1030
+ type SendTokenChannel = 'email';
1031
+ /**
1032
+ * `data` returned by `PUT /public/documents/{documentId}/send-token`.
1033
+ *
1034
+ * ```jsonc
1035
+ * {
1036
+ * "document": { "resource": "document", "id": "a1b2…", "name": "Contract.pdf", "page_count": 3, "created_by": "Jane Doe" },
1037
+ * "channel": "email",
1038
+ * "recipient": "signer@example.com"
1039
+ * }
1040
+ * ```
1041
+ */
1042
+ interface ISendTokenResult {
1043
+ /** Summary of the document the token unlocks. */
1044
+ document: {
1045
+ resource: string;
1046
+ id: string;
1047
+ name: string;
1048
+ page_count: number;
1049
+ created_by: string;
1050
+ };
1051
+ /** Channel the token was sent through. */
1052
+ channel: string;
1053
+ /** Address the token was sent to. */
1054
+ recipient: string;
1055
+ }
1029
1056
  /** Authenticated user profile returned by login and `users.getCurrent()`. */
1030
1057
  interface IAuthenticatedUser {
1031
1058
  id: string;
@@ -1365,6 +1392,12 @@ interface IOAuthTokenResponse {
1365
1392
  scope?: string;
1366
1393
  /** Signed OIDC identity token (RS256). Present only when `openid` was granted. */
1367
1394
  id_token?: string | null;
1395
+ /**
1396
+ * RFC 8693 token type. Returned only by the token-exchange grant, which is
1397
+ * reserved for Assinafy's own services; absent from the two grants the SDK
1398
+ * sends.
1399
+ */
1400
+ issued_token_type?: string;
1368
1401
  }
1369
1402
  /** OpenID Connect claims returned by `GET /oauth/userinfo`. */
1370
1403
  interface IOAuthUserInfo {
@@ -2274,55 +2307,48 @@ declare class DocumentResource extends BaseResource {
2274
2307
  */
2275
2308
  getPublic(documentId: string): Promise<IPublicDocumentInfo>;
2276
2309
  /**
2277
- * Send the signer's access token to their email
2310
+ * Email the signer the verification token that unlocks a document
2278
2311
  * (`PUT /public/documents/{documentId}/send-token`).
2279
2312
  *
2280
2313
  * Part of the public signing flow: dispatches the 6-digit verification
2281
- * token the signer enters to view the document. The documented request body
2282
- * is `{ recipient, channel }` with `channel` set to `email`. This
2283
- * two-argument form sends the legacy `{ email }` shape, which current
2284
- * deployments still accept, and retries the documented shape only when the
2285
- * server explicitly reports that `channel`/`recipient` is required. Use the
2286
- * three-argument overload to send the documented shape directly.
2314
+ * token the signer enters to view the document. Runs on the
2315
+ * credential-free transport. The contract accepts only the `email`
2316
+ * channel, and both body fields are required.
2287
2317
  *
2288
2318
  * Request body (`application/json`):
2289
2319
  * ```jsonc
2290
- * { "email": "signer@example.com" }
2291
- * ```
2292
- * Documented body, sent on the explicit-channel overload or on retry:
2293
- * ```jsonc
2294
- * { "recipient": "signer@example.com", "channel": "email" }
2320
+ * { "channel": "email", "recipient": "signer@example.com" }
2295
2321
  * ```
2296
2322
  *
2297
2323
  * @param documentId - The document to send the token for.
2298
- * @param email - The signer's email address.
2299
- * @returns Nothing after the API's empty acknowledgement.
2300
- * @throws {ValidationError} If `documentId` is missing or `email` is not a
2301
- * valid email address.
2302
- * @throws {ApiError} If the API rejects the request.
2303
- *
2304
- * @example
2305
- * ```ts
2306
- * await client.documents.sendToken('doc-1', 'signer@example.com');
2324
+ * @param recipient - The signer's email address.
2325
+ * @param channel - Delivery channel; only `email` is accepted (default).
2326
+ * @returns The delivery confirmation (`data` of the envelope):
2327
+ * ```jsonc
2328
+ * {
2329
+ * "document": {
2330
+ * "resource": "document",
2331
+ * "id": "a1b2c3d4e5f6a7b8c9d0",
2332
+ * "name": "Contract.pdf",
2333
+ * "page_count": 3,
2334
+ * "created_by": "Jane Doe"
2335
+ * },
2336
+ * "channel": "email",
2337
+ * "recipient": "signer@example.com"
2338
+ * }
2307
2339
  * ```
2308
- */
2309
- sendToken(documentId: string, email: string): Promise<void>;
2310
- /**
2311
- * Send a signing token through an explicit channel
2312
- * (`PUT /public/documents/{documentId}/send-token`).
2313
- * Sends JSON `{ "recipient": "+5511999998888", "channel": "whatsapp" }`.
2314
- * @param documentId - Document identifier.
2315
- * @param recipient - Controlled email address or WhatsApp number.
2316
- * @param channel - Delivery channel, `email` or `whatsapp`.
2317
- * @returns Nothing; the acknowledgement body is discarded.
2318
- * @throws {ValidationError} If an argument is empty.
2319
- * @throws {ApiError} If delivery is rejected.
2340
+ * @throws {ValidationError} If `documentId` is missing, `recipient` is not
2341
+ * a valid email address, or `channel` is not `email`.
2342
+ * @throws {ApiError} `400` if validation fails; `404` if the document does
2343
+ * not exist.
2344
+ *
2320
2345
  * @example
2321
2346
  * ```ts
2322
- * await client.documents.sendToken('doc-1', 'signer@example.com', 'email');
2347
+ * const sent = await client.documents.sendToken('doc-1', 'signer@example.com');
2348
+ * console.log(sent.recipient);
2323
2349
  * ```
2324
2350
  */
2325
- sendToken(documentId: string, recipient: string, channel: SendTokenChannel): Promise<void>;
2351
+ sendToken(documentId: string, recipient: string, channel?: SendTokenChannel): Promise<ISendTokenResult>;
2326
2352
  /**
2327
2353
  * Quick boolean check (`GET /documents/{documentId}`): has every signer
2328
2354
  * completed their assignment?
@@ -5674,6 +5700,12 @@ declare class FieldsResource extends BaseResource {
5674
5700
  */
5675
5701
  declare class SignerDocumentsResource extends BaseResource {
5676
5702
  constructor(http: AxiosInstance, defaultAccountId?: string, logger?: Logger, publicHttp?: AxiosInstance);
5703
+ /**
5704
+ * Credentialed transport used only by the explicit `*AsWorkspace` methods.
5705
+ * Every access-code method stays on the credential-free `http`, so a
5706
+ * signer code and the API key or bearer token never share a request.
5707
+ */
5708
+ private readonly workspaceHttp;
5677
5709
  /**
5678
5710
  * Fetch the document currently awaiting a given signer
5679
5711
  * (`GET /signers/{signer_id}/document?signer-access-code=…`).
@@ -5816,6 +5848,54 @@ declare class SignerDocumentsResource extends BaseResource {
5816
5848
  * ```
5817
5849
  */
5818
5850
  search(signerId: string, signerAccessCode: string, search?: string): Promise<IDocumentListResponse>;
5851
+ /**
5852
+ * List a signer's documents with the workspace credentials
5853
+ * (`GET /signers/{signer_id}/documents`).
5854
+ *
5855
+ * The same operation as {@link SignerDocumentsResource.list}, authorised by
5856
+ * the client's API key or OAuth bearer token instead of a signer access
5857
+ * code. No `signer-access-code` is sent.
5858
+ *
5859
+ * @param signerId - The signer whose documents are listed.
5860
+ * @param params - Pagination: `page`, `per-page` (also accepts `per_page`).
5861
+ * @returns Documents in the compact {@link IDocumentListItem} shape, with
5862
+ * pagination in `meta` (same shape as {@link SignerDocumentsResource.list}):
5863
+ * ```jsonc
5864
+ * {
5865
+ * "data": [{ "id": "103acccd24234c07858ffddf6d84", "name": "Service agreement.pdf", "status": "pending_signature" }],
5866
+ * "meta": { "current_page": 1, "per_page": 20, "total": 1, "last_page": 1 }
5867
+ * }
5868
+ * ```
5869
+ * @throws {ValidationError} If `signerId` is missing.
5870
+ * @throws {ApiError} `401` if the workspace credentials are rejected.
5871
+ *
5872
+ * @example
5873
+ * ```ts
5874
+ * const { data } = await client.signerDocuments.listAsWorkspace(signerId, { page: 1 });
5875
+ * ```
5876
+ */
5877
+ listAsWorkspace(signerId: string, params?: IListParams): Promise<IDocumentListResponse>;
5878
+ /**
5879
+ * Search a signer's documents with the workspace credentials
5880
+ * (`GET /signers/{signer_id}/documents/search`).
5881
+ *
5882
+ * The same operation as {@link SignerDocumentsResource.search}, authorised
5883
+ * by the client's API key or OAuth bearer token instead of a signer access
5884
+ * code. No `signer-access-code` is sent.
5885
+ *
5886
+ * @param signerId - The signer whose documents are searched.
5887
+ * @param search - Free-text term matched against the document name.
5888
+ * @returns Matching documents with pagination in `meta`, as
5889
+ * {@link SignerDocumentsResource.listAsWorkspace} returns.
5890
+ * @throws {ValidationError} If `signerId` is missing or `search` is not a string.
5891
+ * @throws {ApiError} `401` if the workspace credentials are rejected.
5892
+ *
5893
+ * @example
5894
+ * ```ts
5895
+ * const { data } = await client.signerDocuments.searchAsWorkspace(signerId, 'agreement');
5896
+ * ```
5897
+ */
5898
+ searchAsWorkspace(signerId: string, search?: string): Promise<IDocumentListResponse>;
5819
5899
  /**
5820
5900
  * Download one of a signer's document artifacts as raw bytes
5821
5901
  * (`GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`).
@@ -7064,6 +7144,23 @@ interface IAuthenticateChallenge {
7064
7144
  * ```
7065
7145
  */
7066
7146
  declare function parseWwwAuthenticate(value: string | undefined): IAuthenticateChallenge | undefined;
7147
+ /**
7148
+ * Rate-limit state reported by the API's response headers.
7149
+ *
7150
+ * Every rate-limited response carries the `X-Rate-Limit-*` trio; a `429 Too
7151
+ * Many Requests` adds `Retry-After`. Absent or non-numeric headers are left
7152
+ * out rather than guessed.
7153
+ */
7154
+ interface IRateLimitInfo {
7155
+ /** `X-Rate-Limit-Limit` — requests allowed in the current window. */
7156
+ limit?: number;
7157
+ /** `X-Rate-Limit-Remaining` — requests left in the current window. */
7158
+ remaining?: number;
7159
+ /** `X-Rate-Limit-Reset` — seconds until the window resets. */
7160
+ reset?: number;
7161
+ /** `Retry-After` — seconds to wait before retrying (sent on `429`). */
7162
+ retryAfter?: number;
7163
+ }
7067
7164
 
7068
7165
  /** Base class for all Assinafy SDK errors. */
7069
7166
  declare class AssinafyError extends Error {
@@ -7109,6 +7206,25 @@ declare class ApiError extends AssinafyError {
7109
7206
  * ```
7110
7207
  */
7111
7208
  challenge?: IAuthenticateChallenge;
7209
+ /**
7210
+ * Rate-limit headers carried by the failed response: `X-Rate-Limit-Limit`,
7211
+ * `X-Rate-Limit-Remaining`, `X-Rate-Limit-Reset` and, on `429`,
7212
+ * `Retry-After` (all in requests or seconds). `undefined` when the response
7213
+ * carried none of them. The client already retries a `429` up to
7214
+ * `maxRetries` times; this is what remains once those retries are spent.
7215
+ *
7216
+ * @example
7217
+ * ```ts
7218
+ * try {
7219
+ * await client.documents.list();
7220
+ * } catch (error) {
7221
+ * if (error instanceof ApiError && error.statusCode === 429) {
7222
+ * await sleep((error.rateLimit?.retryAfter ?? 60) * 1000);
7223
+ * }
7224
+ * }
7225
+ * ```
7226
+ */
7227
+ rateLimit?: IRateLimitInfo;
7112
7228
  /**
7113
7229
  * Create an error representing a non-success API response.
7114
7230
  *
@@ -7247,4 +7363,4 @@ declare const MAX_LIST_PAGE_SIZE = 50;
7247
7363
 
7248
7364
  declare const SDK_USER_AGENT: string;
7249
7365
 
7250
- export { type AccountLogoUploadSource, type AnyString, ApiError, type AssignmentDisplaySettings, type AssignmentMethod, type AssignmentNotificationMethod, AssignmentResource, type AssignmentVerificationMethod, AssinafyClient, type AssinafyClientOptions, AssinafyError, AuthenticationResource, type ClientConfigInput, DEFAULT_WEBHOOK_EVENTS, type DocumentArtifactName, DocumentResource, type DocumentStatsGranularity, type DocumentStatus, type DocumentUploadSource, FieldsResource, type IAccountTheme, type IApiKeyResponse, type IAssignment, type IAssignmentCostSigner, type IAssignmentEntry, type IAssignmentItem, type IAssignmentListParams, type IAssignmentListResponse, type IAssignmentSigner, type IAuthenticateChallenge, type IAuthenticatedUser, type IConfirmSignerDataPayload, type IConfirmTotpPayload, type ICostEstimate, type ICreateAssignmentPayload, type ICreateAssignmentResponse, type ICreateDocumentFromTemplateOptions, type ICreateFieldPayload, type ICreateSignerPayload, type ICreateSignerResponse, type ICreateTagPayload, type ICreateWorkspacePayload, type IDeleteTagResponse, type IDetachDocumentTagResponse, type IDisplaySettings, type IDocumentActivity, type IDocumentDetailsResponse, type IDocumentListItem, type IDocumentListParams, type IDocumentListResponse, type IDocumentSearchParams, type IDocumentStatsParams, type IDocumentStatsRow, type IDocumentStatusInfo, type IDocumentUploadOptions, type IDocumentUploadResponse, type IDocumentVerification, type IEstimateAssignmentCostPayload, type IFieldDefinition, type IFieldType, type IFieldValidateMultipleEntry, type IFieldValidationMultipleResult, type IFieldValidationResponse, type IFieldValidationResult, type IInlineTag, type ILegacyConfirmSignerDataPayload, type ILegacyResendCostEstimate, type ILegacyUploadSignatureOptions, type IListParams, type ILoginResponse, type IMaskedApiKeyResponse, type IMfaMethod, type IMfaReauth, type IMfaRecoveryCodes, type IMfaStatus, type INotificationHistoryEntry, type INotificationPreferences, type IOAuthAuthorizationCallback, type IOAuthAuthorizationRequest, type IOAuthAuthorizationServerMetadata, type IOAuthProtectedResourceMetadata, type IOAuthTokenResponse, type IOAuthUserInfo, type IPage, type IPaginatedResponse, type IPublicDocumentInfo, type IRenameDocumentResponse, type IResendCostEstimate, type IResendEmailResponse, type ISignFieldEntry, type ISigner, type ISignerListParams, type ISignerListResponse, type ISignerSelf, type ISigningProgress, type ITag, type ITemplateCostSigner, type ITemplateDetailsResponse, type ITemplateFieldPlacement, type ITemplateListItem, type ITemplateListParams, type ITemplateListResponse, type ITemplateRole, type ITemplateSigner, type ITotpEnrollment, type IUpdateFieldPayload, type IUpdateNotificationPreferences, type IUpdateSignerPayload, type IUpdateTagPayload, type IUpdateTemplatePayload, type IUpdateWorkspacePayload, type IUploadAndRequestSignaturesResult, type IUploadAndRequestSignaturesSigner, type IUploadSignatureOptions, type IWebhookDispatch, type IWebhookDispatchListParams, type IWebhookEndpoint, type IWebhookEndpointCreatePayload, type IWebhookEndpointSecret, type IWebhookEndpointUpdatePayload, type IWebhookEventTypeInfo, type IWebhookPayload, type IWebhookRegisterPayload, type IWebhookSubscription, type IWhatsAppNotification, type IWorkspaceListItem, type IWorkspaceListResponse, type IWorkspaceResponse, type Logger, MAX_LIST_PAGE_SIZE, MAX_UPLOAD_BYTES, NetworkError, type NotificationSenderType, OAuthError, OAuthResource, type OAuthScope, type PaginatedResult, type PaginationMeta, SDK_USER_AGENT, type SendTokenChannel, type SignatureImageType, SignerDocumentsResource, type SignerReference, SignerResource, TagResource, TemplateResource, UserResource, ValidationError, type WebhookEventType, type WebhookHeaders, WebhookResource, WebhookVerifier, WorkspaceResource, buildAssignmentPayload, parseWwwAuthenticate };
7366
+ export { type AccountLogoUploadSource, type AnyString, ApiError, type AssignmentDisplaySettings, type AssignmentMethod, type AssignmentNotificationMethod, AssignmentResource, type AssignmentVerificationMethod, AssinafyClient, type AssinafyClientOptions, AssinafyError, AuthenticationResource, type ClientConfigInput, DEFAULT_WEBHOOK_EVENTS, type DocumentArtifactName, DocumentResource, type DocumentStatsGranularity, type DocumentStatus, type DocumentUploadSource, FieldsResource, type IAccountTheme, type IApiKeyResponse, type IAssignment, type IAssignmentCostSigner, type IAssignmentEntry, type IAssignmentItem, type IAssignmentListParams, type IAssignmentListResponse, type IAssignmentSigner, type IAuthenticateChallenge, type IAuthenticatedUser, type IConfirmSignerDataPayload, type IConfirmTotpPayload, type ICostEstimate, type ICreateAssignmentPayload, type ICreateAssignmentResponse, type ICreateDocumentFromTemplateOptions, type ICreateFieldPayload, type ICreateSignerPayload, type ICreateSignerResponse, type ICreateTagPayload, type ICreateWorkspacePayload, type IDeleteTagResponse, type IDetachDocumentTagResponse, type IDisplaySettings, type IDocumentActivity, type IDocumentDetailsResponse, type IDocumentListItem, type IDocumentListParams, type IDocumentListResponse, type IDocumentSearchParams, type IDocumentStatsParams, type IDocumentStatsRow, type IDocumentStatusInfo, type IDocumentUploadOptions, type IDocumentUploadResponse, type IDocumentVerification, type IEstimateAssignmentCostPayload, type IFieldDefinition, type IFieldType, type IFieldValidateMultipleEntry, type IFieldValidationMultipleResult, type IFieldValidationResponse, type IFieldValidationResult, type IInlineTag, type ILegacyConfirmSignerDataPayload, type ILegacyResendCostEstimate, type ILegacyUploadSignatureOptions, type IListParams, type ILoginResponse, type IMaskedApiKeyResponse, type IMfaMethod, type IMfaReauth, type IMfaRecoveryCodes, type IMfaStatus, type INotificationHistoryEntry, type INotificationPreferences, type IOAuthAuthorizationCallback, type IOAuthAuthorizationRequest, type IOAuthAuthorizationServerMetadata, type IOAuthProtectedResourceMetadata, type IOAuthTokenResponse, type IOAuthUserInfo, type IPage, type IPaginatedResponse, type IPublicDocumentInfo, type IRateLimitInfo, type IRenameDocumentResponse, type IResendCostEstimate, type IResendEmailResponse, type ISendTokenResult, type ISignFieldEntry, type ISigner, type ISignerListParams, type ISignerListResponse, type ISignerSelf, type ISigningProgress, type ITag, type ITemplateCostSigner, type ITemplateDetailsResponse, type ITemplateFieldPlacement, type ITemplateListItem, type ITemplateListParams, type ITemplateListResponse, type ITemplateRole, type ITemplateSigner, type ITotpEnrollment, type IUpdateFieldPayload, type IUpdateNotificationPreferences, type IUpdateSignerPayload, type IUpdateTagPayload, type IUpdateTemplatePayload, type IUpdateWorkspacePayload, type IUploadAndRequestSignaturesResult, type IUploadAndRequestSignaturesSigner, type IUploadSignatureOptions, type IWebhookDispatch, type IWebhookDispatchListParams, type IWebhookEndpoint, type IWebhookEndpointCreatePayload, type IWebhookEndpointSecret, type IWebhookEndpointUpdatePayload, type IWebhookEventTypeInfo, type IWebhookPayload, type IWebhookRegisterPayload, type IWebhookSubscription, type IWhatsAppNotification, type IWorkspaceListItem, type IWorkspaceListResponse, type IWorkspaceResponse, type Logger, MAX_LIST_PAGE_SIZE, MAX_UPLOAD_BYTES, NetworkError, type NotificationSenderType, OAuthError, OAuthResource, type OAuthScope, type PaginatedResult, type PaginationMeta, SDK_USER_AGENT, type SendTokenChannel, type SignatureImageType, SignerDocumentsResource, type SignerReference, SignerResource, TagResource, TemplateResource, UserResource, ValidationError, type WebhookEventType, type WebhookHeaders, WebhookResource, WebhookVerifier, WorkspaceResource, buildAssignmentPayload, parseWwwAuthenticate };
package/dist/index.js CHANGED
@@ -115,6 +115,25 @@ var ApiError = class _ApiError extends AssinafyError {
115
115
  * ```
116
116
  */
117
117
  challenge;
118
+ /**
119
+ * Rate-limit headers carried by the failed response: `X-Rate-Limit-Limit`,
120
+ * `X-Rate-Limit-Remaining`, `X-Rate-Limit-Reset` and, on `429`,
121
+ * `Retry-After` (all in requests or seconds). `undefined` when the response
122
+ * carried none of them. The client already retries a `429` up to
123
+ * `maxRetries` times; this is what remains once those retries are spent.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * try {
128
+ * await client.documents.list();
129
+ * } catch (error) {
130
+ * if (error instanceof ApiError && error.statusCode === 429) {
131
+ * await sleep((error.rateLimit?.retryAfter ?? 60) * 1000);
132
+ * }
133
+ * }
134
+ * ```
135
+ */
136
+ rateLimit;
118
137
  /**
119
138
  * Create an error representing a non-success API response.
120
139
  *
@@ -220,6 +239,7 @@ var OAuthError = class _OAuthError extends ApiError {
220
239
  body
221
240
  );
222
241
  if (error.challenge !== void 0) upgraded.challenge = error.challenge;
242
+ if (error.rateLimit !== void 0) upgraded.rateLimit = error.rateLimit;
223
243
  return upgraded;
224
244
  }
225
245
  };
@@ -297,6 +317,20 @@ function parseWwwAuthenticate(value) {
297
317
  }
298
318
  return challenge;
299
319
  }
320
+ var RATE_LIMIT_HEADERS = [
321
+ ["limit", "x-rate-limit-limit"],
322
+ ["remaining", "x-rate-limit-remaining"],
323
+ ["reset", "x-rate-limit-reset"],
324
+ ["retryAfter", "retry-after"]
325
+ ];
326
+ function parseRateLimit(headers) {
327
+ const info = {};
328
+ for (const [key, header2] of RATE_LIMIT_HEADERS) {
329
+ const value = readHeader(headers, header2)?.trim();
330
+ if (value !== void 0 && /^\d+$/u.test(value)) info[key] = Number(value);
331
+ }
332
+ return Object.keys(info).length > 0 ? info : void 0;
333
+ }
300
334
 
301
335
  // src/utils.ts
302
336
  var SAFE_LOG_NUMBER_FIELDS = /* @__PURE__ */ new Set([
@@ -343,10 +377,11 @@ function toSdkError(error, fallbackMessage) {
343
377
  if (status) {
344
378
  const body = decodeBinaryErrorBody(error.response?.data ?? null);
345
379
  const apiError = ApiError.fromResponse(status, body ?? null);
346
- const challenge = parseWwwAuthenticate(
347
- readHeader(error.response?.headers, "www-authenticate")
348
- );
380
+ const headers = error.response?.headers;
381
+ const challenge = parseWwwAuthenticate(readHeader(headers, "www-authenticate"));
349
382
  if (challenge) apiError.challenge = challenge;
383
+ const rateLimit = parseRateLimit(headers);
384
+ if (rateLimit) apiError.rateLimit = rateLimit;
350
385
  return apiError;
351
386
  }
352
387
  const cause = sanitiseNetworkCause(error);
@@ -652,7 +687,7 @@ var import_axios2 = __toESM(require("axios"));
652
687
  // package.json
653
688
  var package_default = {
654
689
  name: "@assinafy/sdk",
655
- version: "2.7.0",
690
+ version: "2.7.1",
656
691
  packageManager: "bun@1.4.0",
657
692
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
658
693
  type: "commonjs",
@@ -715,7 +750,7 @@ var package_default = {
715
750
  bugs: {
716
751
  url: "https://github.com/assinafy/typescript-sdk/issues"
717
752
  },
718
- homepage: "https://github.com/assinafy/typescript-sdk/#readme",
753
+ homepage: "https://www.assinafy.com.br",
719
754
  devDependencies: {
720
755
  "@arethetypeswrong/cli": "^0.18.5",
721
756
  "@eslint/js": "^10.0.1",
@@ -2824,32 +2859,63 @@ var DocumentResource = class extends BaseResource {
2824
2859
  () => this.publicHttp.get(`/public/documents/${this.pathSegment(id, "Document ID")}`)
2825
2860
  );
2826
2861
  }
2827
- async sendToken(documentId, recipient, channel) {
2862
+ /**
2863
+ * Email the signer the verification token that unlocks a document
2864
+ * (`PUT /public/documents/{documentId}/send-token`).
2865
+ *
2866
+ * Part of the public signing flow: dispatches the 6-digit verification
2867
+ * token the signer enters to view the document. Runs on the
2868
+ * credential-free transport. The contract accepts only the `email`
2869
+ * channel, and both body fields are required.
2870
+ *
2871
+ * Request body (`application/json`):
2872
+ * ```jsonc
2873
+ * { "channel": "email", "recipient": "signer@example.com" }
2874
+ * ```
2875
+ *
2876
+ * @param documentId - The document to send the token for.
2877
+ * @param recipient - The signer's email address.
2878
+ * @param channel - Delivery channel; only `email` is accepted (default).
2879
+ * @returns The delivery confirmation (`data` of the envelope):
2880
+ * ```jsonc
2881
+ * {
2882
+ * "document": {
2883
+ * "resource": "document",
2884
+ * "id": "a1b2c3d4e5f6a7b8c9d0",
2885
+ * "name": "Contract.pdf",
2886
+ * "page_count": 3,
2887
+ * "created_by": "Jane Doe"
2888
+ * },
2889
+ * "channel": "email",
2890
+ * "recipient": "signer@example.com"
2891
+ * }
2892
+ * ```
2893
+ * @throws {ValidationError} If `documentId` is missing, `recipient` is not
2894
+ * a valid email address, or `channel` is not `email`.
2895
+ * @throws {ApiError} `400` if validation fails; `404` if the document does
2896
+ * not exist.
2897
+ *
2898
+ * @example
2899
+ * ```ts
2900
+ * const sent = await client.documents.sendToken('doc-1', 'signer@example.com');
2901
+ * console.log(sent.recipient);
2902
+ * ```
2903
+ */
2904
+ async sendToken(documentId, recipient, channel = "email") {
2828
2905
  const id = this.requireId(documentId, "Document ID");
2829
- assertNonEmptyString(recipient, "recipient");
2830
- if (channel !== void 0) assertNonEmptyString(channel, "channel");
2831
- if (channel === void 0 && !isEmail(recipient)) {
2832
- throw new ValidationError("recipient must be a valid email address");
2833
- }
2834
- const path2 = `/public/documents/${this.pathSegment(id, "Document ID")}/send-token`;
2835
- if (channel !== void 0) {
2836
- return this.callVoid(
2837
- "Failed to send signing token",
2838
- () => this.publicHttp.put(path2, { recipient, channel })
2839
- );
2906
+ if (channel !== "email") {
2907
+ throw new ValidationError('channel must be "email"', { channel });
2840
2908
  }
2841
- try {
2842
- return await this.callVoid(
2843
- "Failed to send signing token",
2844
- () => this.publicHttp.put(path2, { email: recipient })
2845
- );
2846
- } catch (error) {
2847
- if (!isLegacySendTokenValidation(error)) throw error;
2848
- return this.callVoid(
2849
- "Failed to send signing token",
2850
- () => this.publicHttp.put(path2, { recipient, channel: "email" })
2851
- );
2909
+ if (!isEmail(recipient)) {
2910
+ throw new ValidationError("recipient must be a valid email address");
2852
2911
  }
2912
+ return this.call(
2913
+ "Failed to send signing token",
2914
+ () => this.publicHttp.put(
2915
+ `/public/documents/${this.pathSegment(id, "Document ID")}/send-token`,
2916
+ { channel, recipient }
2917
+ )
2918
+ );
2853
2919
  }
2854
2920
  /**
2855
2921
  * Quick boolean check (`GET /documents/{documentId}`): has every signer
@@ -2995,23 +3061,6 @@ function validateWaitOption(value, name) {
2995
3061
  function sleep(ms) {
2996
3062
  return new Promise((resolve) => setTimeout(resolve, ms));
2997
3063
  }
2998
- function isLegacySendTokenValidation(error) {
2999
- if (!(error instanceof ApiError) || error.statusCode !== 400 && error.statusCode !== 422) {
3000
- return false;
3001
- }
3002
- const namesLegacyField = /\b(?:channel|recipient)\b/iu.test(error.message);
3003
- const saysRequired = /\b(?:required|obrigat[oó]ri[oa])\b/iu.test(error.message);
3004
- if (namesLegacyField && saysRequired) return true;
3005
- const response = error.responseData;
3006
- if (!response || typeof response !== "object" || Array.isArray(response)) return false;
3007
- const errors = response["errors"];
3008
- if (!errors || typeof errors !== "object" || Array.isArray(errors)) return false;
3009
- return ["channel", "recipient"].some((field) => {
3010
- if (!Object.hasOwn(errors, field)) return false;
3011
- const detail = JSON.stringify(errors[field]);
3012
- return /required|obrigat[oó]ri[oa]/iu.test(detail);
3013
- });
3014
- }
3015
3064
 
3016
3065
  // src/resources/signers.ts
3017
3066
  var SignerResource = class extends BaseResource {
@@ -6724,7 +6773,14 @@ function validateSignerAccessCode(value) {
6724
6773
  var SignerDocumentsResource = class extends BaseResource {
6725
6774
  constructor(http, defaultAccountId, logger, publicHttp) {
6726
6775
  super(withoutCredentials(publicHttp ?? http), defaultAccountId, logger);
6776
+ this.workspaceHttp = http;
6727
6777
  }
6778
+ /**
6779
+ * Credentialed transport used only by the explicit `*AsWorkspace` methods.
6780
+ * Every access-code method stays on the credential-free `http`, so a
6781
+ * signer code and the API key or bearer token never share a request.
6782
+ */
6783
+ workspaceHttp;
6728
6784
  /**
6729
6785
  * Fetch the document currently awaiting a given signer
6730
6786
  * (`GET /signers/{signer_id}/document?signer-access-code=…`).
@@ -6897,6 +6953,73 @@ var SignerDocumentsResource = class extends BaseResource {
6897
6953
  })
6898
6954
  );
6899
6955
  }
6956
+ /**
6957
+ * List a signer's documents with the workspace credentials
6958
+ * (`GET /signers/{signer_id}/documents`).
6959
+ *
6960
+ * The same operation as {@link SignerDocumentsResource.list}, authorised by
6961
+ * the client's API key or OAuth bearer token instead of a signer access
6962
+ * code. No `signer-access-code` is sent.
6963
+ *
6964
+ * @param signerId - The signer whose documents are listed.
6965
+ * @param params - Pagination: `page`, `per-page` (also accepts `per_page`).
6966
+ * @returns Documents in the compact {@link IDocumentListItem} shape, with
6967
+ * pagination in `meta` (same shape as {@link SignerDocumentsResource.list}):
6968
+ * ```jsonc
6969
+ * {
6970
+ * "data": [{ "id": "103acccd24234c07858ffddf6d84", "name": "Service agreement.pdf", "status": "pending_signature" }],
6971
+ * "meta": { "current_page": 1, "per_page": 20, "total": 1, "last_page": 1 }
6972
+ * }
6973
+ * ```
6974
+ * @throws {ValidationError} If `signerId` is missing.
6975
+ * @throws {ApiError} `401` if the workspace credentials are rejected.
6976
+ *
6977
+ * @example
6978
+ * ```ts
6979
+ * const { data } = await client.signerDocuments.listAsWorkspace(signerId, { page: 1 });
6980
+ * ```
6981
+ */
6982
+ async listAsWorkspace(signerId, params = {}) {
6983
+ const sid = this.pathSegment(signerId, "Signer ID");
6984
+ return this.callList(
6985
+ "Failed to list signer documents",
6986
+ () => this.workspaceHttp.get(`/signers/${sid}/documents`, {
6987
+ params: cleanListParams(params)
6988
+ })
6989
+ );
6990
+ }
6991
+ /**
6992
+ * Search a signer's documents with the workspace credentials
6993
+ * (`GET /signers/{signer_id}/documents/search`).
6994
+ *
6995
+ * The same operation as {@link SignerDocumentsResource.search}, authorised
6996
+ * by the client's API key or OAuth bearer token instead of a signer access
6997
+ * code. No `signer-access-code` is sent.
6998
+ *
6999
+ * @param signerId - The signer whose documents are searched.
7000
+ * @param search - Free-text term matched against the document name.
7001
+ * @returns Matching documents with pagination in `meta`, as
7002
+ * {@link SignerDocumentsResource.listAsWorkspace} returns.
7003
+ * @throws {ValidationError} If `signerId` is missing or `search` is not a string.
7004
+ * @throws {ApiError} `401` if the workspace credentials are rejected.
7005
+ *
7006
+ * @example
7007
+ * ```ts
7008
+ * const { data } = await client.signerDocuments.searchAsWorkspace(signerId, 'agreement');
7009
+ * ```
7010
+ */
7011
+ async searchAsWorkspace(signerId, search) {
7012
+ const sid = this.pathSegment(signerId, "Signer ID");
7013
+ if (search !== void 0 && typeof search !== "string") {
7014
+ throw new ValidationError("search must be a string");
7015
+ }
7016
+ return this.callList(
7017
+ "Failed to search signer documents",
7018
+ () => this.workspaceHttp.get(`/signers/${sid}/documents/search`, {
7019
+ params: cleanParams({ search })
7020
+ })
7021
+ );
7022
+ }
6900
7023
  /**
6901
7024
  * Download one of a signer's document artifacts as raw bytes
6902
7025
  * (`GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`).
@@ -7479,6 +7602,9 @@ function assertDeclineReason(declineReason) {
7479
7602
  if (typeof declineReason !== "string" || !declineReason.trim()) {
7480
7603
  throw new ValidationError("declineReason is required");
7481
7604
  }
7605
+ if (declineReason.length > 2e3) {
7606
+ throw new ValidationError("declineReason must be at most 2000 characters");
7607
+ }
7482
7608
  }
7483
7609
  function validateConfirmDataPayload(payload) {
7484
7610
  for (const key of ["full_name", "government_id"]) {
@@ -8044,9 +8170,8 @@ function decodeSecret(secret) {
8044
8170
  return key.length > 0 ? key : null;
8045
8171
  }
8046
8172
  function header(headers, name) {
8047
- const value = typeof headers.get === "function" ? headers.get(name) : headers[name];
8048
- const first = Array.isArray(value) ? value[0] : value;
8049
- return typeof first === "string" ? first.trim() : void 0;
8173
+ const value = typeof headers.get === "function" ? headers.get(name) ?? void 0 : readHeader(headers, name);
8174
+ return typeof value === "string" ? value.trim() : void 0;
8050
8175
  }
8051
8176
  function isRecord(value) {
8052
8177
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -8183,7 +8308,7 @@ var AssinafyClient = class _AssinafyClient {
8183
8308
  );
8184
8309
  this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
8185
8310
  this.signerDocuments = new SignerDocumentsResource(
8186
- this.publicAxiosInstance,
8311
+ this.axiosInstance,
8187
8312
  this.defaultAccountId,
8188
8313
  this.logger,
8189
8314
  this.publicAxiosInstance