@assinafy/sdk 2.6.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.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
  *
@@ -158,7 +177,7 @@ var ApiError = class _ApiError extends AssinafyError {
158
177
  const data = responseData ?? {};
159
178
  const rawMessage = data["message"];
160
179
  const rawError = data["error"];
161
- const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : FALLBACK_MESSAGE;
180
+ const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" && rawError.length > 0 ? rawError : FALLBACK_MESSAGE;
162
181
  return new _ApiError(message, statusCode, responseData);
163
182
  }
164
183
  };
@@ -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);
@@ -455,15 +490,16 @@ function assertDocumentArtifactName(value) {
455
490
  }
456
491
  function serializeJsonRecord(value, label) {
457
492
  assertRecord(value, label);
493
+ let serialized;
458
494
  try {
459
- const serialized = JSON.stringify(value);
460
- if (typeof serialized !== "string" || !serialized.startsWith("{")) {
461
- throw new ValidationError(`${label} must serialize to a JSON object`);
462
- }
463
- return serialized;
495
+ serialized = JSON.stringify(value);
464
496
  } catch {
465
497
  throw new ValidationError(`${label} must be JSON-serializable`);
466
498
  }
499
+ if (typeof serialized !== "string" || !serialized.startsWith("{")) {
500
+ throw new ValidationError(`${label} must serialize to a JSON object`);
501
+ }
502
+ return serialized;
467
503
  }
