@assinafy/cli 2.0.2 → 2.1.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.
Files changed (48) hide show
  1. package/.env.example +54 -0
  2. package/CONTRIBUTING.md +29 -0
  3. package/README.en.md +559 -0
  4. package/README.md +314 -180
  5. package/SECURITY.md +10 -0
  6. package/THIRD_PARTY_NOTICES.md +3 -3
  7. package/dist/api.cjs +453 -74
  8. package/dist/api.cjs.map +1 -1
  9. package/dist/api.js +451 -74
  10. package/dist/api.js.map +1 -1
  11. package/dist/cli.cjs +1278 -228
  12. package/dist/types/api/client.d.ts +7 -0
  13. package/dist/types/api/client.d.ts.map +1 -1
  14. package/dist/types/api/errors.d.ts +42 -1
  15. package/dist/types/api/errors.d.ts.map +1 -1
  16. package/dist/types/api/index.d.ts +1 -0
  17. package/dist/types/api/index.d.ts.map +1 -1
  18. package/dist/types/api/resources/assignments.d.ts +3 -1
  19. package/dist/types/api/resources/assignments.d.ts.map +1 -1
  20. package/dist/types/api/resources/documents.d.ts +3 -3
  21. package/dist/types/api/resources/documents.d.ts.map +1 -1
  22. package/dist/types/api/resources/fields.d.ts.map +1 -1
  23. package/dist/types/api/resources/oauth.d.ts +20 -0
  24. package/dist/types/api/resources/oauth.d.ts.map +1 -0
  25. package/dist/types/api/resources/signer-documents.d.ts +9 -5
  26. package/dist/types/api/resources/signer-documents.d.ts.map +1 -1
  27. package/dist/types/api/resources/signers.d.ts.map +1 -1
  28. package/dist/types/api/resources/webhooks.d.ts.map +1 -1
  29. package/dist/types/api/support/webhook-verifier.d.ts.map +1 -1
  30. package/dist/types/api/types.d.ts +146 -56
  31. package/dist/types/api/types.d.ts.map +1 -1
  32. package/dist/types/api/utils.d.ts +18 -0
  33. package/dist/types/api/utils.d.ts.map +1 -1
  34. package/docs/README.md +4 -2
  35. package/docs/api-operations.json +33 -1
  36. package/docs/api-reference.md +323 -79
  37. package/docs/assignments.md +3 -3
  38. package/docs/documents.md +8 -8
  39. package/docs/fields.md +4 -4
  40. package/docs/migration-v2.md +6 -2
  41. package/docs/oauth-guide.md +343 -0
  42. package/docs/oauth.md +162 -0
  43. package/docs/releasing.md +16 -6
  44. package/docs/sdk-reference.md +121 -24
  45. package/docs/signer.md +3 -2
  46. package/install.ps1 +9 -2
  47. package/install.sh +5 -5
  48. package/package.json +8 -5
package/dist/cli.cjs CHANGED
@@ -15467,22 +15467,82 @@ var { toString } = Object.prototype;
15467
15467
  var { getPrototypeOf } = Object;
15468
15468
  var { iterator, toStringTag } = Symbol;
15469
15469
  var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