468
504
  function assertDateTime(value, label) {
469
505
  if (typeof value !== "string") throw new ValidationError(`${label} must be an ISO-8601 date-time`);
@@ -651,7 +687,7 @@ var import_axios2 = __toESM(require("axios"));
651
687
  // package.json
652
688
  var package_default = {
653
689
  name: "@assinafy/sdk",
654
- version: "2.6.0",
690
+ version: "2.7.1",
655
691
  packageManager: "bun@1.4.0",
656
692
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
657
693
  type: "commonjs",
@@ -714,7 +750,7 @@ var package_default = {
714
750
  bugs: {
715
751
  url: "https://github.com/assinafy/typescript-sdk/issues"
716
752
  },
717
- homepage: "https://github.com/assinafy/typescript-sdk/#readme",
753
+ homepage: "https://www.assinafy.com.br",
718
754
  devDependencies: {
719
755
  "@arethetypeswrong/cli": "^0.18.5",
720
756
  "@eslint/js": "^10.0.1",
@@ -1545,9 +1581,10 @@ var AssignmentResource = class extends BaseResource {
1545
1581
  * Update the expiration date of an existing assignment
1546
1582
  * (`PUT /documents/{documentId}/assignments/{assignmentId}/reset-expiration`).
1547
1583
  *
1548
- * Sends `{ expires_at }` verbatim. Use an ISO-8601 date/time string; `null`
1549
- * is retained as a compatibility value and, unlike ordinary nullable
1550
- * inputs, is intentionally not stripped from the body.
1584
+ * Sends `{ expires_at }` verbatim; the key itself is required by the
1585
+ * contract. Use an ISO-8601 date/time string, or `null` to remove the
1586
+ * expiration — `null` is the documented clear mechanism and, unlike
1587
+ * ordinary nullable inputs, is intentionally not stripped from the body.
1551
1588
  *
1552
1589
  * Request body (`application/json`):
1553
1590
  * ```jsonc
@@ -1558,8 +1595,8 @@ var AssignmentResource = class extends BaseResource {
1558
1595
  *
1559
1596
  * @param documentId - The document the assignment belongs to.
1560
1597
  * @param assignmentId - The assignment to update.
1561
- * @param expiresAt - New expiry as an ISO-8601 date/time string. `null` is
1562
- * a compatibility value intended to clear it.
1598
+ * @param expiresAt - New expiry as an ISO-8601 date/time string, or `null`
1599
+ * to remove the expiration.
1563
1600
  * @returns The updated {@link IAssignment} — the same full shape
1564
1601
  * {@link AssignmentResource.create} returns (`signers`, `items`, `summary`,
1565
1602
  * `signing_urls`), with `expires_at` reflecting the new value:
@@ -2822,32 +2859,63 @@ var DocumentResource = class extends BaseResource {
2822
2859
  () => this.publicHttp.get(`/public/documents/${this.pathSegment(id, "Document ID")}`)
2823
2860
  );
2824
2861
  }
2825
- 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") {
2826
2905
  const id = this.requireId(documentId, "Document ID");
2827
- assertNonEmptyString(recipient, "recipient");
2828
- if (channel !== void 0) assertNonEmptyString(channel, "channel");
2829
- if (channel === void 0 && !isEmail(recipient)) {
2830
- throw new ValidationError("recipient must be a valid email address");
2831
- }
2832
- const path2 = `/public/documents/${this.pathSegment(id, "Document ID")}/send-token`;
2833
- if (channel !== void 0) {
2834
- return this.callVoid(
2835
- "Failed to send signing token",
2836
- () => this.publicHttp.put(path2, { recipient, channel })
2837
- );
2906
+ if (channel !== "email") {
2907
+ throw new ValidationError('channel must be "email"', { channel });
2838
2908
  }
2839
- try {
2840
- return await this.callVoid(
2841
- "Failed to send signing token",
2842
- () => this.publicHttp.put(path2, { email: recipient })
2843
- );
2844
- } catch (error) {
2845
- if (!isLegacySendTokenValidation(error)) throw error;
2846
- return this.callVoid(
2847
- "Failed to send signing token",
2848
- () => this.publicHttp.put(path2, { recipient, channel: "email" })
2849
- );
2909
+ if (!isEmail(recipient)) {
2910
+ throw new ValidationError("recipient must be a valid email address");
2850
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
+ );
2851
2919
  }
2852
2920
  /**
2853
2921
  * Quick boolean check (`GET /documents/{documentId}`): has every signer
@@ -2993,23 +3061,6 @@ function validateWaitOption(value, name) {
2993
3061
  function sleep(ms) {
2994
3062
  return new Promise((resolve) => setTimeout(resolve, ms));
2995
3063
  }
2996
- function isLegacySendTokenValidation(error) {
2997
- if (!(error instanceof ApiError) || error.statusCode !== 400 && error.statusCode !== 422) {
2998
- return false;
2999
- }
3000
- const namesLegacyField = /\b(?:channel|recipient)\b/iu.test(error.message);
3001
- const saysRequired = /\b(?:required|obrigat[oó]ri[oa])\b/iu.test(error.message);
3002
- if (namesLegacyField && saysRequired) return true;
3003
- const response = error.responseData;
3004
- if (!response || typeof response !== "object" || Array.isArray(response)) return false;
3005
- const errors = response["errors"];
3006
- if (!errors || typeof errors !== "object" || Array.isArray(errors)) return false;
3007
- return ["channel", "recipient"].some((field) => {
3008
- if (!Object.hasOwn(errors, field)) return false;
3009
- const detail = JSON.stringify(errors[field]);
3010
- return /required|obrigat[oó]ri[oa]/iu.test(detail);
3011
- });
3012
- }
3013
3064
 
3014
3065
  // src/resources/signers.ts
3015
3066
  var SignerResource = class extends BaseResource {
@@ -4808,7 +4859,7 @@ var TemplateResource = class extends BaseResource {
4808
4859
  * ```ts
4809
4860
  * const tmpl = await client.templates.get('103ad2171db7979468c3e97eb067');
4810
4861
  * const jpeg = await client.templates.downloadPage(tmpl.id, tmpl.pages[0].id);
4811
- * await fs.writeFile('page-1.jpg', jpeg);
4862
+ * await fs.promises.writeFile('page-1.jpg', jpeg);
4812
4863
  * ```
4813
4864
  */
4814
4865
  async downloadPage(templateId, pageId, accountId) {
@@ -5145,10 +5196,10 @@ var AuthenticationResource = class extends BaseResource {
5145
5196
  * ]
5146
5197
  * }
5147
5198
  * ```
5148
- * @throws {ValidationError} If `email` or `password` is missing.
5149
5199
  * When the user has two-factor authentication enabled the response carries
5150
5200
  * an `mfa_token` instead of a usable session; finish with
5151
5201
  * {@link AuthenticationResource.verifyMfa}.
5202
+ * @throws {ValidationError} If `email` or `password` is missing.
5152
5203
  * @throws {ApiError} `400` if the credentials are rejected.
5153
5204
  *
5154
5205
  * @example
@@ -5296,13 +5347,6 @@ var AuthenticationResource = class extends BaseResource {
5296
5347
  * Link a Google identity to the authenticated user
5297
5348
  * (`POST /auth/link-social-login`).
5298
5349
  *
5299
- * Request body:
5300
- * ```jsonc
5301
- * { "provider": "google", "token": "provider-issued-token" }
5302
- * ```
5303
- * The response is the standard status/message acknowledgement with no data,
5304
- * so this method resolves to `void`.
5305
- *
5306
5350
  * Request body (`application/json`):
5307
5351
  * ```jsonc
5308
5352
  * {
@@ -5310,6 +5354,8 @@ var AuthenticationResource = class extends BaseResource {
5310
5354
  * "token": "provider_token_example"
5311
5355
  * }
5312
5356
  * ```
5357
+ * The response is the standard status/message acknowledgement with no data,
5358
+ * so this method resolves to `void`.
5313
5359
  *
5314
5360
  * @param payload - Social provider and provider-issued access/ID token.
5315
5361
  * @returns Resolves when the API acknowledges that the identity was linked.
@@ -6066,6 +6112,11 @@ var OAuthResource = class extends BaseResource {
6066
6112
  * already-revoked included — so the endpoint cannot be used to probe
6067
6113
  * whether a token exists. Only failed client authentication returns `401`.
6068
6114
  *
6115
+ * Request body (`application/x-www-form-urlencoded`):
6116
+ * ```text
6117
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
6118
+ * ```
6119
+ *
6069
6120
  * @param options - Revocation options.
6070
6121
  * @param options.token - The access or refresh token to revoke.
6071
6122
  * @param options.clientId - The application's `client_id`.
@@ -6074,10 +6125,6 @@ var OAuthResource = class extends BaseResource {
6074
6125
  * @param options.tokenTypeHint - Optional `access_token` or
6075
6126
  * `refresh_token` hint that lets the server skip a lookup.
6076
6127
  * @returns Nothing; resolves once the API acknowledges the request.
6077
- * Request body (`application/x-www-form-urlencoded`):
6078
- * ```text
6079
- * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
6080
- * ```
6081
6128
  * @throws {ValidationError} If `token` or `clientId` is missing, or
6082
6129
  * `tokenTypeHint` is not one of the two documented values.
6083
6130
  * @throws {OAuthError} `invalid_client` when client authentication fails.
@@ -6726,7 +6773,14 @@ function validateSignerAccessCode(value) {
6726
6773
  var SignerDocumentsResource = class extends BaseResource {
6727
6774
  constructor(http, defaultAccountId, logger, publicHttp) {
6728
6775
  super(withoutCredentials(publicHttp ?? http), defaultAccountId, logger);
6776
+ this.workspaceHttp = http;
6729
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;
6730
6784
  /**
6731
6785
  * Fetch the document currently awaiting a given signer
6732
6786
  * (`GET /signers/{signer_id}/document?signer-access-code=…`).
@@ -6899,6 +6953,73 @@ var SignerDocumentsResource = class extends BaseResource {
6899
6953
  })
6900
6954
  );
6901
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
+ }
6902
7023
  /**
6903
7024
  * Download one of a signer's document artifacts as raw bytes
6904
7025
  * (`GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`).
@@ -6932,7 +7053,7 @@ var SignerDocumentsResource = class extends BaseResource {
6932
7053
  * documentId,
6933
7054
  * 'original',
6934
7055
  * );
6935
- * await fs.writeFile('to-sign.pdf', pdf);
7056
+ * await fs.promises.writeFile('to-sign.pdf', pdf);
6936
7057
  * ```
6937
7058
  */
6938
7059
  async download(signerId, documentId, artifactName, signerAccessCode) {
@@ -7239,7 +7360,7 @@ var SignerDocumentsResource = class extends BaseResource {
7239
7360
  * @example
7240
7361
  * ```ts
7241
7362
  * const png = await client.signerDocuments.downloadSignature(accessCode, 'signature');
7242
- * await fs.writeFile('signature.png', png);
7363
+ * await fs.promises.writeFile('signature.png', png);
7243
7364
  * ```
7244
7365
  */
7245
7366
  async downloadSignature(signerAccessCode, imageType = "signature") {
@@ -7481,6 +7602,9 @@ function assertDeclineReason(declineReason) {
7481
7602
  if (typeof declineReason !== "string" || !declineReason.trim()) {
7482
7603
  throw new ValidationError("declineReason is required");
7483
7604
  }
7605
+ if (declineReason.length > 2e3) {
7606
+ throw new ValidationError("declineReason must be at most 2000 characters");
7607
+ }
7484
7608
  }
7485
7609
  function validateConfirmDataPayload(payload) {
7486
7610
  for (const key of ["full_name", "government_id"]) {
@@ -8046,9 +8170,8 @@ function decodeSecret(secret) {
8046
8170
  return key.length > 0 ? key : null;
8047
8171
  }
8048
8172
  function header(headers, name) {
8049
- const value = typeof headers.get === "function" ? headers.get(name) : headers[name];
8050
- const first = Array.isArray(value) ? value[0] : value;
8051
- 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;
8052
8175
  }
8053
8176
  function isRecord(value) {
8054
8177
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -8185,7 +8308,7 @@ var AssinafyClient = class _AssinafyClient {
8185
8308
  );
8186
8309
  this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
8187
8310
  this.signerDocuments = new SignerDocumentsResource(
8188
- this.publicAxiosInstance,
8311
+ this.axiosInstance,
8189
8312
  this.defaultAccountId,
8190
8313
  this.logger,
8191
8314
  this.publicAxiosInstance
@@ -8255,7 +8378,7 @@ var AssinafyClient = class _AssinafyClient {
8255
8378
  if (baseUrl !== void 0) opts.baseUrl = baseUrl;
8256
8379
  if (webhookSecret !== void 0) opts.webhookSecret = webhookSecret;
8257
8380
  if (config.timeout !== void 0) opts.timeout = config.timeout;
8258
- const maxRetries = config.maxRetries ?? config.max_retries;
8381
+ const maxRetries = config.max_retries ?? config.maxRetries;
8259
8382
  if (maxRetries !== void 0) opts.maxRetries = maxRetries;
8260
8383
  if (config.logger !== void 0) opts.logger = config.logger;
8261
8384
  return new _AssinafyClient(opts);