15470
+ var isUnsafeObjectKey = (prop) => typeof prop === "string" && (prop === "__proto__" || prop === "constructor" || prop === "prototype");
15471
+ var isPrototypeBoundary = (obj, prototype2, source) => obj === Object.prototype || !source && prototype2 === null;
15472
+ var isSafeAndFullyMutable = (obj) => {
15473
+ if (!Object.isExtensible(obj)) {
15474
+ return false;
15475
+ }
15476
+ const props = Object.getOwnPropertyNames(obj);
15477
+ if (Object.getOwnPropertySymbols) {
15478
+ props.push(...Object.getOwnPropertySymbols(obj));
15479
+ }
15480
+ return props.every((prop) => {
15481
+ if (isUnsafeObjectKey(prop)) {
15482
+ return false;
15483
+ }
15484
+ const descriptor = Object.getOwnPropertyDescriptor(obj, prop);
15485
+ return !!descriptor && descriptor.configurable && descriptor.writable === true;
15486
+ });
15487
+ };
15470
15488
  var hasOwnInPrototypeChain = (thing, prop) => {
15471
15489
  let obj = thing;
15472
15490
  const seen = [];
15473
- while (obj != null && obj !== Object.prototype) {
15491
+ while (obj != null) {
15474
15492
  if (seen.indexOf(obj) !== -1) {
15475
15493
  return false;
15476
15494
  }
15477
15495
  seen.push(obj);
15496
+ const prototype2 = getPrototypeOf(obj);
15497
+ if (isPrototypeBoundary(obj, prototype2, obj === thing)) {
15498
+ return false;
15499
+ }
15478
15500
  if (hasOwnProperty(obj, prop)) {
15479
15501
  return true;
15480
15502
  }
15481
- obj = getPrototypeOf(obj);
15503
+ obj = prototype2;
15482
15504
  }
15483
15505
  return false;
15484
15506
  };
15485
15507
  var getSafeProp = (obj, prop) => obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : void 0;
15508
+ var toSafeFlatObject = (thing) => {
15509
+ if (thing == null || typeof thing !== "object" && typeof thing !== "function") {
15510
+ return thing;
15511
+ }
15512
+ const sourcePrototype = getPrototypeOf(thing);
15513
+ if (sourcePrototype === null && isSafeAndFullyMutable(thing)) {
15514
+ return thing;
15515
+ }
15516
+ const result = /* @__PURE__ */ Object.create(null);
15517
+ const merged = /* @__PURE__ */ Object.create(null);
15518
+ const seen = [];
15519
+ let current = thing;
15520
+ while (current != null) {
15521
+ if (seen.indexOf(current) !== -1) {
15522
+ break;
15523
+ }
15524
+ seen.push(current);
15525
+ const prototype2 = current === thing ? sourcePrototype : getPrototypeOf(current);
15526
+ if (isPrototypeBoundary(current, prototype2, current === thing)) {
15527
+ break;
15528
+ }
15529
+ const props = Object.getOwnPropertyNames(current);
15530
+ if (Object.getOwnPropertySymbols) {
15531
+ props.push(...Object.getOwnPropertySymbols(current));
15532
+ }
15533
+ for (const prop of props) {
15534
+ if (isUnsafeObjectKey(prop)) {
15535
+ continue;
15536
+ }
15537
+ if (!hasOwnProperty(merged, prop)) {
15538
+ result[prop] = thing[prop];
15539
+ merged[prop] = true;
15540
+ }
15541
+ }
15542
+ current = prototype2;
15543
+ }
15544
+ return result;
15545
+ };
15486
15546
  var kindOf = /* @__PURE__ */ ((cache) => (thing) => {
15487
15547
  const str = toString.call(thing);
15488
15548
  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
@@ -15517,9 +15577,9 @@ var isPlainObject = (val) => {
15517
15577
  return false;
15518
15578
  }
15519
15579
  const prototype2 = getPrototypeOf(val);
15520
- return (prototype2 === null || prototype2 === Object.prototype || getPrototypeOf(prototype2) === null) && // Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or
15521
- // Symbol.iterator as evidence the value is a tagged/iterable type rather
15522
- // than a plain object, while ignoring keys injected onto Object.prototype.
15580
+ return (prototype2 === null || prototype2 === Object.prototype || getPrototypeOf(prototype2) === null) && // Treat safe own/inherited Symbol.toStringTag or Symbol.iterator members as
15581
+ // evidence the value is tagged/iterable, while ignoring members reachable
15582
+ // only through shared or terminal prototype boundaries.
15523
15583
  !hasOwnInPrototypeChain(val, toStringTag) && !hasOwnInPrototypeChain(val, iterator);
15524
15584
  };
15525
15585
  var isEmptyObject = (val) => {
@@ -15930,6 +15990,7 @@ var utils_default = {
15930
15990
  // an alias to avoid ESLint no-prototype-builtins detection
15931
15991
  hasOwnInPrototypeChain,
15932
15992
  getSafeProp,
15993
+ toSafeFlatObject,
15933
15994
  reduceDescriptors,
15934
15995
  freezeMethods,
15935
15996
  toObjectSet,
@@ -16568,24 +16629,16 @@ function toFormData(obj, formData, options) {
16568
16629
  throw new TypeError("target must be an object");
16569
16630
  }
16570
16631
  formData = formData || new (FormData_default || FormData)();
16571
- options = utils_default.toFlatObject(
16572
- options,
16573
- {
16574
- metaTokens: true,
16575
- dots: false,
16576
- indexes: false
16577
- },
16578
- false,
16579
- function defined(option, source) {
16580
- return !utils_default.isUndefined(source[option]);
16581
- }
16582
- );
16583
- const metaTokens = options.metaTokens;
16584
- const visitor = options.visitor || defaultVisitor;
16585
- const dots = options.dots;
16586
- const indexes = options.indexes;
16587
- const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
16588
- const maxDepth = options.maxDepth === void 0 ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
16632
+ const option = (name, fallback) => {
16633
+ const value = utils_default.getSafeProp(options, name);
16634
+ return utils_default.isUndefined(value) ? fallback : value;
16635
+ };
16636
+ const metaTokens = option("metaTokens", true);
16637
+ const visitor = option("visitor") || defaultVisitor;
16638
+ const dots = option("dots", false);
16639
+ const indexes = option("indexes", false);
16640
+ const _Blob = option("Blob") || typeof Blob !== "undefined" && Blob;
16641
+ const maxDepth = option("maxDepth", DEFAULT_FORM_DATA_MAX_DEPTH);
16589
16642
  const useBlob = _Blob && utils_default.isSpecCompliantForm(formData);
16590
16643
  const stack = [];
16591
16644
  if (!utils_default.isFunction(visitor)) {
@@ -16609,7 +16662,10 @@ function toFormData(obj, formData, options) {
16609
16662
  if (Buffer_default && Buffer_default.isBufferAvailable()) {
16610
16663
  return Buffer_default.from(value);
16611
16664
  }
16612
- throw new AxiosError_default("Blob is not supported. Use a Buffer instead.", AxiosError_default.ERR_NOT_SUPPORT);
16665
+ throw new AxiosError_default(
16666
+ "Blob is not supported. Use a Buffer instead.",
16667
+ AxiosError_default.ERR_NOT_SUPPORT
16668
+ );
16613
16669
  }
16614
16670
  return value;
16615
16671
  }
@@ -16755,9 +16811,47 @@ function buildURL(url2, params, options) {
16755
16811
  }
16756
16812
 
16757
16813
  // node_modules/axios/lib/core/InterceptorManager.js
16814
+ var $internals2 = /* @__PURE__ */ Symbol("internals");
16815
+ function countHandlers(handlers) {
16816
+ return handlers ? handlers.length : 0;
16817
+ }
16818
+ function trimHandlers(handlers) {
16819
+ if (!handlers) {
16820
+ return;
16821
+ }
16822
+ while (handlers.length && handlers[handlers.length - 1] === null) {
16823
+ handlers.pop();
16824
+ }
16825
+ }
16826
+ function syncHandlerEntries(manager, internals) {
16827
+ const handlers = manager.handlers;
16828
+ const length = countHandlers(handlers);
16829
+ if (handlers !== internals.handlersRef) {
16830
+ internals.handlersRef = handlers;
16831
+ internals.handlerEntries.clear();
16832
+ } else if (length !== internals.handlersLength) {
16833
+ if (!length) {
16834
+ internals.handlerEntries.clear();
16835
+ } else {
16836
+ internals.handlerEntries.forEach(function removeStaleEntry(entry, id) {
16837
+ if (handlers[entry.index] !== entry.handler) {
16838
+ internals.handlerEntries.delete(id);
16839
+ }
16840
+ });
16841
+ }
16842
+ }
16843
+ internals.handlersLength = length;
16844
+ }
16758
16845
  var InterceptorManager = class {
16759
16846
  constructor() {
16760
16847
  this.handlers = [];
16848
+ this[$internals2] = {
16849
+ handlersRef: this.handlers,
16850
+ handlersLength: this.handlers.length,
16851
+ handlerEntries: /* @__PURE__ */ new Map(),
16852
+ iterationDepth: 0,
16853
+ nextId: 0
16854
+ };
16761
16855
  }
16762
16856
  /**
16763
16857
  * Add a new interceptor to the stack
@@ -16769,13 +16863,25 @@ var InterceptorManager = class {
16769
16863
  * @return {Number} An ID used to remove interceptor later
16770
16864
  */
16771
16865
  use(fulfilled, rejected, options) {
16772
- this.handlers.push({
16866
+ const handler = {
16773
16867
  fulfilled,
16774
16868
  rejected,
16775
16869
  synchronous: options ? options.synchronous : false,
16776
16870
  runWhen: options ? options.runWhen : null
16871
+ };
16872
+ const internals = this[$internals2];
16873
+ if (this.handlers == null) {
16874
+ this.handlers = [];
16875
+ }
16876
+ syncHandlerEntries(this, internals);
16877
+ const id = internals.nextId++;
16878
+ this.handlers.push(handler);
16879
+ internals.handlerEntries.set(id, {
16880
+ handler,
16881
+ index: this.handlers.length - 1
16777
16882
  });
16778
- return this.handlers.length - 1;
16883
+ internals.handlersLength = this.handlers.length;
16884
+ return id;
16779
16885
  }
16780
16886
  /**
16781
16887
  * Remove an interceptor from the stack
@@ -16785,8 +16891,19 @@ var InterceptorManager = class {
16785
16891
  * @returns {void}
16786
16892
  */
16787
16893
  eject(id) {
16788
- if (this.handlers[id]) {
16789
- this.handlers[id] = null;
16894
+ const internals = this[$internals2];
16895
+ syncHandlerEntries(this, internals);
16896
+ const entry = internals.handlerEntries.get(id);
16897
+ if (entry) {
16898
+ internals.handlerEntries.delete(id);
16899
+ if (this.handlers[entry.index] !== entry.handler) {
16900
+ return;
16901
+ }
16902
+ this.handlers[entry.index] = null;
16903
+ if (!internals.iterationDepth) {
16904
+ trimHandlers(this.handlers);
16905
+ internals.handlersLength = this.handlers.length;
16906
+ }
16790
16907
  }
16791
16908
  }
16792
16909
  /**
@@ -16797,6 +16914,7 @@ var InterceptorManager = class {
16797
16914
  clear() {
16798
16915
  if (this.handlers) {
16799
16916
  this.handlers = [];
16917
+ syncHandlerEntries(this, this[$internals2]);
16800
16918
  }
16801
16919
  }
16802
16920
  /**
@@ -16810,11 +16928,22 @@ var InterceptorManager = class {
16810
16928
  * @returns {void}
16811
16929
  */
16812
16930
  forEach(fn) {
16813
- utils_default.forEach(this.handlers, function forEachHandler(h2) {
16814
- if (h2 !== null) {
16815
- fn(h2);
16931
+ const internals = this[$internals2];
16932
+ syncHandlerEntries(this, internals);
16933
+ internals.iterationDepth++;
16934
+ try {
16935
+ utils_default.forEach(this.handlers, function forEachHandler(h2) {
16936
+ if (h2 !== null) {
16937
+ fn(h2);
16938
+ }
16939
+ });
16940
+ } finally {
16941
+ if (!--internals.iterationDepth) {
16942
+ syncHandlerEntries(this, internals);
16943
+ trimHandlers(this.handlers);
16944
+ internals.handlersLength = countHandlers(this.handlers);
16816
16945
  }
16817
- });
16946
+ }
16818
16947
  }
16819
16948
  };
16820
16949
  var InterceptorManager_default = InterceptorManager;
@@ -16972,6 +17101,22 @@ function formDataToJSON(formData) {
16972
17101
  }
16973
17102
  var formDataToJSON_default = formDataToJSON;
16974
17103
 
17104
+ // node_modules/axios/lib/core/methodList.js
17105
+ var methodList = Object.freeze([
17106
+ "get",
17107
+ "delete",
17108
+ "head",
17109
+ "options",
17110
+ "post",
17111
+ "put",
17112
+ "patch",
17113
+ "purge",
17114
+ "link",
17115
+ "unlink",
17116
+ "query"
17117
+ ]);
17118
+ var methodList_default = methodList;
17119
+
16975
17120
  // node_modules/axios/lib/defaults/index.js
16976
17121
  var own = (obj, key) => obj != null && utils_default.hasOwnProp(obj, key) ? obj[key] : void 0;
16977
17122
  function stringifySafely2(rawValue, parser, encoder) {
@@ -17084,7 +17229,7 @@ var defaults = {
17084
17229
  }
17085
17230
  }
17086
17231
  };
17087
- utils_default.forEach(["delete", "get", "head", "post", "put", "patch", "query"], (method) => {
17232
+ utils_default.forEach(methodList_default, (method) => {
17088
17233
  defaults.headers[method] = {};
17089
17234
  });
17090
17235
  var defaults_default = defaults;
@@ -17162,19 +17307,21 @@ function combineURLs(baseURL, relativeURL) {
17162
17307
  return baseURL.slice(0, end) + "/" + relativeURL.replace(/^\/+/, "");
17163
17308
  }
17164
17309
 
17165
- // node_modules/axios/lib/core/buildFullPath.js
17166
- var malformedHttpProtocol = /^https?:(?!\/\/)/i;
17167
- var httpProtocolControlCharacters = /[\t\n\r]/g;
17168
- function stripLeadingC0ControlOrSpace(url2) {
17169
- let i2 = 0;
17170
- while (i2 < url2.length && url2.charCodeAt(i2) <= 32) {
17171
- i2++;
17172
- }
17173
- return url2.slice(i2);
17174
- }
17310
+ // node_modules/axios/lib/helpers/normalizeURLForProtocolCheck.js
17311
+ var urlParserControlCharacters = /[\t\n\r]/g;
17175
17312
  function normalizeURLForProtocolCheck(url2) {
17176
- return stripLeadingC0ControlOrSpace(url2).replace(httpProtocolControlCharacters, "");
17313
+ if (typeof url2 !== "string") {
17314
+ return url2;
17315
+ }
17316
+ let start = 0;
17317
+ while (start < url2.length && url2.charCodeAt(start) <= 32) {
17318
+ start++;
17319
+ }
17320
+ return url2.slice(start).replace(urlParserControlCharacters, "");
17177
17321
  }
17322
+
17323
+ // node_modules/axios/lib/core/buildFullPath.js
17324
+ var malformedHttpProtocol = /^https?:(?!\/\/)/i;
17178
17325
  function redactFragment(fragment) {
17179
17326
  if (!fragment) {
17180
17327
  return fragment;
@@ -17296,7 +17443,7 @@ var import_follow_redirects = __toESM(require_follow_redirects(), 1);
17296
17443
  var import_zlib = __toESM(require("zlib"), 1);
17297
17444
 
17298
17445
  // node_modules/axios/lib/env/data.js
17299
- var VERSION = "1.19.0";
17446
+ var VERSION = "1.20.0";
17300
17447
 
17301
17448
  // node_modules/axios/lib/helpers/parseProtocol.js
17302
17449
  function parseProtocol(url2) {
@@ -17305,7 +17452,7 @@ function parseProtocol(url2) {
17305
17452
  }
17306
17453
 
17307
17454
  // node_modules/axios/lib/helpers/fromDataURI.js
17308
- var DATA_URL_PATTERN = /^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;
17455
+ var DATA_URL_PATTERN = /^([^,;/]+\/[^,;/]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;
17309
17456
  function fromDataURI(uri, asBlob, options) {
17310
17457
  const _Blob = options && options.Blob || platform_default.classes.Blob;
17311
17458
  const protocol = parseProtocol(uri);
@@ -17618,6 +17765,7 @@ var Http2Sessions = class {
17618
17765
  }
17619
17766
  getSession(authority, options) {
17620
17767
  options = Object.assign(
17768
+ /* @__PURE__ */ Object.create(null),
17621
17769
  {
17622
17770
  sessionTimeout: 1e3
17623
17771
  },
@@ -17683,6 +17831,7 @@ var Http2Sessions = class {
17683
17831
  };
17684
17832
  }
17685
17833
  session.once("close", removeSession);
17834
+ session.once("error", removeSession);
17686
17835
  let entry = [session, options];
17687
17836
  authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry];
17688
17837
  return session;
@@ -17707,6 +17856,13 @@ var callbackify_default = callbackify;
17707
17856
 
17708
17857
  // node_modules/axios/lib/helpers/shouldBypassProxy.js
17709
17858
  var LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "0.0.0.0"]);
17859
+ var trimTrailingDots = (value) => {
17860
+ let end = value.length;
17861
+ while (end && value.charCodeAt(end - 1) === 46) {
17862
+ end--;
17863
+ }
17864
+ return end === value.length ? value : value.slice(0, end);
17865
+ };
17710
17866
  var isIPv4Loopback = (host) => {
17711
17867
  const parts = host.split(".");
17712
17868
  if (parts.length !== 4) return false;
@@ -17739,7 +17895,7 @@ var normalizeIPAddress = (host) => {
17739
17895
  if (h2.charAt(0) === "[" && h2.charAt(h2.length - 1) === "]") {
17740
17896
  h2 = h2.slice(1, -1);
17741
17897
  }
17742
- h2 = h2.replace(/\.+$/, "");
17898
+ h2 = trimTrailingDots(h2);
17743
17899
  if (!/^[0-9.xXa-fA-F]+$/.test(h2)) return host;
17744
17900
  const parts = h2.split(".");
17745
17901
  if (parts.some((p) => p === "")) return host;
@@ -17851,6 +18007,40 @@ var unmapIPv4MappedIPv6 = (host) => {
17851
18007
  }
17852
18008
  return host;
17853
18009
  };
18010
+ var IPV4_OCTET_RE = /^(?:0|[1-9]\d{0,2})$/;
18011
+ var ipv4ToBytes = (host) => {
18012
+ const parts = host.split(".");
18013
+ return parts.length === 4 && parts.every((part) => IPV4_OCTET_RE.test(part) && Number(part) <= 255) ? parts.map(Number) : null;
18014
+ };
18015
+ var IPV6_GROUP_RE = /^[0-9a-f]{1,4}$/i;
18016
+ var ipv6ToBytes = (host) => {
18017
+ const halves = host.split("::");
18018
+ if (halves.length > 2) {
18019
+ return null;
18020
+ }
18021
+ const groups = halves[0] ? halves[0].split(":") : [];
18022
+ if (halves.length === 2) {
18023
+ const rear = halves[1] ? halves[1].split(":") : [];
18024
+ const missing = 8 - groups.length - rear.length;
18025
+ if (missing < 1) {
18026
+ return null;
18027
+ }
18028
+ groups.push(...new Array(missing).fill("0"), ...rear);
18029
+ }
18030
+ if (groups.length !== 8 || groups.some((group) => !IPV6_GROUP_RE.test(group))) {
18031
+ return null;
18032
+ }
18033
+ return groups.flatMap((group) => {
18034
+ const value = Number.parseInt(group, 16);
18035
+ return [value >> 8 & 255, value & 255];
18036
+ });
18037
+ };
18038
+ var ipToBytes = (host) => {
18039
+ if (typeof host !== "string" || !host) {
18040
+ return null;
18041
+ }
18042
+ return host.indexOf(":") !== -1 ? ipv6ToBytes(host) : ipv4ToBytes(host);
18043
+ };
17854
18044
  var normalizeNoProxyHost = (hostname) => {
17855
18045
  if (!hostname) {
17856
18046
  return hostname;
@@ -17858,13 +18048,90 @@ var normalizeNoProxyHost = (hostname) => {
17858
18048
  if (hostname.charAt(0) === "[" && hostname.charAt(hostname.length - 1) === "]") {
17859
18049
  hostname = hostname.slice(1, -1);
17860
18050
  }
17861
- const trimmed = hostname.replace(/\.+$/, "");
18051
+ const trimmed = trimTrailingDots(hostname);
17862
18052
  const ipv4 = normalizeIPAddress(trimmed);
17863
18053
  if (ipv4 !== trimmed) {
17864
18054
  return ipv4;
17865
18055
  }
17866
18056
  return unmapIPv4MappedIPv6(trimmed);
17867
18057
  };
18058
+ var normalizeCidrBase = (input) => {
18059
+ let base = input;
18060
+ const startsBracket = base.charAt(0) === "[";
18061
+ const endsBracket = base.charAt(base.length - 1) === "]";
18062
+ const hasBracket = base.includes("[") || base.includes("]");
18063
+ if (startsBracket || endsBracket) {
18064
+ if (!startsBracket || !endsBracket) {
18065
+ return null;
18066
+ }
18067
+ base = base.slice(1, -1);
18068
+ if (base.indexOf(":") === -1 || base.includes("[") || base.includes("]")) {
18069
+ return null;
18070
+ }
18071
+ } else if (hasBracket) {
18072
+ return null;
18073
+ }
18074
+ if (!base || base.charAt(base.length - 1) === ".") {
18075
+ return null;
18076
+ }
18077
+ const wasIPv6 = base.indexOf(":") !== -1;
18078
+ if (wasIPv6) {
18079
+ try {
18080
+ base = new URL(`http://[${base}]/`).hostname.slice(1, -1);
18081
+ } catch (_err) {
18082
+ return null;
18083
+ }
18084
+ } else {
18085
+ base = normalizeIPAddress(base);
18086
+ if (!ipv4ToBytes(base)) {
18087
+ return null;
18088
+ }
18089
+ }
18090
+ return { normalized: unmapIPv4MappedIPv6(base), wasIPv6 };
18091
+ };
18092
+ var CIDR_ENTRY_RE = /^(.+)\/(0|[1-9]\d{0,2})$/;
18093
+ var parseCidrEntry = (entry) => {
18094
+ if (entry.indexOf("/") === -1) {
18095
+ return void 0;
18096
+ }
18097
+ const match = CIDR_ENTRY_RE.exec(entry);
18098
+ if (!match) {
18099
+ return null;
18100
+ }
18101
+ let prefix = Number(match[2]);
18102
+ const parsedBase = normalizeCidrBase(match[1]);
18103
+ if (!parsedBase) {
18104
+ return null;
18105
+ }
18106
+ const { normalized, wasIPv6 } = parsedBase;
18107
+ if (wasIPv6 && normalized.indexOf(":") === -1) {
18108
+ if (prefix < 96) {
18109
+ return null;
18110
+ }
18111
+ prefix -= 96;
18112
+ }
18113
+ const bytes = ipToBytes(normalized);
18114
+ if (!bytes || prefix > bytes.length * 8) {
18115
+ return null;
18116
+ }
18117
+ return { bytes, prefix };
18118
+ };
18119
+ var isInSubnet = (addressBytes, networkBytes, prefix) => {
18120
+ const fullBytes = prefix >> 3;
18121
+ for (let i2 = 0; i2 < fullBytes; i2++) {
18122
+ if (addressBytes[i2] !== networkBytes[i2]) {
18123
+ return false;
18124
+ }
18125
+ }
18126
+ const remainingBits = prefix & 7;
18127
+ if (remainingBits) {
18128
+ const mask2 = 255 << 8 - remainingBits & 255;
18129
+ if ((addressBytes[fullBytes] & mask2) !== (networkBytes[fullBytes] & mask2)) {
18130
+ return false;
18131
+ }
18132
+ }
18133
+ return true;
18134
+ };
17868
18135
  function shouldBypassProxy(location) {
17869
18136
  let parsed;
17870
18137
  try {
@@ -17881,6 +18148,7 @@ function shouldBypassProxy(location) {
17881
18148
  }
17882
18149
  const port = Number.parseInt(parsed.port, 10) || DEFAULT_PORTS2[parsed.protocol.split(":", 1)[0]] || 0;
17883
18150
  const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase());
18151
+ const hostnameBytes = ipToBytes(hostname);
17884
18152
  return noProxy.split(/[\s,]+/).some((entry) => {
17885
18153
  if (!entry) {
17886
18154
  return false;
@@ -17888,6 +18156,10 @@ function shouldBypassProxy(location) {
17888
18156
  if (entry === "*") {
17889
18157
  return true;
17890
18158
  }
18159
+ const cidr = parseCidrEntry(entry);
18160
+ if (cidr !== void 0) {
18161
+ return cidr !== null && !!hostnameBytes && hostnameBytes.length === cidr.bytes.length && isInSubnet(hostnameBytes, cidr.bytes, cidr.prefix);
18162
+ }
17891
18163
  let [entryHost, entryPort] = parseNoProxyEntry(entry);
17892
18164
  entryHost = normalizeNoProxyHost(entryHost);
17893
18165
  if (!entryHost) {
@@ -17973,7 +18245,8 @@ function throttle(fn, freq) {
17973
18245
  }
17974
18246
  };
17975
18247
  const flush = () => lastArgs && invoke(lastArgs);
17976
- return [throttled, flush];
18248
+ const flushWith = (...args) => invoke(args);
18249
+ return [throttled, flush, flushWith];
17977
18250
  }
17978
18251
  var throttle_default = throttle;
17979
18252
 
@@ -17982,7 +18255,7 @@ var progressEventReducer = (listener, isDownloadStream, freq = 3) => {
17982
18255
  let bytesNotified = 0;
17983
18256
  const _speedometer = speedometer_default(50, 250);
17984
18257
  return throttle_default((e) => {
17985
- if (!e || typeof e.loaded !== "number") {
18258
+ if (!e || !utils_default.isNumber(e.loaded)) {
17986
18259
  return;
17987
18260
  }
17988
18261
  const rawLoaded = e.loaded;
@@ -18143,6 +18416,12 @@ var { http: httpFollow, https: httpsFollow } = import_follow_redirects.default;
18143
18416
  var isHttps = /https:?/;
18144
18417
  var kAxiosSocketListener = /* @__PURE__ */ Symbol("axios.http.socketListener");
18145
18418
  var kAxiosCurrentReq = /* @__PURE__ */ Symbol("axios.http.currentReq");
18419
+ function handleSocketError(err) {
18420
+ const current = this[kAxiosCurrentReq];
18421
+ if (current && !current.destroyed) {
18422
+ current.destroy(err);
18423
+ }
18424
+ }
18146
18425
  var kAxiosInstalledTunnel = /* @__PURE__ */ Symbol("axios.http.installedTunnel");
18147
18426
  var tunnelingAgentCache = /* @__PURE__ */ new Map();
18148
18427
  var tunnelingAgentCacheUser = /* @__PURE__ */ new WeakMap();
@@ -18245,10 +18524,10 @@ function isSameOriginRedirect(redirectOptions, requestDetails) {
18245
18524
  return false;
18246
18525
  }
18247
18526
  }
18248
- function setProxy(options, configProxy, location, isRedirect, configHttpsAgent, configHttpAgent) {
18527
+ function setProxy(options, configProxy, location, isRedirect, configHttpsAgent, configHttpAgent, allowEnvProxy = true) {
18249
18528
  let proxy = configProxy;
18250
18529
  const proxyEnvAgent = getProxyEnvAgent(options, configHttpAgent, configHttpsAgent);
18251
- if (!proxy && proxy !== false && !isNodeEnvProxyEnabled(proxyEnvAgent)) {
18530
+ if (!proxy && proxy !== false && allowEnvProxy && !isNodeEnvProxyEnabled(proxyEnvAgent)) {
18252
18531
  const proxyUrl = getProxyForUrl(location);
18253
18532
  if (proxyUrl) {
18254
18533
  if (!shouldBypassProxy(location)) {
@@ -18345,9 +18624,13 @@ function setProxy(options, configProxy, location, isRedirect, configHttpsAgent,
18345
18624
  redirectOptions.href,
18346
18625
  true,
18347
18626
  configHttpsAgent,
18348
- configHttpAgent
18627
+ configHttpAgent,
18628
+ allowEnvProxy
18349
18629
  );
18350
18630
  };
18631
+ return Boolean(
18632
+ proxy || configProxy !== false && allowEnvProxy && isNodeEnvProxyEnabled(proxyEnvAgent)
18633
+ );
18351
18634
  }
18352
18635
  var isHttpAdapterSupported = typeof process !== "undefined" && utils_default.kindOf(process) === "process";
18353
18636
  var wrapAsync = (asyncExecutor) => {
@@ -18372,7 +18655,7 @@ var wrapAsync = (asyncExecutor) => {
18372
18655
  };
18373
18656
  var resolveFamily = ({ address, family }) => {
18374
18657
  if (!utils_default.isString(address)) {
18375
- throw TypeError("address must be a string");
18658
+ throw new AxiosError_default("address must be a string", AxiosError_default.ERR_BAD_OPTION_VALUE);
18376
18659
  }
18377
18660
  return {
18378
18661
  address,
@@ -18380,6 +18663,30 @@ var resolveFamily = ({ address, family }) => {
18380
18663
  };
18381
18664
  };
18382
18665
  var buildAddressEntry = (address, family) => resolveFamily(utils_default.isObject(address) ? address : { address, family });
18666
+ var normalizedLookupCache = /* @__PURE__ */ new WeakMap();
18667
+ var normalizeLookup = (lookup) => {
18668
+ let normalized = normalizedLookupCache.get(lookup);
18669
+ if (normalized) {
18670
+ return normalized;
18671
+ }
18672
+ const callbackLookup = callbackify_default(lookup, (value) => utils_default.isArray(value) ? value : [value]);
18673
+ normalized = (hostname, opt, cb) => {
18674
+ callbackLookup(hostname, opt, (err, arg0, arg1) => {
18675
+ if (err) {
18676
+ return cb(err);
18677
+ }
18678
+ let addresses;
18679
+ try {
18680
+ addresses = utils_default.isArray(arg0) ? arg0.map((addr) => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
18681
+ } catch (error) {
18682
+ return cb(error);
18683
+ }
18684
+ opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
18685
+ });
18686
+ };
18687
+ normalizedLookupCache.set(lookup, normalized);
18688
+ return normalized;
18689
+ };
18383
18690
  var http2Transport = {
18384
18691
  request(options, cb) {
18385
18692
  const authority = options.protocol + "//" + options.hostname + ":" + (options.port || (options.protocol === "https:" ? 443 : 80));
@@ -18416,6 +18723,7 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
18416
18723
  let family = own2("family");
18417
18724
  let httpVersion = own2("httpVersion");
18418
18725
  if (httpVersion === void 0) httpVersion = 1;
18726
+ const rawHttpVersion = httpVersion;
18419
18727
  let http2Options = own2("http2Options");
18420
18728
  const httpAgent = own2("httpAgent");
18421
18729
  const httpsAgent = own2("httpsAgent");
@@ -18432,25 +18740,32 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
18432
18740
  let rejected = false;
18433
18741
  let req;
18434
18742
  let connectPhaseTimer;
18435
- httpVersion = +httpVersion;
18743
+ try {
18744
+ httpVersion = +httpVersion;
18745
+ } catch (err) {
18746
+ throw new AxiosError_default(
18747
+ "Invalid protocol version: value is not a number",
18748
+ AxiosError_default.ERR_BAD_OPTION_VALUE,
18749
+ config
18750
+ );
18751
+ }
18436
18752
  if (Number.isNaN(httpVersion)) {
18437
- throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);
18753
+ throw new AxiosError_default(
18754
+ `Invalid protocol version: '${rawHttpVersion}' is not a number`,
18755
+ AxiosError_default.ERR_BAD_OPTION_VALUE,
18756
+ config
18757
+ );
18438
18758
  }
18439
18759
  if (httpVersion !== 1 && httpVersion !== 2) {
18440
- throw TypeError(`Unsupported protocol version '${httpVersion}'`);
18760
+ throw new AxiosError_default(
18761
+ `Unsupported protocol version '${httpVersion}'`,
18762
+ AxiosError_default.ERR_BAD_OPTION_VALUE,
18763
+ config
18764
+ );
18441
18765
  }
18442
18766
  const isHttp2 = httpVersion === 2;
18443
18767
  if (lookup) {
18444
- const _lookup = callbackify_default(lookup, (value) => utils_default.isArray(value) ? value : [value]);
18445
- lookup = (hostname, opt, cb) => {
18446
- _lookup(hostname, opt, (err, arg0, arg1) => {
18447
- if (err) {
18448
- return cb(err);
18449
- }
18450
- const addresses = utils_default.isArray(arg0) ? arg0.map((addr) => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
18451
- opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
18452
- });
18453
- };
18768
+ lookup = normalizeLookup(lookup);
18454
18769
  }
18455
18770
  const abortEmitter = new import_events.EventEmitter();
18456
18771
  function abort(reason) {
@@ -18693,6 +19008,9 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
18693
19008
  utils_default.hasOwnProp(transitional2, "advertiseZstdAcceptEncoding") && transitional2.advertiseZstdAcceptEncoding === true ? ACCEPT_ENCODING_WITH_ZSTD : ACCEPT_ENCODING,
18694
19009
  false
18695
19010
  );
19011
+ if (isHttp2 && lookup) {
19012
+ http2Options = Object.assign(/* @__PURE__ */ Object.create(null), http2Options, { lookup });
19013
+ }
18696
19014
  const options = Object.assign(/* @__PURE__ */ Object.create(null), {
18697
19015
  path: path6,
18698
19016
  method,
@@ -18703,9 +19021,11 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
18703
19021
  family,
18704
19022
  beforeRedirect: dispatchBeforeRedirect,
18705
19023
  beforeRedirects: /* @__PURE__ */ Object.create(null),
18706
- http2Options
19024
+ http2Options,
19025
+ createConnection: void 0
18707
19026
  });
18708
19027
  !utils_default.isUndefined(lookup) && (options.lookup = lookup);
19028
+ let proxyApplied = false;
18709
19029
  if (socketPath) {
18710
19030
  if (typeof socketPath !== "string") {
18711
19031
  return reject(
@@ -18733,13 +19053,17 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
18733
19053
  } else {
18734
19054
  options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;
18735
19055
  options.port = parsed.port;
18736
- setProxy(
19056
+ proxyApplied = setProxy(
18737
19057
  options,
18738
19058
  configProxy,
18739
19059
  protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options.path,
18740
19060
  false,
18741
19061
  httpsAgent,
18742
- httpAgent
19062
+ httpAgent,
19063
+ // The HTTP/2 transport connects independently of HTTP/1 agents, so it
19064
+ // cannot apply either axios-resolved or agent-local environment proxies.
19065
+ // Explicit proxy config is still processed and rejected below.
19066
+ !isHttp2
18743
19067
  );
18744
19068
  }
18745
19069
  let transport;
@@ -18750,6 +19074,15 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
18750
19074
  options.agent = isHttpsRequest ? httpsAgent : httpAgent;
18751
19075
  }
18752
19076
  if (isHttp2) {
19077
+ if (proxyApplied) {
19078
+ return reject(
19079
+ new AxiosError_default(
19080
+ "HTTP/2 requests with a proxy are not supported",
19081
+ AxiosError_default.ERR_NOT_SUPPORT,
19082
+ config
19083
+ )
19084
+ );
19085
+ }
18753
19086
  transport = http2Transport;
18754
19087
  } else {
18755
19088
  const configTransport = own2("transport");
@@ -18837,7 +19170,11 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
18837
19170
  transformStream,
18838
19171
  progressEventDecorator(
18839
19172
  responseLength,
18840
- progressEventReducer(asyncDecorator(onDownloadProgress, scheduleProgress), true, 3)
19173
+ progressEventReducer(
19174
+ asyncDecorator(onDownloadProgress, scheduleProgress),
19175
+ true,
19176
+ 3
19177
+ )
18841
19178
  )
18842
19179
  )
18843
19180
  );
@@ -18986,12 +19323,7 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) {
18986
19323
  socket.setKeepAlive(true, 1e3 * 60);
18987
19324
  }
18988
19325
  if (!socket[kAxiosSocketListener]) {
18989
- socket.on("error", function handleSocketError(err) {
18990
- const current = socket[kAxiosCurrentReq];
18991
- if (current && !current.destroyed) {
18992
- current.destroy(err);
18993
- }
18994
- });
19326
+ socket.on("error", handleSocketError);
18995
19327
  socket[kAxiosSocketListener] = true;
18996
19328
  }
18997
19329
  socket[kAxiosCurrentReq] = req;
@@ -19236,7 +19568,7 @@ function mergeConfig(config1, config2) {
19236
19568
  transformResponse: defaultToConfig2,
19237
19569
  paramsSerializer: defaultToConfig2,
19238
19570
  timeout: defaultToConfig2,
19239
- timeoutMessage: defaultToConfig2,
19571
+ timeoutErrorMessage: defaultToConfig2,
19240
19572
  withCredentials: defaultToConfig2,
19241
19573
  withXSRFToken: defaultToConfig2,
19242
19574
  adapter: defaultToConfig2,
@@ -19313,10 +19645,11 @@ function resolveConfig(config) {
19313
19645
  }
19314
19646
  }
19315
19647
  if (utils_default.isFormData(data)) {
19648
+ const getHeaders = utils_default.getSafeProp(data, "getHeaders");
19316
19649
  if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv || utils_default.isReactNative(data)) {
19317
19650
  headers.setContentType(void 0);
19318
- } else if (utils_default.isFunction(data.getHeaders)) {
19319
- setFormDataHeaders(headers, data.getHeaders(), own2("formDataHeaderPolicy"));
19651
+ } else if (utils_default.isFunction(getHeaders)) {
19652
+ setFormDataHeaders(headers, getHeaders.call(data), own2("formDataHeaderPolicy"));
19320
19653
  }
19321
19654
  }
19322
19655
  if (platform_default.hasStandardBrowserEnv) {
@@ -19345,7 +19678,7 @@ var xhr_default = isXHRAdapterSupported && function(config) {
19345
19678
  let { responseType, onUploadProgress, onDownloadProgress } = _config;
19346
19679
  let onCanceled;
19347
19680
  let uploadThrottled, downloadThrottled;
19348
- let flushUpload, flushDownload;
19681
+ let flushUpload, flushDownload, flushDownloadWithEvent;
19349
19682
  function done() {
19350
19683
  flushUpload && flushUpload();
19351
19684
  flushDownload && flushDownload();
@@ -19355,7 +19688,27 @@ var xhr_default = isXHRAdapterSupported && function(config) {
19355
19688
  let request = new XMLHttpRequest();
19356
19689
  request.open(_config.method.toUpperCase(), _config.url, true);
19357
19690
  request.timeout = _config.timeout;
19358
- function onloadend() {
19691
+ function onloadend(event) {
19692
+ if (!request) {
19693
+ return;
19694
+ }
19695
+ if (request.status === 0 && (parseProtocol(normalizeURLForProtocolCheck(_config.url)) || parseProtocol(platform_default.origin)) !== "file" && !(request.responseURL && request.responseURL.startsWith("file:"))) {
19696
+ reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config, request));
19697
+ done();
19698
+ request = null;
19699
+ return;
19700
+ }
19701
+ try {
19702
+ if (event) {
19703
+ flushDownloadWithEvent && flushDownloadWithEvent(event);
19704
+ } else {
19705
+ flushDownload && flushDownload();
19706
+ }
19707
+ } catch (err) {
19708
+ setTimeout(() => {
19709
+ throw err;
19710
+ });
19711
+ }
19359
19712
  if (!request) {
19360
19713
  return;
19361
19714
  }
@@ -19443,7 +19796,10 @@ var xhr_default = isXHRAdapterSupported && function(config) {
19443
19796
  request.responseType = _config.responseType;
19444
19797
  }
19445
19798
  if (onDownloadProgress) {
19446
- [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
19799
+ [downloadThrottled, flushDownload, flushDownloadWithEvent] = progressEventReducer(
19800
+ onDownloadProgress,
19801
+ true
19802
+ );
19447
19803
  request.addEventListener("progress", downloadThrottled);
19448
19804
  }
19449
19805
  if (onUploadProgress && request.upload) {
@@ -19613,6 +19969,17 @@ var trackStream = (stream4, chunkSize, onProgress, onFinish) => {
19613
19969
 
19614
19970
  // node_modules/axios/lib/adapters/fetch.js
19615
19971
  var DEFAULT_CHUNK_SIZE = 64 * 1024;
19972
+ var DEFAULT_REQUEST_OPTIONS = {
19973
+ cache: "default",
19974
+ redirect: "follow",
19975
+ referrer: "about:client",
19976
+ referrerPolicy: "",
19977
+ mode: "cors",
19978
+ integrity: "",
19979
+ keepalive: false,
19980
+ priority: "auto",
19981
+ window: null
19982
+ };
19616
19983
  var { isFunction: isFunction2 } = utils_default;
19617
19984
  var encodeUTF82 = (str) => encodeURIComponent(str).replace(
19618
19985
  /%([0-9A-F]{2})/gi,
@@ -19743,7 +20110,8 @@ var factory = (env) => {
19743
20110
  withCredentials = "same-origin",
19744
20111
  fetchOptions,
19745
20112
  maxContentLength,
19746
- maxBodyLength
20113
+ maxBodyLength,
20114
+ maxRedirects
19747
20115
  } = resolveConfig_default(config);
19748
20116
  const hasMaxContentLength = utils_default.isNumber(maxContentLength) && maxContentLength > -1;
19749
20117
  const hasMaxBodyLength = utils_default.isNumber(maxBodyLength) && maxBodyLength > -1;
@@ -19873,17 +20241,44 @@ var factory = (env) => {
19873
20241
  }
19874
20242
  }
19875
20243
  headers.set("User-Agent", "axios/" + VERSION, false);
19876
- const resolvedOptions = {
19877
- ...fetchOptions,
20244
+ const safeFetchOptions = fetchOptions == null ? fetchOptions : Object.assign(/* @__PURE__ */ Object.create(null), fetchOptions);
20245
+ if (safeFetchOptions) {
20246
+ delete safeFetchOptions.body;
20247
+ delete safeFetchOptions.headers;
20248
+ delete safeFetchOptions.method;
20249
+ delete safeFetchOptions.signal;
20250
+ delete safeFetchOptions.duplex;
20251
+ delete safeFetchOptions.credentials;
20252
+ }
20253
+ const resolvedOptions = Object.assign(/* @__PURE__ */ Object.create(null), safeFetchOptions, {
19878
20254
  signal: composedSignal,
19879
20255
  method: method.toUpperCase(),
19880
20256
  headers: toByteStringHeaderObject(headers.normalize()),
19881
20257
  body: data,
19882
20258
  duplex: "half",
19883
20259
  credentials: isCredentialsSupported ? withCredentials : void 0
19884
- };
20260
+ });
20261
+ if (isRequestSupported) {
20262
+ utils_default.forEach(DEFAULT_REQUEST_OPTIONS, (value, key) => {
20263
+ if (resolvedOptions[key] === void 0) {
20264
+ resolvedOptions[key] = value;
20265
+ }
20266
+ });
20267
+ if (resolvedOptions.signal === void 0) {
20268
+ resolvedOptions.signal = null;
20269
+ }
20270
+ if (resolvedOptions.body === void 0) {
20271
+ resolvedOptions.body = null;
20272
+ }
20273
+ }
20274
+ if (maxRedirects === 0) {
20275
+ resolvedOptions.redirect = "manual";
20276
+ if (safeFetchOptions) {
20277
+ safeFetchOptions.redirect = "manual";
20278
+ }
20279
+ }
19885
20280
  request = isRequestSupported && new Request(url2, resolvedOptions);
19886
- let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url2, resolvedOptions));
20281
+ let response = await (isRequestSupported ? _fetch(request, safeFetchOptions) : _fetch(url2, resolvedOptions));
19887
20282
  const responseHeaders = AxiosHeaders_default.from(response.headers);
19888
20283
  if (hasMaxContentLength) {
19889
20284
  const declaredLength = utils_default.toFiniteNumber(responseHeaders.getContentLength());
@@ -20102,9 +20497,10 @@ function throwIfCancellationRequested(config) {
20102
20497
  throw new CanceledError_default(null, config);
20103
20498
  }
20104
20499
  }
20105
- function dispatchRequest(config) {
20500
+ function dispatchRequest(_config) {
20501
+ const config = utils_default.toSafeFlatObject(_config);
20106
20502
  throwIfCancellationRequested(config);
20107
- config.headers = AxiosHeaders_default.from(config.headers);
20503
+ config.headers = AxiosHeaders_default.from(utils_default.getSafeProp(config, "headers"));
20108
20504
  config.data = transformData.call(config, config.transformRequest);
20109
20505
  if (["post", "put", "patch"].indexOf(config.method) !== -1) {
20110
20506
  config.headers.setContentType("application/x-www-form-urlencoded", false);
@@ -20234,16 +20630,15 @@ var Axios = class {
20234
20630
  return await this._request(configOrUrl, config);
20235
20631
  } catch (err) {
20236
20632
  if (err instanceof Error) {
20237
- let dummy = {};
20238
- Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
20239
- const stack = (() => {
20240
- if (!dummy.stack) {
20241
- return "";
20242
- }
20243
- const firstNewlineIndex = dummy.stack.indexOf("\n");
20244
- return firstNewlineIndex === -1 ? "" : dummy.stack.slice(firstNewlineIndex + 1);
20245
- })();
20246
20633
  try {
20634
+ let dummy = {};
20635
+ Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
20636
+ const dummyStack = dummy.stack;
20637
+ let stack = "";
20638
+ if (typeof dummyStack === "string") {
20639
+ const firstNewlineIndex = dummyStack.indexOf("\n");
20640
+ stack = firstNewlineIndex === -1 ? "" : dummyStack.slice(firstNewlineIndex + 1);
20641
+ }
20247
20642
  if (!err.stack) {
20248
20643
  err.stack = stack;
20249
20644
  } else if (stack) {
@@ -20313,9 +20708,9 @@ var Axios = class {
20313
20708
  },
20314
20709
  true
20315
20710
  );
20316
- config.method = (config.method || this.defaults.method || "get").toLowerCase();
20711
+ config.method = (utils_default.getSafeProp(config, "method") || utils_default.getSafeProp(this.defaults, "method") || "get").toLowerCase();
20317
20712
  let contextHeaders = headers && utils_default.merge(headers.common, headers[config.method]);
20318
- headers && utils_default.forEach(["delete", "get", "head", "post", "put", "patch", "query", "common"], (method) => {
20713
+ headers && utils_default.forEach(methodList_default.concat("common"), (method) => {
20319
20714
  delete headers[method];
20320
20715
  });
20321
20716
  config.headers = AxiosHeaders_default.concat(contextHeaders, headers);
@@ -20578,14 +20973,22 @@ var HttpStatusCode = {
20578
20973
  Gone: 410,
20579
20974
  LengthRequired: 411,
20580
20975
  PreconditionFailed: 412,
20976
+ /**
20977
+ * @deprecated Use `ContentTooLarge` instead.
20978
+ */
20581
20979
  PayloadTooLarge: 413,
20980
+ ContentTooLarge: 413,
20582
20981
  UriTooLong: 414,
20583
20982
  UnsupportedMediaType: 415,
20584
20983
  RangeNotSatisfiable: 416,
20585
20984
  ExpectationFailed: 417,
20586
20985
  ImATeapot: 418,
20587
20986
  MisdirectedRequest: 421,
20987
+ /**
20988
+ * @deprecated Use `UnprocessableContent` instead.
20989
+ */
20588
20990
  UnprocessableEntity: 422,
20991
+ UnprocessableContent: 422,
20589
20992
  Locked: 423,
20590
20993
  FailedDependency: 424,
20591
20994
  TooEarly: 425,
@@ -20614,7 +21017,9 @@ var HttpStatusCode = {
20614
21017
  InvalidSslCertificate: 526
20615
21018
  };
20616
21019
  Object.entries(HttpStatusCode).forEach(([key, value]) => {
20617
- HttpStatusCode[value] = key;
21020
+ if (HttpStatusCode[value] === void 0) {
21021
+ HttpStatusCode[value] = key;
21022
+ }
20618
21023
  });
20619
21024
  var HttpStatusCode_default = HttpStatusCode;
20620
21025
 
@@ -20684,18 +21089,35 @@ var AssinafyError = class extends Error {
20684
21089
  var ApiError = class _ApiError extends AssinafyError {
20685
21090
  statusCode;
20686
21091
  responseData;
21092
+ /** Bearer challenge, including insufficient_scope and resource_metadata when provided. */
21093
+ wwwAuthenticate;
21094
+ /** Server retry delay (seconds or HTTP date), when provided. */
21095
+ retryAfter;
20687
21096
  constructor(message, statusCode, responseData = null, options) {
20688
21097
  super(message, { statusCode, responseData }, options);
20689
21098
  this.name = "ApiError";
20690
21099
  this.statusCode = statusCode;
20691
21100
  this.responseData = responseData;
21101
+ this.wwwAuthenticate = options?.wwwAuthenticate;
21102
+ this.retryAfter = options?.retryAfter;
20692
21103
  }
20693
- static fromResponse(statusCode, responseData) {
21104
+ static fromResponse(statusCode, responseData, headers = {}) {
21105
+ if (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {
21106
+ const text2 = (Buffer.isBuffer(responseData) ? responseData : Buffer.from(responseData)).toString("utf8");
21107
+ try {
21108
+ responseData = JSON.parse(text2);
21109
+ } catch {
21110
+ responseData = text2;
21111
+ }
21112
+ }
20694
21113
  const data = responseData ?? {};
20695
21114
  const rawMessage = data.message;
20696
21115
  const rawError = data.error;
20697
21116
  const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : "API request failed";
20698
- return new _ApiError(message, statusCode, responseData);
21117
+ return new _ApiError(message, statusCode, responseData, {
21118
+ wwwAuthenticate: typeof headers["www-authenticate"] === "string" ? headers["www-authenticate"] : void 0,
21119
+ retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0
21120
+ });
20699
21121
  }
20700
21122
  };
20701
21123
  var ValidationError = class extends AssinafyError {
@@ -20712,6 +21134,19 @@ var NetworkError = class extends AssinafyError {
20712
21134
  this.name = "NetworkError";
20713
21135
  }
20714
21136
  };
21137
+ var PartialWorkflowError = class extends AssinafyError {
21138
+ /** The document that was uploaded before the failure, if any. */
21139
+ documentId;
21140
+ /** IDs of every signer created (or reused) before the failure. */
21141
+ signerIds;
21142
+ constructor(message, created, options) {
21143
+ const signerIds = created.signerIds ?? [];
21144
+ super(message, { documentId: created.documentId, signerIds }, options);
21145
+ this.name = "PartialWorkflowError";
21146
+ this.documentId = created.documentId;
21147
+ this.signerIds = signerIds;
21148
+ }
21149
+ };
20715
21150
 
20716
21151
  // src/api/utils.ts
20717
21152
  var DOCUMENT_ARTIFACT_NAMES = [
@@ -20721,6 +21156,13 @@ var DOCUMENT_ARTIFACT_NAMES = [
20721
21156
  "pades",
20722
21157
  "bundle"
20723
21158
  ];
21159
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
21160
+ var VERIFICATION_METHODS = [
21161
+ "Email",
21162
+ "Whatsapp",
21163
+ "DigitalCertificate"
21164
+ ];
21165
+ var NOTIFICATION_METHODS = ["Email", "Whatsapp"];
20724
21166
  function handleAssinafyResponse(response) {
20725
21167
  const resp = response;
20726
21168
  if (resp && typeof resp === "object" && resp.status !== void 0 && "data" in resp) {
@@ -20738,7 +21180,7 @@ function toSdkError(error, fallbackMessage) {
20738
21180
  if (axios_default.isAxiosError(error)) {
20739
21181
  const status = error.response?.status;
20740
21182
  if (status) {
20741
- return ApiError.fromResponse(status, error.response?.data ?? null);
21183
+ return ApiError.fromResponse(status, error.response?.data ?? null, error.response?.headers);
20742
21184
  }
20743
21185
  return new NetworkError(`${fallbackMessage}: ${error.message}`);
20744
21186
  }
@@ -20798,6 +21240,51 @@ function requireIso8601(value, name = "timestamp") {
20798
21240
  }
20799
21241
  return value;
20800
21242
  }
21243
+ function requireEmail(value) {
21244
+ if (!value || !EMAIL_RE.test(value)) {
21245
+ throw new ValidationError("Invalid email address", { email: value });
21246
+ }
21247
+ return value;
21248
+ }
21249
+ function validateSignerOptions(input) {
21250
+ if (input.verification_method !== void 0 && !VERIFICATION_METHODS.includes(input.verification_method)) {
21251
+ throw new ValidationError(
21252
+ `verification_method must be one of: ${VERIFICATION_METHODS.join(", ")}`
21253
+ );
21254
+ }
21255
+ if (input.notification_methods !== void 0 && (!Array.isArray(input.notification_methods) || input.notification_methods.some(
21256
+ (method) => !NOTIFICATION_METHODS.includes(method)
21257
+ ))) {
21258
+ throw new ValidationError(
21259
+ `notification_methods must contain only: ${NOTIFICATION_METHODS.join(", ")}`
21260
+ );
21261
+ }
21262
+ if (input.step !== void 0 && !Number.isInteger(input.step)) {
21263
+ throw new ValidationError("step must be an integer");
21264
+ }
21265
+ }
21266
+ function validateSigningSteps(signers) {
21267
+ const withSteps = signers.filter((signer) => signer.step !== void 0);
21268
+ if (withSteps.length > 0) {
21269
+ if (withSteps.length !== signers.length) {
21270
+ throw new ValidationError("step must be supplied for every signer when used");
21271
+ }
21272
+ const steps = [...new Set(withSteps.map((signer) => signer.step))].sort(
21273
+ (a2, b) => a2 - b
21274
+ );
21275
+ if (steps.some((step, index) => step !== index + 1)) {
21276
+ throw new ValidationError("steps must form a contiguous sequence starting at 1");
21277
+ }
21278
+ }
21279
+ validateDigitalCertificateSteps(signers);
21280
+ }
21281
+ function validateDigitalCertificateSteps(signers) {
21282
+ for (const signer of signers) {
21283
+ if (signer.verification_method === "DigitalCertificate" && signers.some((other) => other !== signer && (other.step ?? 1) === (signer.step ?? 1))) {
21284
+ throw new ValidationError("a DigitalCertificate signer must be alone in its signing step");
21285
+ }
21286
+ }
21287
+ }
20801
21288
  function documentStatsParams(params = {}) {
20802
21289
  if (params.granularity !== void 0 && !["monthly", "daily"].includes(params.granularity)) {
20803
21290
  throw new ValidationError("granularity must be monthly or daily");
@@ -20943,15 +21430,25 @@ function toInt(value) {
20943
21430
 
20944
21431
  // src/api/resources/assignments.ts
20945
21432
  function buildAssignmentPayload(payload, options = {}) {
21433
+ if (payload.method !== void 0 && payload.method !== "virtual" && payload.method !== "collect") {
21434
+ throw new ValidationError("method must be virtual or collect");
21435
+ }
20946
21436
  const signers = extractSignerRefs(payload);
20947
- if (signers.length === 0 && !options.allowEmptySigners) {
21437
+ if (signers.length === 0 && (!options.allowEmptySigners || (payload.method ?? "virtual") !== "collect")) {
20948
21438
  throw new ValidationError("At least one signer is required", {
20949
21439
  signers: payload.signers ?? payload.signer_ids ?? payload.signerIds
20950
21440
  });
20951
21441
  }
21442
+ if (payload.method === "collect" && !Array.isArray(payload.entries)) {
21443
+ throw new ValidationError("entries are required for collect assignments");
21444
+ }
21445
+ const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));
21446
+ if (!options.skipDigitalCertificateStepValidation) {
21447
+ validateSigningSteps(normalisedSigners);
21448
+ }
20952
21449
  return cleanParams({
20953
21450
  method: payload.method ?? "virtual",
20954
- signers: signers.map((ref) => normaliseSignerRef(ref, options)),
21451
+ signers: normalisedSigners,
20955
21452
  message: payload.message,
20956
21453
  expires_at: payload.expires_at === void 0 ? void 0 : requireIso8601(payload.expires_at, "expires_at"),
20957
21454
  copy_receivers: payload.copy_receivers,
@@ -20979,6 +21476,7 @@ function normaliseSignerRef(ref, options) {
20979
21476
  if (ref && typeof ref === "object") {
20980
21477
  const input = ref;
20981
21478
  const id = input.id ?? input.signer_id;
21479
+ validateSignerOptions(input);
20982
21480
  const normalised = cleanParams({
20983
21481
  id,
20984
21482
  verification_method: input.verification_method,
@@ -21036,14 +21534,16 @@ var AssignmentResource = class extends BaseResource {
21036
21534
  `/documents/${docId}/assignments/estimate-cost`,
21037
21535
  buildAssignmentPayload(payload, {
21038
21536
  allowSignersWithoutId: true,
21039
- allowEmptySigners: true
21537
+ allowEmptySigners: true,
21538
+ skipDigitalCertificateStepValidation: true
21040
21539
  })
21041
21540
  )
21042
21541
  );
21043
21542
  }
21044
21543
  /**
21045
21544
  * Update the expiration date of an existing assignment.
21046
- * Pass `null` to remove the expiration entirely.
21545
+ * The published API accepts an ISO 8601 timestamp. Deployments that support
21546
+ * clearing an expiration also accept `null`.
21047
21547
  */
21048
21548
  async resetExpiration(documentId, assignmentId, expiresAt) {
21049
21549
  const docId = this.requireId(documentId, "Document ID");
@@ -21378,24 +21878,24 @@ var DocumentResource = class extends BaseResource {
21378
21878
  );
21379
21879
  }
21380
21880
  /**
21381
- * Replace the document's tag set with `tags` (an array of tag names).
21382
- * Unknown names are auto-created; an empty array detaches all tags.
21881
+ * Replace the document's tag set with tag IDs. An empty array detaches all tags.
21882
+ * Values are forwarded unchanged for compatibility with deployments that also accept names.
21383
21883
  */
21384
21884
  async replaceTags(documentId, tags, accountId) {
21385
21885
  const accId = this.accountId(accountId);
21386
21886
  const docId = this.requireId(documentId, "Document ID");
21387
- if (!Array.isArray(tags)) throw new ValidationError("tags must be an array of tag names");
21887
+ if (!Array.isArray(tags)) throw new ValidationError("tags must be an array of tag IDs");
21388
21888
  return this.call(
21389
21889
  "Failed to replace document tags",
21390
21890
  () => this.http.put(`/accounts/${accId}/documents/${docId}/tags`, { tags })
21391
21891
  );
21392
21892
  }
21393
- /** Attach additional tags (by name) without removing existing ones. Idempotent. */
21893
+ /** Attach additional tag IDs without removing existing ones. */
21394
21894
  async addTags(documentId, tags, accountId) {
21395
21895
  const accId = this.accountId(accountId);
21396
21896
  const docId = this.requireId(documentId, "Document ID");
21397
21897
  if (!Array.isArray(tags) || tags.length === 0) {
21398
- throw new ValidationError("tags must be a non-empty array of tag names");
21898
+ throw new ValidationError("tags must be a non-empty array of tag IDs");
21399
21899
  }
21400
21900
  return this.call(
21401
21901
  "Failed to add document tags",
@@ -21425,7 +21925,14 @@ var DocumentResource = class extends BaseResource {
21425
21925
  async createFromTemplate(templateId, signers, options = {}, accountId) {
21426
21926
  const tmplId = this.requireId(templateId, "Template ID");
21427
21927
  const accId = this.accountId(accountId);
21928
+ validateTemplateSigners(signers, { requireId: true, singleNotification: true });
21428
21929
  if (options.expires_at !== void 0) requireIso8601(options.expires_at, "expires_at");
21930
+ if (options.editor_fields !== void 0 && (!Array.isArray(options.editor_fields) || options.editor_fields.some((field) => !field?.field_id || typeof field.value !== "string"))) {
21931
+ throw new ValidationError("editor_fields must contain field_id and value");
21932
+ }
21933
+ if (options.tags !== void 0 && (!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== "string" || !tag))) {
21934
+ throw new ValidationError("tags must contain non-empty tag names");
21935
+ }
21429
21936
  const body = { ...options, signers };
21430
21937
  this.logger.info("Creating document from template", { templateId: tmplId, accountId: accId });
21431
21938
  return this.call(
@@ -21437,6 +21944,7 @@ var DocumentResource = class extends BaseResource {
21437
21944
  async estimateCostFromTemplate(templateId, signers, accountId) {
21438
21945
  const tmplId = this.requireId(templateId, "Template ID");
21439
21946
  const accId = this.accountId(accountId);
21947
+ validateTemplateSigners(signers, { requireId: false, singleNotification: false });
21440
21948
  return this.call(
21441
21949
  "Failed to estimate cost from template",
21442
21950
  () => this.http.post(`/accounts/${accId}/templates/${tmplId}/documents/estimate-cost`, { signers })
@@ -21483,7 +21991,7 @@ var DocumentResource = class extends BaseResource {
21483
21991
  async sendToken(documentId, recipient, channel = "email") {
21484
21992
  const id = this.requireId(documentId, "Document ID");
21485
21993
  if (typeof recipient === "object") {
21486
- if (!recipient?.email) throw new ValidationError("email is required");
21994
+ requireEmail(recipient?.email);
21487
21995
  return this.call(
21488
21996
  "Failed to send signing token",
21489
21997
  () => this.http.put(
@@ -21494,6 +22002,10 @@ var DocumentResource = class extends BaseResource {
21494
22002
  );
21495
22003
  }
21496
22004
  if (!recipient) throw new ValidationError("recipient is required");
22005
+ if (channel !== "email" && channel !== "whatsapp") {
22006
+ throw new ValidationError("channel must be email or whatsapp");
22007
+ }
22008
+ if (channel === "email") requireEmail(recipient);
21497
22009
  return this.call(
21498
22010
  "Failed to send signing token",
21499
22011
  () => this.http.put(
@@ -21524,6 +22036,31 @@ var DocumentResource = class extends BaseResource {
21524
22036
  return { signed, total, pending, percentage };
21525
22037
  }
21526
22038
  };
22039
+ function validateTemplateSigners(signers, options) {
22040
+ if (!Array.isArray(signers)) throw new ValidationError("signers must be an array");
22041
+ for (const value of signers) {
22042
+ if (!value || typeof value !== "object") {
22043
+ throw new ValidationError("each template signer must be an object");
22044
+ }
22045
+ const signer = value;
22046
+ if (typeof signer.role_id !== "string" || !signer.role_id) {
22047
+ throw new ValidationError("each template signer requires role_id");
22048
+ }
22049
+ if ((options.requireId || signer.id !== void 0) && (typeof signer.id !== "string" || !signer.id)) {
22050
+ throw new ValidationError("each template signer requires a valid id");
22051
+ }
22052
+ validateSignerOptions(signer);
22053
+ if (options.requireId && signer.step !== void 0 && Number(signer.step) < 1) {
22054
+ throw new ValidationError("template signer step must be a positive integer");
22055
+ }
22056
+ if (options.singleNotification && Array.isArray(signer.notification_methods) && signer.notification_methods.length > 1) {
22057
+ throw new ValidationError("template signers accept at most one notification method");
22058
+ }
22059
+ }
22060
+ if (options.requireId) {
22061
+ validateSigningSteps(signers);
22062
+ }
22063
+ }
21527
22064
  async function loadSource(source) {
21528
22065
  if ("buffer" in source) {
21529
22066
  if (!source.fileName) {
@@ -21635,6 +22172,7 @@ var FieldsResource = class extends BaseResource {
21635
22172
  async validate(fieldId, value, options = {}) {
21636
22173
  const id = this.accountId(options.accountId);
21637
22174
  const fid = this.requireId(fieldId, "Field ID");
22175
+ if (value === void 0) throw new ValidationError("value is required");
21638
22176
  return this.call(
21639
22177
  "Failed to validate field value",
21640
22178
  () => this.http.post(
@@ -21649,6 +22187,11 @@ var FieldsResource = class extends BaseResource {
21649
22187
  if (!Array.isArray(entries) || entries.length === 0) {
21650
22188
  throw new ValidationError("entries must be a non-empty array");
21651
22189
  }
22190
+ if (entries.some(
22191
+ (entry) => !entry || typeof entry !== "object" || typeof entry.field_id !== "string" || !entry.field_id || entry.value === void 0
22192
+ )) {
22193
+ throw new ValidationError("each entry must contain field_id and value");
22194
+ }
21652
22195
  const id = this.accountId(options.accountId);
21653
22196
  return this.call(
21654
22197
  "Failed to validate field values",
@@ -21668,6 +22211,174 @@ function validationConfig(signerAccessCode) {
21668
22211
  return signerAccessCode ? signerAccessConfig(signerAccessCode) : void 0;
21669
22212
  }
21670
22213
 
22214
+ // src/api/resources/oauth.ts
22215
+ var import_node_crypto = require("crypto");
22216
+ var OAuthResource = class extends BaseResource {
22217
+ /** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */
22218
+ async metadata() {
22219
+ return this.call(
22220
+ "Failed to discover OAuth resource",
22221
+ () => this.http.get(
22222
+ "/.well-known/oauth-protected-resource",
22223
+ publicRequestConfig({
22224
+ baseURL: new URL(this.http.defaults.baseURL).origin
22225
+ })
22226
+ )
22227
+ );
22228
+ }
22229
+ /** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */
22230
+ async discovery(issuer) {
22231
+ const url2 = httpsUrl(issuer, "issuer");
22232
+ if (url2.search || url2.pathname !== "/") {
22233
+ throw new ValidationError("issuer must be an HTTPS origin");
22234
+ }
22235
+ const metadata = await this.call(
22236
+ "Failed to discover OAuth authorization server",
22237
+ () => this.http.get(
22238
+ `${url2.origin}/.well-known/oauth-authorization-server`,
22239
+ publicRequestConfig()
22240
+ )
22241
+ );
22242
+ if (metadata.issuer !== issuer) throw new ValidationError("OAuth issuer mismatch");
22243
+ httpsUrl(metadata.authorization_endpoint, "authorization_endpoint");
22244
+ return metadata;
22245
+ }
22246
+ /** Discover endpoints and create a fresh authorization URL, PKCE verifier, and state. */
22247
+ async authorize(options) {
22248
+ required(options.clientId, "clientId");
22249
+ httpsUrl(options.redirectUri, "redirectUri");
22250
+ if (!Array.isArray(options.scopes) || options.scopes.length === 0 || options.scopes.some(
22251
+ (scope) => typeof scope !== "string" || !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(scope)
22252
+ )) {
22253
+ throw new ValidationError("scopes must contain non-empty OAuth scope names");
22254
+ }
22255
+ const resource = await this.metadata();
22256
+ const issuer = resource.authorization_servers?.[0];
22257
+ if (!issuer) throw new ValidationError("OAuth metadata has no authorization server");
22258
+ httpsUrl(resource.resource, "resource");
22259
+ const server = await this.discovery(issuer);
22260
+ const codeVerifier = (0, import_node_crypto.randomBytes)(32).toString("base64url");
22261
+ const state = (0, import_node_crypto.randomBytes)(32).toString("base64url");
22262
+ const nonce = options.scopes.includes("openid") ? (0, import_node_crypto.randomBytes)(32).toString("base64url") : void 0;
22263
+ const url2 = new URL(server.authorization_endpoint);
22264
+ const params = {
22265
+ response_type: "code",
22266
+ client_id: options.clientId,
22267
+ redirect_uri: options.redirectUri,
22268
+ scope: options.scopes.join(" "),
22269
+ state,
22270
+ code_challenge: (0, import_node_crypto.createHash)("sha256").update(codeVerifier).digest("base64url"),
22271
+ code_challenge_method: "S256",
22272
+ resource: resource.resource
22273
+ };
22274
+ for (const [key, value] of Object.entries(params)) url2.searchParams.set(key, value);
22275
+ if (nonce) url2.searchParams.set("nonce", nonce);
22276
+ return {
22277
+ authorization_url: url2.toString(),
22278
+ code_verifier: codeVerifier,
22279
+ state,
22280
+ issuer,
22281
+ client_id: options.clientId,
22282
+ redirect_uri: options.redirectUri,
22283
+ resource: resource.resource,
22284
+ ...nonce ? { nonce } : {}
22285
+ };
22286
+ }
22287
+ /** Validate callback URI, state, and issuer before exchanging its one-time code. */
22288
+ async exchangeCode(callbackUrl, request, clientSecret) {
22289
+ const callback = httpsUrl(callbackUrl, "callbackUrl");
22290
+ const redirect = httpsUrl(request.redirect_uri, "redirect_uri");
22291
+ if (callback.origin !== redirect.origin || callback.pathname !== redirect.pathname || [...new Set(redirect.searchParams.keys())].some((key) => {
22292
+ const expected2 = redirect.searchParams.getAll(key);
22293
+ const actual2 = callback.searchParams.getAll(key);
22294
+ return expected2.length !== actual2.length || expected2.some((value, i2) => value !== actual2[i2]);
22295
+ })) {
22296
+ throw new ValidationError("OAuth callback does not match the registered redirect URI");
22297
+ }
22298
+ for (const key of ["state", "iss", "code", "error"]) {
22299
+ if (callback.searchParams.getAll(key).length > 1) {
22300
+ throw new ValidationError(`Duplicate OAuth callback parameter: ${key}`);
22301
+ }
22302
+ }
22303
+ const actual = Buffer.from(callback.searchParams.get("state") ?? "");
22304
+ const expected = Buffer.from(required(request.state, "state"));
22305
+ if (actual.length !== expected.length || !(0, import_node_crypto.timingSafeEqual)(actual, expected)) {
22306
+ throw new ValidationError("OAuth state mismatch");
22307
+ }
22308
+ if (callback.searchParams.get("iss") !== request.issuer) {
22309
+ throw new ValidationError("OAuth issuer mismatch");
22310
+ }
22311
+ if (callback.searchParams.has("error")) {
22312
+ throw new ValidationError("OAuth authorization was declined or failed");
22313
+ }
22314
+ return this.token({
22315
+ grant_type: "authorization_code",
22316
+ code: required(callback.searchParams.get("code"), "code"),
22317
+ client_id: request.client_id,
22318
+ client_secret: clientSecret,
22319
+ redirect_uri: request.redirect_uri,
22320
+ code_verifier: request.code_verifier,
22321
+ resource: request.resource
22322
+ });
22323
+ }
22324
+ /** `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body. */
22325
+ async token(payload) {
22326
+ required(payload.client_id, "client_id");
22327
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
22328
+ if (payload.resource !== void 0) httpsUrl(payload.resource, "resource");
22329
+ if (payload.grant_type === "authorization_code") {
22330
+ required(payload.code, "code");
22331
+ httpsUrl(payload.redirect_uri, "redirect_uri");
22332
+ if (typeof payload.code_verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)) {
22333
+ throw new ValidationError(
22334
+ "code_verifier must contain 43\u2013128 RFC 7636 unreserved characters"
22335
+ );
22336
+ }
22337
+ } else if (payload.grant_type === "refresh_token") {
22338
+ required(payload.refresh_token, "refresh_token");
22339
+ } else {
22340
+ throw new ValidationError("grant_type must be authorization_code or refresh_token");
22341
+ }
22342
+ return this.call(
22343
+ "OAuth token request failed",
22344
+ () => this.http.post("/oauth/token", payload, publicRequestConfig())
22345
+ );
22346
+ }
22347
+ /** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */
22348
+ async revoke(payload) {
22349
+ required(payload.client_id, "client_id");
22350
+ required(payload.token, "token");
22351
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
22352
+ if (payload.token_type_hint !== void 0 && !["access_token", "refresh_token"].includes(payload.token_type_hint)) {
22353
+ throw new ValidationError("token_type_hint must be access_token or refresh_token");
22354
+ }
22355
+ await this.call(
22356
+ "OAuth revocation failed",
22357
+ () => this.http.post("/oauth/revoke", payload, publicRequestConfig())
22358
+ );
22359
+ }
22360
+ /** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
22361
+ async userinfo() {
22362
+ return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
22363
+ }
22364
+ };
22365
+ function required(value, name) {
22366
+ if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
22367
+ return value;
22368
+ }
22369
+ function httpsUrl(value, name) {
22370
+ let url2;
22371
+ try {
22372
+ url2 = new URL(value);
22373
+ } catch {
22374
+ throw new ValidationError(`${name} must be an absolute HTTPS URL`);
22375
+ }
22376
+ if (url2.protocol !== "https:" || url2.username || url2.password || url2.hash) {
22377
+ throw new ValidationError(`${name} must use HTTPS without credentials or a fragment`);
22378
+ }
22379
+ return url2;
22380
+ }
22381
+
21671
22382
  // src/api/resources/signer-documents.ts
21672
22383
  var SignerDocumentsResource = class extends BaseResource {
21673
22384
  /** `GET /signers/{signer_id}/document?signer-access-code=…` */
@@ -21700,20 +22411,28 @@ var SignerDocumentsResource = class extends BaseResource {
21700
22411
  () => this.http.get(`/signers/${sid}/documents/search`, signerAccessConfig(code, { search }))
21701
22412
  );
21702
22413
  }
21703
- /** `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}?signer-access-code=…` */
22414
+ /**
22415
+ * Public `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`.
22416
+ * When an access code is supplied, the SDK first verifies that it belongs to
22417
+ * the requested signer for callers that want that additional check.
22418
+ */
21704
22419
  async download(signerId, documentId, artifactName, signerAccessCode) {
21705
22420
  const sid = this.requireId(signerId, "Signer ID");
21706
22421
  const did = this.requireId(documentId, "Document ID");
21707
22422
  const artifact = requireDocumentArtifactName(artifactName);
21708
- const code = this.requireId(signerAccessCode, "signer-access-code");
21709
- const signer = await this.self(code);
21710
- if (signer.id !== sid) {
21711
- throw new ValidationError("Signer access code does not match the signer ID");
22423
+ let config = publicRequestConfig();
22424
+ if (signerAccessCode !== void 0) {
22425
+ const code = this.requireId(signerAccessCode, "signer-access-code");
22426
+ const signer = await this.self(code);
22427
+ if (signer.id !== sid) {
22428
+ throw new ValidationError("Signer access code does not match the signer ID");
22429
+ }
22430
+ config = signerAccessConfig(code);
21712
22431
  }
21713
22432
  return this.callBinary(
21714
22433
  "Failed to download signer document",
21715
22434
  () => this.http.get(`/signers/${sid}/documents/${did}/download/${artifact}`, {
21716
- ...signerAccessConfig(code),
22435
+ ...config,
21717
22436
  responseType: "arraybuffer"
21718
22437
  })
21719
22438
  );
@@ -21738,7 +22457,7 @@ var SignerDocumentsResource = class extends BaseResource {
21738
22457
  if (!Array.isArray(documentIds) || documentIds.length === 0) {
21739
22458
  throw new ValidationError("documentIds must be a non-empty array");
21740
22459
  }
21741
- if (!declineReason) throw new ValidationError("declineReason is required");
22460
+ validateDeclineReason(declineReason);
21742
22461
  const code = this.requireId(signerAccessCode, "signer-access-code");
21743
22462
  return this.call(
21744
22463
  "Failed to decline multiple documents",
@@ -21868,7 +22587,7 @@ var SignerDocumentsResource = class extends BaseResource {
21868
22587
  const did = this.requireId(documentId, "Document ID");
21869
22588
  const aid = this.requireId(assignmentId, "Assignment ID");
21870
22589
  const code = this.requireId(signerAccessCode, "signer-access-code");
21871
- if (!declineReason) throw new ValidationError("declineReason is required");
22590
+ validateDeclineReason(declineReason);
21872
22591
  return this.call(
21873
22592
  "Failed to decline assignment",
21874
22593
  () => this.http.put(
@@ -21879,17 +22598,19 @@ var SignerDocumentsResource = class extends BaseResource {
21879
22598
  );
21880
22599
  }
21881
22600
  };
22601
+ function validateDeclineReason(value) {
22602
+ if (typeof value !== "string" || !value.trim()) {
22603
+ throw new ValidationError("declineReason is required");
22604
+ }
22605
+ if ([...value].length > 2e3) {
22606
+ throw new ValidationError("declineReason must contain at most 2000 characters");
22607
+ }
22608
+ }
21882
22609
 
21883
22610
  // src/api/resources/signers.ts
21884
- var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
21885
22611
  function validateCreateSignerPayload(payload) {
21886
22612
  if (!payload.full_name?.trim()) throw new ValidationError("Signer full name is required");
21887
- if (payload.email) assertEmail(payload.email);
21888
- }
21889
- function assertEmail(email) {
21890
- if (!email || !EMAIL_RE.test(email)) {
21891
- throw new ValidationError("Invalid email address", { email });
21892
- }
22613
+ if (payload.email !== void 0) requireEmail(payload.email);
21893
22614
  }
21894
22615
  var SignerResource = class extends BaseResource {
21895
22616
  /**
@@ -21952,6 +22673,10 @@ var SignerResource = class extends BaseResource {
21952
22673
  async update(signerId, payload, accountId) {
21953
22674
  const id = this.accountId(accountId);
21954
22675
  const sid = this.requireId(signerId, "Signer ID");
22676
+ if (payload.full_name !== void 0 && !payload.full_name.trim()) {
22677
+ throw new ValidationError("Signer full name cannot be blank");
22678
+ }
22679
+ if (payload.email !== void 0) requireEmail(payload.email);
21955
22680
  return this.call(
21956
22681
  "Failed to update signer",
21957
22682
  () => this.http.put(`/accounts/${id}/signers/${sid}`, normaliseSignerPayload(payload, true))
@@ -21968,11 +22693,15 @@ var SignerResource = class extends BaseResource {
21968
22693
  }
21969
22694
  /** Find a signer by email via the API's `search` parameter. Returns `null` if none match. */
21970
22695
  async findByEmail(email, accountId) {
21971
- assertEmail(email);
22696
+ requireEmail(email);
21972
22697
  try {
21973
- const { data } = await this.list({ search: email, per_page: 100 }, accountId);
21974
22698
  const lower = email.toLowerCase();
21975
- return data.find((s) => (s.email ?? "").toLowerCase() === lower) ?? null;
22699
+ for (let page = 1; ; page++) {
22700
+ const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
22701
+ const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
22702
+ if (match) return match;
22703
+ if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
22704
+ }
21976
22705
  } catch (err) {
21977
22706
  if (err instanceof ApiError && err.statusCode === 404) {
21978
22707
  return null;
@@ -22166,7 +22895,22 @@ var WebhookResource = class extends BaseResource {
22166
22895
  /** Register (or replace) the webhook subscription for the workspace. */
22167
22896
  async register(payload, accountId) {
22168
22897
  if (!payload.url) throw new ValidationError("Webhook URL is required");
22169
- if (!payload.email) throw new ValidationError("Webhook email is required");
22898
+ let webhookUrl;
22899
+ try {
22900
+ webhookUrl = new URL(payload.url);
22901
+ } catch {
22902
+ throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
22903
+ }
22904
+ if (webhookUrl.protocol !== "http:" && webhookUrl.protocol !== "https:") {
22905
+ throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
22906
+ }
22907
+ requireEmail(payload.email);
22908
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
22909
+ throw new ValidationError("Webhook events must contain non-empty strings");
22910
+ }
22911
+ if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
22912
+ throw new ValidationError("Webhook is_active must be a boolean");
22913
+ }
22170
22914
  const id = this.accountId(accountId);
22171
22915
  const body = {
22172
22916
  url: payload.url,
@@ -22327,7 +23071,7 @@ function validateNotificationSender(value) {
22327
23071
  }
22328
23072
 
22329
23073
  // src/api/support/webhook-verifier.ts
22330
- var import_node_crypto = require("crypto");
23074
+ var import_node_crypto2 = require("crypto");
22331
23075
  var WebhookVerifier = class {
22332
23076
  constructor(webhookSecret, options = {}) {
22333
23077
  this.webhookSecret = webhookSecret;
@@ -22340,14 +23084,14 @@ var WebhookVerifier = class {
22340
23084
  /** Returns `true` if `signature` is a valid HMAC of `payload` under the configured scheme. */
22341
23085
  verify(payload, signature) {
22342
23086
  if (!this.webhookSecret || !signature) return false;
22343
- const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
22344
- const expected = (0, import_node_crypto.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
22345
- const provided = signature.trim();
22346
- const a2 = Buffer.from(expected, "utf8");
22347
- const b = Buffer.from(provided, "utf8");
22348
- if (a2.length !== b.length) return false;
22349
23087
  try {
22350
- return (0, import_node_crypto.timingSafeEqual)(a2, b);
23088
+ const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
23089
+ const expected = (0, import_node_crypto2.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
23090
+ const provided = signature.trim();
23091
+ const a2 = Buffer.from(expected, "utf8");
23092
+ const b = Buffer.from(provided, "utf8");
23093
+ if (a2.length !== b.length) return false;
23094
+ return (0, import_node_crypto2.timingSafeEqual)(a2, b);
22351
23095
  } catch {
22352
23096
  return false;
22353
23097
  }
@@ -22366,7 +23110,8 @@ var WebhookVerifier = class {
22366
23110
  getEventType(event) {
22367
23111
  if (!event || typeof event !== "object") return null;
22368
23112
  const e = event;
22369
- return e.event ?? e.type ?? null;
23113
+ if (typeof e.event === "string") return e.event;
23114
+ return typeof e.type === "string" ? e.type : null;
22370
23115
  }
22371
23116
  /**
22372
23117
  * Extract the event data from an event envelope.
@@ -22388,6 +23133,9 @@ var WebhookVerifier = class {
22388
23133
 
22389
23134
  // src/api/client.ts
22390
23135
  var DEFAULT_BASE_URL = "https://api.assinafy.com.br/v1";
23136
+ function isLoopbackHost(hostname) {
23137
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(hostname);
23138
+ }
22391
23139
  var AssinafyClient = class _AssinafyClient {
22392
23140
  axiosInstance;
22393
23141
  defaultAccountId;
@@ -22401,6 +23149,7 @@ var AssinafyClient = class _AssinafyClient {
22401
23149
  templates;
22402
23150
  tags;
22403
23151
  auth;
23152
+ oauth;
22404
23153
  fields;
22405
23154
  users;
22406
23155
  signerDocuments;
@@ -22408,9 +23157,12 @@ var AssinafyClient = class _AssinafyClient {
22408
23157
  constructor(options) {
22409
23158
  if (!options.apiKey && !options.token && !options.allowUnauthenticated) {
22410
23159
  throw new ValidationError(
22411
- "An API key (options.apiKey) or legacy access token (options.token) is required."
23160
+ "An API key (options.apiKey) or access token (options.token) is required."
22412
23161
  );
22413
23162
  }
23163
+ if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout <= 0)) {
23164
+ throw new ValidationError("timeout must be a finite positive number");
23165
+ }
22414
23166
  this.defaultAccountId = options.accountId;
22415
23167
  this.logger = options.logger ?? createNoopLogger();
22416
23168
  this.webhookSecret = options.webhookSecret;
@@ -22421,13 +23173,17 @@ var AssinafyClient = class _AssinafyClient {
22421
23173
  } catch {
22422
23174
  throw new ValidationError("baseUrl must be an absolute HTTP(S) URL");
22423
23175
  }
22424
- if (!["https:", "http:"].includes(parsedBaseUrl.protocol)) {
22425
- throw new ValidationError("baseUrl must use HTTPS");
22426
- }
22427
- if (parsedBaseUrl.protocol !== "https:" && !options.allowInsecureHttp) {
22428
- throw new ValidationError(
22429
- "baseUrl must use HTTPS; set allowInsecureHttp only for isolated local development"
22430
- );
23176
+ if (parsedBaseUrl.protocol !== "https:") {
23177
+ if (parsedBaseUrl.protocol !== "http:" || !options.allowInsecureHttp) {
23178
+ throw new ValidationError(
23179
+ "baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server"
23180
+ );
23181
+ }
23182
+ if (!isLoopbackHost(parsedBaseUrl.hostname)) {
23183
+ throw new ValidationError(
23184
+ "allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)"
23185
+ );
23186
+ }
22431
23187
  }
22432
23188
  if (parsedBaseUrl.username || parsedBaseUrl.password) {
22433
23189
  throw new ValidationError("baseUrl must not contain embedded credentials");
@@ -22463,6 +23219,7 @@ var AssinafyClient = class _AssinafyClient {
22463
23219
  this.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);
22464
23220
  this.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);
22465
23221
  this.auth = new AuthenticationResource(this.axiosInstance, void 0, this.logger);
23222
+ this.oauth = new OAuthResource(this.axiosInstance, void 0, this.logger);
22466
23223
  this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
22467
23224
  this.users = new UsersResource(this.axiosInstance, void 0, this.logger);
22468
23225
  this.signerDocuments = new SignerDocumentsResource(
@@ -22498,13 +23255,22 @@ var AssinafyClient = class _AssinafyClient {
22498
23255
  /**
22499
23256
  * High-level helper that uploads a PDF, ensures it's processed, creates any
22500
23257
  * missing signers, and kicks off a virtual signature assignment.
23258
+ *
23259
+ * Once the upload succeeds the workflow owns real workspace resources, so any
23260
+ * later failure is rethrown as a {@link PartialWorkflowError} carrying the
23261
+ * document and signer IDs that already exist. Catch it to resume or clean up;
23262
+ * nothing is deleted automatically.
22501
23263
  */
22502
23264
  async uploadAndRequestSignatures(options) {
22503
- if (!options.signers || options.signers.length === 0) {
23265
+ if (!Array.isArray(options.signers) || options.signers.length === 0) {
22504
23266
  throw new ValidationError("At least one signer is required");
22505
23267
  }
22506
23268
  if (options.expiresAt !== void 0) requireIso8601(options.expiresAt, "expiresAt");
22507
23269
  const preparedSigners = options.signers.map((signer) => {
23270
+ if (!signer || typeof signer !== "object") {
23271
+ throw new ValidationError("Each signer must be an object");
23272
+ }
23273
+ validateSignerOptions(signer);
22508
23274
  const payload = { full_name: signer.name };
22509
23275
  if (signer.email !== void 0) payload.email = signer.email;
22510
23276
  const phone = signer.whatsapp_phone_number ?? signer.phone;
@@ -22514,6 +23280,7 @@ var AssinafyClient = class _AssinafyClient {
22514
23280
  validateCreateSignerPayload(payload);
22515
23281
  return { signer, payload, phone };
22516
23282
  });
23283
+ validateSigningSteps(options.signers);
22517
23284
  this.logger.info("Starting upload + signature workflow", {
22518
23285
  signerCount: options.signers.length
22519
23286
  });
@@ -22521,33 +23288,46 @@ var AssinafyClient = class _AssinafyClient {
22521
23288
  if (options.metadata !== void 0) uploadOpts.metadata = options.metadata;
22522
23289
  if (options.accountId !== void 0) uploadOpts.accountId = options.accountId;
22523
23290
  const document2 = await this.documents.upload(options.source, uploadOpts);
22524
- if (options.waitForReady !== false) {
22525
- await this.documents.waitUntilReady(document2.id);
22526
- }
22527
23291
  const signerIds = [];
22528
- const assignmentSigners = [];
22529
- for (const { signer, payload, phone } of preparedSigners) {
22530
- const created = await this.signers.create(payload, options.accountId);
22531
- signerIds.push(created.id);
22532
- const useWhatsapp = phone !== void 0 && signer.email === void 0;
22533
- assignmentSigners.push({
22534
- id: created.id,
22535
- verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
22536
- notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
22537
- step: signer.step
23292
+ try {
23293
+ if (options.waitForReady !== false) {
23294
+ await this.documents.waitUntilReady(document2.id);
23295
+ }
23296
+ const assignmentSigners = [];
23297
+ for (const { signer, payload, phone } of preparedSigners) {
23298
+ const created = await this.signers.create(payload, options.accountId);
23299
+ signerIds.push(created.id);
23300
+ const useWhatsapp = phone !== void 0 && signer.email === void 0;
23301
+ assignmentSigners.push({
23302
+ id: created.id,
23303
+ verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
23304
+ notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
23305
+ step: signer.step
23306
+ });
23307
+ }
23308
+ const assignmentPayload = {
23309
+ method: "virtual",
23310
+ signers: assignmentSigners
23311
+ };
23312
+ if (options.message !== void 0) assignmentPayload.message = options.message;
23313
+ if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
23314
+ if (options.copyReceivers !== void 0)
23315
+ assignmentPayload.copy_receivers = options.copyReceivers;
23316
+ const assignment = await this.assignments.create(document2.id, assignmentPayload);
23317
+ this.logger.info("Upload + signature workflow completed", { documentId: document2.id });
23318
+ return { document: document2, assignment, signer_ids: signerIds };
23319
+ } catch (err) {
23320
+ this.logger.error("Upload + signature workflow failed after creating resources", {
23321
+ documentId: document2.id,
23322
+ signerIds
22538
23323
  });
23324
+ const reason = err instanceof Error ? err.message : String(err);
23325
+ throw new PartialWorkflowError(
23326
+ `${reason} (document ${document2.id} exists; ${signerIds.length} signer(s) created or reused)`,
23327
+ { documentId: document2.id, signerIds },
23328
+ { cause: err }
23329
+ );
22539
23330
  }
22540
- const assignmentPayload = {
22541
- method: "virtual",
22542
- signers: assignmentSigners
22543
- };
22544
- if (options.message !== void 0) assignmentPayload.message = options.message;
22545
- if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
22546
- if (options.copyReceivers !== void 0)
22547
- assignmentPayload.copy_receivers = options.copyReceivers;
22548
- const assignment = await this.assignments.create(document2.id, assignmentPayload);
22549
- this.logger.info("Upload + signature workflow completed", { documentId: document2.id });
22550
- return { document: document2, assignment, signer_ids: signerIds };
22551
23331
  }
22552
23332
  /** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */
22553
23333
  getAxiosInstance() {
@@ -22575,9 +23355,23 @@ function normalizeError(err) {
22575
23355
  message: err.message,
22576
23356
  code: "api_error",
22577
23357
  statusCode: err.statusCode,
22578
- details: err.responseData ?? void 0
23358
+ details: err.responseData ?? void 0,
23359
+ ...err.wwwAuthenticate ? { wwwAuthenticate: err.wwwAuthenticate } : {},
23360
+ ...err.retryAfter ? { retryAfter: err.retryAfter } : {}
22579
23361
  };
22580
23362
  }
23363
+ if (err instanceof PartialWorkflowError) {
23364
+ const cause = normalizeError(err.cause);
23365
+ const normalized = {
23366
+ message: err.message,
23367
+ code: cause.code,
23368
+ details: err.context
23369
+ };
23370
+ if (cause.statusCode !== void 0) normalized.statusCode = cause.statusCode;
23371
+ if (cause.wwwAuthenticate !== void 0) normalized.wwwAuthenticate = cause.wwwAuthenticate;
23372
+ if (cause.retryAfter !== void 0) normalized.retryAfter = cause.retryAfter;
23373
+ return normalized;
23374
+ }
22581
23375
  if (err instanceof ValidationError) {
22582
23376
  return { message: err.message, code: "validation_error", details: err.errors };
22583
23377
  }
@@ -22592,6 +23386,10 @@ function normalizeError(err) {
22592
23386
  }
22593
23387
  return { message: String(err), code: "unexpected_error" };
22594
23388
  }
23389
+ function errorMessage(err, fallback = "An unexpected error occurred") {
23390
+ const normalized = normalizeError(err);
23391
+ return normalized.message || fallback;
23392
+ }
22595
23393
 
22596
23394
  // src/lib/client.ts
22597
23395
  function createClient(config, options = {}) {
@@ -22786,7 +23584,7 @@ function paginationFooter(result) {
22786
23584
  }
22787
23585
 
22788
23586
  // src/lib/config.ts
22789
- var import_node_crypto2 = require("crypto");
23587
+ var import_node_crypto3 = require("crypto");
22790
23588
  var import_node_fs3 = require("fs");
22791
23589
  var import_node_os = __toESM(require("os"), 1);
22792
23590
  var import_node_path3 = __toESM(require("path"), 1);
@@ -22841,7 +23639,7 @@ function writeConfigFile(config) {
22841
23639
  (0, import_node_fs3.mkdirSync)(dir, { recursive: true, mode: 448 });
22842
23640
  }
22843
23641
  const file = configPath();
22844
- const tmp = `${file}.${(0, import_node_crypto2.randomUUID)()}.tmp`;
23642
+ const tmp = `${file}.${(0, import_node_crypto3.randomUUID)()}.tmp`;
22845
23643
  try {
22846
23644
  (0, import_node_fs3.writeFileSync)(tmp, `${JSON.stringify(config, null, 2)}
22847
23645
  `, {
@@ -22864,9 +23662,14 @@ function resolveConfig2(globals) {
22864
23662
  const profile = file.profiles?.[profileName] ?? {};
22865
23663
  const pick = (flag, env, stored) => flag ?? env ?? stored;
22866
23664
  const baseUrl = pick(globals.baseUrl, process.env.ASSINAFY_BASE_URL, profile.base_url) ?? DEFAULT_BASE_URL2;
23665
+ const credentials = [
23666
+ { apiKey: globals.apiKey, token: globals.token },
23667
+ { apiKey: process.env.ASSINAFY_API_KEY, token: process.env.ASSINAFY_TOKEN },
23668
+ { apiKey: profile.api_key, token: profile.token }
23669
+ ].find(({ apiKey, token }) => apiKey !== void 0 || token !== void 0);
22867
23670
  return {
22868
- apiKey: pick(globals.apiKey, process.env.ASSINAFY_API_KEY, profile.api_key),
22869
- token: pick(globals.token, process.env.ASSINAFY_TOKEN, profile.token),
23671
+ apiKey: credentials?.apiKey,
23672
+ token: credentials?.token,
22870
23673
  accountId: pick(globals.accountId, process.env.ASSINAFY_ACCOUNT_ID, profile.account_id),
22871
23674
  baseUrl: normalizeBaseUrl(baseUrl),
22872
23675
  webhookSecret: pick(void 0, process.env.ASSINAFY_WEBHOOK_SECRET, profile.webhook_secret),
@@ -23936,6 +24739,27 @@ function renderTable(rows, columns) {
23936
24739
  );
23937
24740
  return [headerLine, ...lines].join("\n");
23938
24741
  }
24742
+ function renderDocumentStats(rows) {
24743
+ return renderTable(rows, [
24744
+ { header: "PERIOD", value: (row) => row.period },
24745
+ { header: "UPLOADED", value: (row) => row.documents_uploaded },
24746
+ { header: "SENT", value: (row) => row.documents_sent },
24747
+ { header: "REQUESTS", value: (row) => row.signature_requests },
24748
+ { header: "NOTIFY EMAIL", value: (row) => row.signature_requests_notification_email },
24749
+ { header: "NOTIFY WA", value: (row) => row.signature_requests_notification_whatsapp },
24750
+ { header: "NOTIFY BYPASS", value: (row) => row.signature_requests_notification_bypass },
24751
+ { header: "VERIFY EMAIL", value: (row) => row.signature_requests_verification_email },
24752
+ { header: "VERIFY WA", value: (row) => row.signature_requests_verification_whatsapp },
24753
+ { header: "VERIFY BYPASS", value: (row) => row.signature_requests_verification_bypass },
24754
+ {
24755
+ header: "VERIFY CERT",
24756
+ value: (row) => row.signature_requests_verification_digital_certificate
24757
+ },
24758
+ { header: "VIEWED", value: (row) => row.signature_requests_viewed },
24759
+ { header: "COMPLETED", value: (row) => row.signature_requests_completed },
24760
+ { header: "CERTIFIED", value: (row) => row.documents_certified }
24761
+ ]);
24762
+ }
23939
24763
  function renderKeyValue(obj, order) {
23940
24764
  const keys = order ?? Object.keys(obj);
23941
24765
  const present = keys.filter((k) => k in obj && obj[k] !== void 0);
@@ -23960,13 +24784,13 @@ function displayWidth(text2) {
23960
24784
  }
23961
24785
 
23962
24786
  // src/commands/assignments.ts
23963
- function resolveSigners(signersJson, signerIdsCsv, required = true) {
24787
+ function resolveSigners(signersJson, signerIdsCsv, required2 = true) {
23964
24788
  if (signersJson) {
23965
24789
  return parseJsonArray(signersJson, "--signers");
23966
24790
  }
23967
24791
  const ids = splitList(signerIdsCsv);
23968
24792
  if (!ids || ids.length === 0) {
23969
- if (!required) return [];
24793
+ if (!required2) return [];
23970
24794
  throw new CliError("Provide signers with --signer-ids <id1,id2> or --signers <json>.");
23971
24795
  }
23972
24796
  return ids;
@@ -24056,7 +24880,11 @@ var estimateCostCommand = new Command("estimate-cost").description("Estimate the
24056
24880
  printData(result, config);
24057
24881
  });
24058
24882
  });
24059
- var resetExpirationCommand = new Command("reset-expiration").description("Update or clear an assignment expiration date").argument("<documentId>", "Document ID").argument("<assignmentId>", "Assignment ID").addOption(new Option("--expires-at <iso8601>", "New expiration timestamp").conflicts("clear")).addOption(new Option("--clear", "Remove the expiration entirely").conflicts("expiresAt")).action(async (documentId, assignmentId, opts, command) => {
24883
+ var resetExpirationCommand = new Command("reset-expiration").description("Update an assignment expiration date").argument("<documentId>", "Document ID").argument("<assignmentId>", "Assignment ID").addOption(new Option("--expires-at <iso8601>", "New expiration timestamp").conflicts("clear")).addOption(
24884
+ new Option("--clear", "Remove the expiration when supported by the deployment").conflicts(
24885
+ "expiresAt"
24886
+ )
24887
+ ).action(async (documentId, assignmentId, opts, command) => {
24060
24888
  await runWithClient(command, async ({ client, config }) => {
24061
24889
  if (!opts.clear && !opts.expiresAt) {
24062
24890
  throw new CliError("Pass --expires-at <iso8601> or --clear.");
@@ -24306,10 +25134,12 @@ var setCommand = new Command("set").description(
24306
25134
  let changed = false;
24307
25135
  if (merged.apiKey !== void 0) {
24308
25136
  profile.api_key = merged.apiKey;
25137
+ profile.token = void 0;
24309
25138
  changed = true;
24310
25139
  }
24311
25140
  if (merged.token !== void 0) {
24312
25141
  profile.token = merged.token;
25142
+ if (merged.apiKey === void 0) profile.api_key = void 0;
24313
25143
  changed = true;
24314
25144
  }
24315
25145
  if (merged.accountId !== void 0) {
@@ -24475,17 +25305,26 @@ var uploadCommand = new Command("upload").description("Upload a PDF to the works
24475
25305
  const uploadOptions = { accountId };
24476
25306
  if (metadata) uploadOptions.metadata = metadata;
24477
25307
  if (opts.name) uploadOptions.name = opts.name;
24478
- const doc = await withSpinner(
25308
+ let doc = await withSpinner(
24479
25309
  "Uploading document",
24480
25310
  config,
24481
25311
  () => client.documents.upload({ filePath: file }, uploadOptions)
24482
25312
  );
24483
25313
  if (opts.wait) {
24484
- await withSpinner(
24485
- "Waiting for processing",
24486
- config,
24487
- () => client.documents.waitUntilReady(doc.id)
24488
- );
25314
+ try {
25315
+ const ready = await withSpinner(
25316
+ "Waiting for processing",
25317
+ config,
25318
+ () => client.documents.waitUntilReady(doc.id)
25319
+ );
25320
+ doc = { ...doc, ...ready };
25321
+ } catch (error) {
25322
+ throw new PartialWorkflowError(
25323
+ `${errorMessage(error)} (document ${doc.id} was uploaded)`,
25324
+ { documentId: doc.id },
25325
+ { cause: error }
25326
+ );
25327
+ }
24489
25328
  }
24490
25329
  printSuccess(`Uploaded document ${doc.id}`, config);
24491
25330
  printData(
@@ -24677,25 +25516,25 @@ var tagsCommand = new Command("tags").description("List the tags attached to a d
24677
25516
  );
24678
25517
  });
24679
25518
  });
24680
- var tagsSetCommand = new Command("tags-set").description("Replace a document tag set (names; unknown names are auto-created)").argument("<id>", "Document ID").argument("[names...]", "Tag names (pass none to detach all)").action(async (id, names, _opts, command) => {
25519
+ var tagsSetCommand = new Command("tags-set").description("Replace a document tag set by tag ID").argument("<id>", "Document ID").argument("[tagIds...]", "Tag IDs (pass none to detach all)").action(async (id, tagIds, _opts, command) => {
24681
25520
  await runWithClient(command, async ({ client, config }) => {
24682
25521
  const accountId = requireAccountId(config);
24683
25522
  const tags = await withSpinner(
24684
25523
  "Replacing tags",
24685
25524
  config,
24686
- () => client.documents.replaceTags(id, names ?? [], accountId)
25525
+ () => client.documents.replaceTags(id, tagIds ?? [], accountId)
24687
25526
  );
24688
25527
  printSuccess(`Document now has ${tags.length} tag(s)`, config);
24689
25528
  printData(tags, config);
24690
25529
  });
24691
25530
  });
24692
- var tagsAddCommand = new Command("tags-add").description("Attach additional tags by name without removing existing ones").argument("<id>", "Document ID").argument("<names...>", "Tag names to attach").action(async (id, names, _opts, command) => {
25531
+ var tagsAddCommand = new Command("tags-add").description("Attach additional tag IDs without removing existing ones").argument("<id>", "Document ID").argument("<tagIds...>", "Tag IDs to attach").action(async (id, tagIds, _opts, command) => {
24693
25532
  await runWithClient(command, async ({ client, config }) => {
24694
25533
  const accountId = requireAccountId(config);
24695
25534
  const tags = await withSpinner(
24696
25535
  "Adding tags",
24697
25536
  config,
24698
- () => client.documents.addTags(id, names, accountId)
25537
+ () => client.documents.addTags(id, tagIds, accountId)
24699
25538
  );
24700
25539
  printSuccess(`Document now has ${tags.length} tag(s)`, config);
24701
25540
  printData(tags, config);
@@ -24867,7 +25706,7 @@ var fieldColumns = [
24867
25706
  { header: "REQUIRED", value: (r2) => r2.is_required },
24868
25707
  { header: "ACTIVE", value: (r2) => r2.is_active }
24869
25708
  ];
24870
- var createCommand2 = new Command("create").description("Create a custom field definition").requiredOption("--type <type>", "Field type (see `fields types`)").requiredOption("--name <name>", "Field name").option("--regex <regex>", "Validation regex").option("--required", "Mark the field as required").option("--inactive", "Create the field inactive").action(async (opts, command) => {
25709
+ var createCommand2 = new Command("create").description("Create a custom field definition").requiredOption("--type <type>", "Field type (see `fields types`)").requiredOption("--name <name>", "Field name").option("--regex <regex>", "Validation regex").option("--required", "Mark the field as required").option("--inactive", "Compatibility: create the field inactive").action(async (opts, command) => {
24871
25710
  await runWithClient(command, async ({ client, config }) => {
24872
25711
  const accountId = requireAccountId(config);
24873
25712
  const payload = { type: opts.type, name: opts.name };
@@ -24908,7 +25747,7 @@ var getCommand3 = new Command("get").description("Show a field definition by ID"
24908
25747
  printData(field, config, (f) => renderKeyValue(f));
24909
25748
  });
24910
25749
  });
24911
- var updateCommand = new Command("update").description("Update a field definition").argument("<id>", "Field ID").option("--type <type>", "Field type").option("--name <name>", "Field name").addOption(new Option("--regex <regex>", "Validation regex").conflicts("clearRegex")).addOption(new Option("--clear-regex", "Remove the existing validation regex").conflicts("regex")).addOption(new Option("--required", "Mark as required").conflicts("optional")).addOption(new Option("--optional", "Mark as not required").conflicts("required")).addOption(new Option("--active", "Activate the field").conflicts("inactive")).addOption(new Option("--inactive", "Deactivate the field").conflicts("active")).action(async (id, opts, command) => {
25750
+ var updateCommand = new Command("update").description("Update a field definition").argument("<id>", "Field ID").option("--type <type>", "Compatibility: change the field type").option("--name <name>", "Field name").addOption(new Option("--regex <regex>", "Validation regex").conflicts("clearRegex")).addOption(new Option("--clear-regex", "Remove the existing validation regex").conflicts("regex")).addOption(new Option("--required", "Compatibility: mark as required").conflicts("optional")).addOption(new Option("--optional", "Compatibility: mark as not required").conflicts("required")).addOption(new Option("--active", "Activate the field").conflicts("inactive")).addOption(new Option("--inactive", "Deactivate the field").conflicts("active")).action(async (id, opts, command) => {
24912
25751
  await runWithClient(command, async ({ client, config }) => {
24913
25752
  const accountId = requireAccountId(config);
24914
25753
  const payload = {};
@@ -25046,6 +25885,230 @@ var logoutCommand = new Command("logout").description("Remove stored credentials
25046
25885
  });
25047
25886
  });
25048
25887
 
25888
+ // src/lib/oauth-browser.ts
25889
+ var import_node_child_process3 = require("child_process");
25890
+ var import_node_crypto4 = require("crypto");
25891
+ var import_node_events2 = require("events");
25892
+ var import_node_http = require("http");
25893
+ var CLI_OAUTH_REDIRECT_URI = "https://integrations.assinafy.com.br/assinafy-cli/oauth-callback";
25894
+ var clearHistory = "history.replaceState(null, '', '/');";
25895
+ var callbackPage = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Assinafy CLI</title><script>${clearHistory}</script><h1>Return to your terminal</h1><p>The authorization response was received. Check the terminal for the connection result.</p></html>`;
25896
+ var callbackHeaders = {
25897
+ "Cache-Control": "no-store",
25898
+ "Referrer-Policy": "no-referrer",
25899
+ "X-Content-Type-Options": "nosniff",
25900
+ "Content-Security-Policy": `default-src 'none'; script-src 'sha256-${(0, import_node_crypto4.createHash)("sha256").update(clearHistory).digest("base64")}'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
25901
+ Connection: "close"
25902
+ };
25903
+ function openBrowser(url2) {
25904
+ const [executable, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["rundll32.exe", ["url.dll,FileProtocolHandler", url2]] : ["xdg-open", [url2]];
25905
+ return new Promise((resolve, reject) => {
25906
+ const child = (0, import_node_child_process3.spawn)(executable, args, {
25907
+ stdio: "ignore",
25908
+ detached: true,
25909
+ windowsHide: true
25910
+ });
25911
+ child.once("error", () => reject(new CliError("Could not open the system browser.")));
25912
+ child.once("spawn", () => {
25913
+ child.unref();
25914
+ resolve();
25915
+ });
25916
+ });
25917
+ }
25918
+ async function connectOAuth(oauth, options, onAuthorize, timeoutMs = 18e4) {
25919
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e5) {
25920
+ throw new CliError("OAuth connection timeout must be between 1 and 600000 milliseconds.");
25921
+ }
25922
+ const request = await oauth.authorize(options);
25923
+ if (new URL(request.redirect_uri).search) {
25924
+ throw new CliError("The browser relay redirect URI must not contain query parameters.");
25925
+ }
25926
+ const server = (0, import_node_http.createServer)({ maxHeaderSize: 8192, requestTimeout: 5e3, headersTimeout: 5e3 });
25927
+ server.maxConnections = 8;
25928
+ server.setTimeout(5e3, (socket) => socket.destroy());
25929
+ let timer;
25930
+ let cancel2;
25931
+ let terminate;
25932
+ let callbackUrl;
25933
+ try {
25934
+ server.listen(0, "127.0.0.1");
25935
+ await (0, import_node_events2.once)(server, "listening");
25936
+ const address = server.address();
25937
+ if (!address || typeof address === "string") throw new CliError("No OAuth listener address.");
25938
+ const host = `127.0.0.1:${address.port}`;
25939
+ request.state += `.${address.port}`;
25940
+ const expectedState = Buffer.from(request.state);
25941
+ const authorization = new URL(request.authorization_url);
25942
+ authorization.searchParams.set("state", request.state);
25943
+ request.authorization_url = authorization.toString();
25944
+ callbackUrl = await new Promise((resolve, reject) => {
25945
+ let consumed = false;
25946
+ timer = setTimeout(
25947
+ () => reject(new CliError("OAuth connection timed out. Start again.")),
25948
+ timeoutMs
25949
+ );
25950
+ cancel2 = () => reject(new CliError("OAuth connection cancelled.", { exitCode: 130 }));
25951
+ terminate = () => reject(new CliError("OAuth connection terminated.", { exitCode: 143 }));
25952
+ process.once("SIGINT", cancel2);
25953
+ process.once("SIGTERM", terminate);
25954
+ server.once("error", reject);
25955
+ server.on("request", (incoming, response) => {
25956
+ const raw = incoming.url ?? "";
25957
+ const url2 = new URL(raw.startsWith("/callback?") ? raw : "/invalid", `http://${host}`);
25958
+ const query = url2.searchParams;
25959
+ const state = Buffer.from(query.get("state") ?? "");
25960
+ const valid = !consumed && incoming.method === "GET" && incoming.headers.host === host && raw.startsWith("/callback?") && raw.length <= 8192 && url2.origin === `http://${host}` && url2.pathname === "/callback" && !url2.hash && [...query.keys()].every((key) => query.getAll(key).length === 1) && state.length === expectedState.length && (0, import_node_crypto4.timingSafeEqual)(state, expectedState) && query.get("iss") === request.issuer && query.has("code") !== query.has("error") && Boolean((query.get("code") ?? query.get("error"))?.trim());
25961
+ if (!valid) {
25962
+ response.writeHead(400, {
25963
+ ...callbackHeaders,
25964
+ "Content-Type": "text/plain; charset=utf-8"
25965
+ });
25966
+ response.end("Invalid authorization response. Continue in the original browser session.");
25967
+ return;
25968
+ }
25969
+ consumed = true;
25970
+ const callback = new URL(request.redirect_uri);
25971
+ for (const key of ["code", "state", "iss", "error"]) {
25972
+ if (query.has(key)) callback.searchParams.set(key, query.get(key));
25973
+ }
25974
+ response.writeHead(200, { ...callbackHeaders, "Content-Type": "text/html; charset=utf-8" });
25975
+ response.end(callbackPage, () => resolve(callback.toString()));
25976
+ });
25977
+ void Promise.resolve().then(() => onAuthorize(request.authorization_url)).catch(reject);
25978
+ });
25979
+ } finally {
25980
+ clearTimeout(timer);
25981
+ if (cancel2) process.off("SIGINT", cancel2);
25982
+ if (terminate) process.off("SIGTERM", terminate);
25983
+ await new Promise((resolve) => {
25984
+ server.close(() => resolve());
25985
+ server.closeAllConnections();
25986
+ });
25987
+ }
25988
+ return oauth.exchangeCode(callbackUrl, request);
25989
+ }
25990
+
25991
+ // src/commands/oauth.ts
25992
+ var clientIdOption = () => new Option("--client-id <id>", "OAuth application client ID").env("ASSINAFY_OAUTH_CLIENT_ID").default("96BZZ0sZTb2NkEXt1GCaIRCTprI2YKHZr8JDHawuXUyCLC88");
25993
+ var clientSecretOption = () => new Option(
25994
+ "--client-secret <secret>",
25995
+ "Confidential application secret; omit for public applications"
25996
+ ).env("ASSINAFY_OAUTH_CLIENT_SECRET");
25997
+ var connectCommand = new Command("connect").description(
25998
+ "Open browser consent for a public OAuth app, receive its loopback return, and print tokens"
25999
+ ).addOption(clientIdOption()).option("--redirect-uri <uri>", "Exactly registered HTTPS relay URI", CLI_OAUTH_REDIRECT_URI).option(
26000
+ "--scope <scopes>",
26001
+ "Space-separated scopes; defaults to all supported OAuth scopes",
26002
+ "account:read documents:read documents:write templates:read templates:write openid profile email offline_access"
26003
+ ).option("--timeout <seconds>", "Wait for browser consent (1\u2013600 seconds)", "180").option("--no-browser", "Print the authorization URL without opening the system browser").action(async (opts, command) => {
26004
+ await runWithPublicClient(command, async ({ client, config }) => {
26005
+ const timeout = parseInteger(opts.timeout, "--timeout", { min: 1 });
26006
+ const tokens = await connectOAuth(
26007
+ client.oauth,
26008
+ {
26009
+ clientId: opts.clientId,
26010
+ redirectUri: opts.redirectUri,
26011
+ scopes: opts.scope.trim().split(/\s+/)
26012
+ },
26013
+ async (url2) => {
26014
+ process.stderr.write(
26015
+ `Open this URL in a browser on this computer:
26016
+ ${sanitizeTerminalText(url2)}
26017
+ `
26018
+ );
26019
+ if (opts.browser) {
26020
+ await openBrowser(url2).catch(() => {
26021
+ process.stderr.write("Could not open the browser. Open the URL above manually.\n");
26022
+ });
26023
+ }
26024
+ },
26025
+ timeout * 1e3
26026
+ );
26027
+ printData(tokens, config);
26028
+ });
26029
+ });
26030
+ var metadataCommand = new Command("metadata").description("Read protected-resource metadata from the API origin").action(async (_opts, command) => {
26031
+ await runWithPublicClient(command, async ({ client, config }) => {
26032
+ printData(await client.oauth.metadata(), config);
26033
+ });
26034
+ });
26035
+ var discoveryCommand = new Command("discovery").description("Read authorization-server metadata from an HTTPS issuer").argument("<issuer>", "Issuer from protected-resource metadata").action(async (issuer, _opts, command) => {
26036
+ await runWithPublicClient(command, async ({ client, config }) => {
26037
+ printData(await client.oauth.discovery(issuer), config);
26038
+ });
26039
+ });
26040
+ var authorizeCommand = new Command("authorize").description(
26041
+ "Create an authorization URL and a sensitive PKCE/state request; save the JSON securely"
26042
+ ).addOption(clientIdOption()).requiredOption("--redirect-uri <uri>", "Exactly registered HTTPS callback URI").requiredOption(
26043
+ "--scope <scopes>",
26044
+ "Space-separated scopes; offline_access requests refresh tokens"
26045
+ ).action(async (opts, command) => {
26046
+ await runWithPublicClient(command, async ({ client, config }) => {
26047
+ printData(
26048
+ await client.oauth.authorize({
26049
+ clientId: opts.clientId,
26050
+ redirectUri: opts.redirectUri,
26051
+ scopes: opts.scope.trim().split(/\s+/)
26052
+ }),
26053
+ config
26054
+ );
26055
+ });
26056
+ });
26057
+ var exchangeCommand = new Command("exchange").description("Validate the callback against a saved authorization request and exchange its code").requiredOption("--request <path>", "Private JSON file returned by oauth authorize").addOption(
26058
+ new Option("--callback-url <url>", "Complete callback URL with code, state, and iss").env("ASSINAFY_OAUTH_CALLBACK_URL").makeOptionMandatory()
26059
+ ).addOption(clientSecretOption()).action(async (opts, command) => {
26060
+ await runWithPublicClient(command, async ({ client, config }) => {
26061
+ const request = parseJsonObject(
26062
+ readBinary(opts.request).toString("utf8"),
26063
+ "--request"
26064
+ );
26065
+ printData(
26066
+ await client.oauth.exchangeCode(opts.callbackUrl, request, opts.clientSecret),
26067
+ config
26068
+ );
26069
+ });
26070
+ });
26071
+ var refreshCommand = new Command("refresh").description("Rotate a refresh token once; securely persist the full response before using it").addOption(clientIdOption()).addOption(clientSecretOption()).addOption(
26072
+ new Option("--refresh-token <token>", "Current refresh token").env("ASSINAFY_OAUTH_REFRESH_TOKEN").makeOptionMandatory()
26073
+ ).option("--resource <uri>", "Resource indicator used during authorization").action(async (opts, command) => {
26074
+ await runWithPublicClient(command, async ({ client, config }) => {
26075
+ printData(
26076
+ await client.oauth.token({
26077
+ grant_type: "refresh_token",
26078
+ client_id: opts.clientId,
26079
+ client_secret: opts.clientSecret,
26080
+ refresh_token: opts.refreshToken,
26081
+ resource: opts.resource
26082
+ }),
26083
+ config
26084
+ );
26085
+ });
26086
+ });
26087
+ var revokeCommand = new Command("revoke").description("Revoke an access or refresh token for this application").addOption(clientIdOption()).addOption(clientSecretOption()).addOption(
26088
+ new Option("--revoke-token <token>", "Token to revoke").env("ASSINAFY_OAUTH_REVOKE_TOKEN").makeOptionMandatory()
26089
+ ).addOption(
26090
+ new Option("--token-type-hint <type>", "Type of token being revoked").choices([
26091
+ "access_token",
26092
+ "refresh_token"
26093
+ ])
26094
+ ).action(async (opts, command) => {
26095
+ await runWithPublicClient(command, async ({ client, config }) => {
26096
+ await client.oauth.revoke({
26097
+ token: opts.revokeToken,
26098
+ client_id: opts.clientId,
26099
+ client_secret: opts.clientSecret,
26100
+ token_type_hint: opts.tokenTypeHint
26101
+ });
26102
+ printData({ revoked: true }, config);
26103
+ });
26104
+ });
26105
+ var userinfoCommand = new Command("userinfo").description("Read OIDC claims using --token / ASSINAFY_TOKEN with openid scope").action(async (_opts, command) => {
26106
+ await runWithClient(command, async ({ client, config }) => {
26107
+ printData(await client.oauth.userinfo(), config);
26108
+ });
26109
+ });
26110
+ var oauthCommand = new Command("oauth").description("OAuth 2.1 authorization, PKCE, token rotation, and OpenID Connect").addCommand(connectCommand).addCommand(metadataCommand).addCommand(discoveryCommand).addCommand(authorizeCommand).addCommand(exchangeCommand).addCommand(refreshCommand).addCommand(revokeCommand).addCommand(userinfoCommand);
26111
+
25049
26112
  // src/commands/send.ts
25050
26113
  function parseSignerSpec(spec) {
25051
26114
  const match = spec.match(/^\s*(.*?)\s*<\s*([^>]*)\s*>\s*$/);
@@ -25162,7 +26225,11 @@ var searchCommand2 = new Command("search").description("Search the signer's docu
25162
26225
  );
25163
26226
  });
25164
26227
  });
25165
- var downloadCommand2 = new Command("download").description("Download a signer document artifact").argument("<signerId>", "Signer ID").argument("<documentId>", "Document ID").argument("<artifact>", "original | certificated | certificate-page | pades | bundle").addOption(accessCodeOption()).option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists").action(async (signerId, documentId, artifact, opts, command) => {
26228
+ var downloadCommand2 = new Command("download").description("Download a signer document artifact").argument("<signerId>", "Signer ID").argument("<documentId>", "Document ID").argument("<artifact>", "original | certificated | certificate-page | pades | bundle").addOption(
26229
+ new Option("--access-code <code>", "Optional signer identity preflight code").env(
26230
+ "ASSINAFY_SIGNER_ACCESS_CODE"
26231
+ )
26232
+ ).option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists").action(async (signerId, documentId, artifact, opts, command) => {
25166
26233
  await runWithPublicClient(command, async ({ client, config }) => {
25167
26234
  const artifactName = requireDocumentArtifactName(artifact);
25168
26235
  const buffer = await withSpinner(
@@ -25330,7 +26397,7 @@ var declineMultipleCommand = new Command("decline-multiple").description("Declin
25330
26397
  printData(result, config);
25331
26398
  });
25332
26399
  });
25333
- var signerCommand = new Command("signer").description("Signer-side flows authenticated by a signer access code").addCommand(documentCommand).addCommand(documentsCommand2).addCommand(searchCommand2).addCommand(downloadCommand2).addCommand(selfCommand).addCommand(acceptTermsCommand).addCommand(verifyEmailCommand).addCommand(confirmDataCommand).addCommand(uploadSignatureCommand).addCommand(downloadSignatureCommand).addCommand(assignmentCommand).addCommand(signCommand).addCommand(declineCommand).addCommand(signMultipleCommand).addCommand(declineMultipleCommand);
26400
+ var signerCommand = new Command("signer").description("Signer-side flows and public artifact downloads").addCommand(documentCommand).addCommand(documentsCommand2).addCommand(searchCommand2).addCommand(downloadCommand2).addCommand(selfCommand).addCommand(acceptTermsCommand).addCommand(verifyEmailCommand).addCommand(confirmDataCommand).addCommand(uploadSignatureCommand).addCommand(downloadSignatureCommand).addCommand(assignmentCommand).addCommand(signCommand).addCommand(declineCommand).addCommand(signMultipleCommand).addCommand(declineMultipleCommand);
25334
26401
 
25335
26402
  // src/commands/signers.ts
25336
26403
  var signerColumns = [
@@ -25595,7 +26662,7 @@ var statsCommand = new Command("stats").description("Show document KPIs across t
25595
26662
  config,
25596
26663
  () => client.users.stats(params)
25597
26664
  );
25598
- printData(rows, config, renderStats);
26665
+ printData(rows, config, renderDocumentStats);
25599
26666
  });
25600
26667
  });
25601
26668
  var preferencesGetCommand = new Command("get").description("Show all owner-facing email notification preferences").action(async (_opts, command) => {
@@ -25632,16 +26699,6 @@ var preferencesUpdateCommand = new Command("update").description("Merge one or m
25632
26699
  });
25633
26700
  var preferencesCommand = new Command("notification-preferences").alias("preferences").description("Manage owner-facing email notification preferences").addCommand(preferencesGetCommand).addCommand(preferencesUpdateCommand);
25634
26701
  var usersCommand = new Command("users").description("Show the authenticated user and personal preferences").addCommand(selfCommand2).addCommand(statsCommand).addCommand(preferencesCommand);
25635
- function renderStats(rows) {
25636
- return renderTable(rows, [
25637
- { header: "PERIOD", value: (row) => row.period },
25638
- { header: "UPLOADED", value: (row) => row.documents_uploaded },
25639
- { header: "SENT", value: (row) => row.documents_sent },
25640
- { header: "REQUESTS", value: (row) => row.signature_requests },
25641
- { header: "COMPLETED", value: (row) => row.signature_requests_completed },
25642
- { header: "CERTIFIED", value: (row) => row.documents_certified }
25643
- ]);
25644
- }
25645
26702
 
25646
26703
  // src/commands/webhooks.ts
25647
26704
  var registerCommand = new Command("register").description("Register (or replace) the workspace webhook subscription").requiredOption("--url <url>", "Endpoint URL to receive events").requiredOption("--email <email>", "Contact email for delivery problems").option("--events <csv>", "Comma-separated event names (defaults to a sensible set)").option("--inactive", "Register the subscription as inactive").action(async (opts, command) => {
@@ -25878,7 +26935,7 @@ var statsCommand2 = new Command("stats").description("Show document KPIs for a w
25878
26935
  config,
25879
26936
  () => client.workspaces.stats(id, params)
25880
26937
  );
25881
- printData(rows, config, renderStats2);
26938
+ printData(rows, config, renderDocumentStats);
25882
26939
  });
25883
26940
  });
25884
26941
  var logoDownloadCommand = new Command("download").description("Download the workspace logo").argument("<id>", "Account/workspace ID").option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists").action(async (id, opts, command) => {
@@ -25943,16 +27000,6 @@ function logoContentType(file) {
25943
27000
  ".webp": "image/webp"
25944
27001
  }[import_node_path6.default.extname(file).toLowerCase()] ?? "image/png";
25945
27002
  }
25946
- function renderStats2(rows) {
25947
- return renderTable(rows, [
25948
- { header: "PERIOD", value: (row) => row.period },
25949
- { header: "UPLOADED", value: (row) => row.documents_uploaded },
25950
- { header: "SENT", value: (row) => row.documents_sent },
25951
- { header: "REQUESTS", value: (row) => row.signature_requests },
25952
- { header: "COMPLETED", value: (row) => row.signature_requests_completed },
25953
- { header: "CERTIFIED", value: (row) => row.documents_certified }
25954
- ]);
25955
- }
25956
27003
 
25957
27004
  // src/lib/cli-exit.ts
25958
27005
  var import_picocolors6 = __toESM(require_picocolors(), 1);
@@ -25991,7 +27038,7 @@ function handleStreamError(err, fallback, exit = process.exit) {
25991
27038
  // package.json
25992
27039
  var package_default = {
25993
27040
  name: "@assinafy/cli",
25994
- version: "2.0.2",
27041
+ version: "2.1.1",
25995
27042
  description: "The official command-line interface for the Assinafy digital-signature API",
25996
27043
  license: "MIT",
25997
27044
  type: "module",
@@ -26020,6 +27067,10 @@ var package_default = {
26020
27067
  "install.sh",
26021
27068
  "install.ps1",
26022
27069
  "README.md",
27070
+ "README.en.md",
27071
+ "CONTRIBUTING.md",
27072
+ "SECURITY.md",
27073
+ ".env.example",
26023
27074
  "LICENSE",
26024
27075
  "THIRD_PARTY_NOTICES.md"
26025
27076
  ],
@@ -26050,7 +27101,6 @@ var package_default = {
26050
27101
  lint: "biome check .",
26051
27102
  "lint:fix": "biome check --write .",
26052
27103
  test: "vitest run",
26053
- "test:sandbox": "npm run build && node scripts/sandbox-smoke.mjs",
26054
27104
  "test:watch": "vitest",
26055
27105
  docs: "npm run build && node scripts/gen-docs.mjs",
26056
27106
  "docs:api": "node scripts/gen-api-reference.mjs",
@@ -26062,11 +27112,11 @@ var package_default = {
26062
27112
  prepublishOnly: "npm run typecheck && npm run lint && npm run test && npm run build && npm run verify:bundle"
26063
27113
  },
26064
27114
  dependencies: {
26065
- "@types/node": "^26.2.0",
26066
- axios: "^1.7.9"
27115
+ "@types/node": "^22.20.1",
27116
+ axios: "^1.20.0"
26067
27117
  },
26068
27118
  devDependencies: {
26069
- "@biomejs/biome": "^2.5.9",
27119
+ "@biomejs/biome": "^2.5.10",
26070
27120
  "@clack/prompts": "^1.7.0",
26071
27121
  "@commander-js/extra-typings": "^15.0.0",
26072
27122
  commander: "^15.0.0",
@@ -26092,7 +27142,7 @@ var program2 = new Command().name("assinafy").description("Assinafy CLI \u2014 t
26092
27142
  `${sanitizeTerminalText(str).replace(/^error:/, () => import_picocolors7.default.red("error:"))}
26093
27143
  `
26094
27144
  )
26095
- }).version(`${PACKAGE_NAME} v${VERSION3}`, "-v, --version", "Output the current version").option("--api-key <key>", "API key (overrides env/config)").option("--token <token>", "Legacy JWT access token (overrides env/config)").option("--account-id <id>", "Default account/workspace ID (overrides env/config)").option("--base-url <url>", "API base URL (overrides env/config)").option("-p, --profile <name>", "Config profile to use (overrides ASSINAFY_PROFILE)").option("--json", "Output machine-readable JSON").option("-q, --quiet", "Suppress spinners and status messages").addHelpText(
27145
+ }).version(`${PACKAGE_NAME} v${VERSION3}`, "-v, --version", "Output the current version").option("--api-key <key>", "API key (overrides env/config)").option("--token <token>", "OAuth access token or user JWT (overrides env/config)").option("--account-id <id>", "Default account/workspace ID (overrides env/config)").option("--base-url <url>", "API base URL (overrides env/config)").option("-p, --profile <name>", "Config profile to use (overrides ASSINAFY_PROFILE)").option("--json", "Output machine-readable JSON").option("-q, --quiet", "Suppress spinners and status messages").addHelpText(
26096
27146
  "after",
26097
27147
  `
26098
27148
  ${import_picocolors7.default.gray("Examples:")}
@@ -26100,11 +27150,11 @@ ${import_picocolors7.default.gray("Examples:")}
26100
27150
  ${import_picocolors7.default.blue("$ assinafy login")} Store an API key
26101
27151
  ${import_picocolors7.default.blue("$ assinafy whoami")} Verify credentials
26102
27152
  ${import_picocolors7.default.blue("$ assinafy documents upload contract.pdf")} Upload a PDF
26103
- ${import_picocolors7.default.blue('$ assinafy send contract.pdf --signer "Ana <ana@x.com>"')}
27153
+ ${import_picocolors7.default.blue('$ assinafy send contract.pdf --signer "Ana <ana@example.com>"')}
26104
27154
 
26105
27155
  ${import_picocolors7.default.gray("Sandbox:")} target it with ${import_picocolors7.default.blue("--base-url https://sandbox.assinafy.com.br/v1")}
26106
27156
  `
26107
- ).addCommand(sendCommand).addCommand(documentsCommand).addCommand(signersCommand).addCommand(assignmentsCommand).addCommand(templatesCommand).addCommand(tagsCommand2).addCommand(fieldsCommand).addCommand(webhooksCommand).addCommand(workspacesCommand).addCommand(usersCommand).addCommand(signerCommand).addCommand(authCommand).addCommand(loginCommand2).addCommand(logoutCommand).addCommand(whoamiCommand).addCommand(configCommand).addCommand(docsCommand);
27157
+ ).addCommand(sendCommand).addCommand(documentsCommand).addCommand(signersCommand).addCommand(assignmentsCommand).addCommand(templatesCommand).addCommand(tagsCommand2).addCommand(fieldsCommand).addCommand(webhooksCommand).addCommand(workspacesCommand).addCommand(usersCommand).addCommand(signerCommand).addCommand(authCommand).addCommand(oauthCommand).addCommand(loginCommand2).addCommand(logoutCommand).addCommand(whoamiCommand).addCommand(configCommand).addCommand(docsCommand);
26108
27158
  program2.parseAsync().catch((err) => {
26109
27159
  process.stderr.write(
26110
27160
  `${import_picocolors7.default.red("error:")} ${sanitizeTerminalText(err instanceof Error ? err.message : String(err))}