@pkcprotocol/pkc-js 0.0.49 → 0.0.51

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 (59) hide show
  1. package/dist/browser/generated-version.d.ts +1 -1
  2. package/dist/browser/generated-version.js +1 -1
  3. package/dist/browser/pkc/pkc.d.ts +2 -1
  4. package/dist/browser/pkc/pkc.js +17 -10
  5. package/dist/browser/pkc/pkc.js.map +1 -1
  6. package/dist/browser/runtime/browser/setup-kubo-address-rewriter-and-http-router.d.ts +1 -0
  7. package/dist/browser/runtime/browser/setup-kubo-address-rewriter-and-http-router.js +4 -0
  8. package/dist/browser/runtime/browser/setup-kubo-address-rewriter-and-http-router.js.map +1 -0
  9. package/dist/browser/runtime/node/address-rewriter-db.d.ts +32 -0
  10. package/dist/browser/runtime/node/address-rewriter-db.js +156 -0
  11. package/dist/browser/runtime/node/address-rewriter-db.js.map +1 -0
  12. package/dist/browser/runtime/node/addresses-rewriter-proxy-server.d.ts +46 -0
  13. package/dist/browser/runtime/node/addresses-rewriter-proxy-server.js +512 -0
  14. package/dist/browser/runtime/node/addresses-rewriter-proxy-server.js.map +1 -0
  15. package/dist/browser/runtime/node/community/local-community/cleanup.js +21 -0
  16. package/dist/browser/runtime/node/community/local-community/cleanup.js.map +1 -1
  17. package/dist/browser/runtime/node/setup-kubo-address-rewriter-and-http-router.d.ts +4 -0
  18. package/dist/browser/runtime/node/{setup-kubo-http-routers.js → setup-kubo-address-rewriter-and-http-router.js} +96 -18
  19. package/dist/browser/runtime/node/setup-kubo-address-rewriter-and-http-router.js.map +1 -0
  20. package/dist/bundled/bundle-manifest.json +43 -26
  21. package/dist/bundled/chunks/{helia-for-pkc-BZ6rZnW_.js → helia-for-pkc-CUP6OHZK.js} +2 -2
  22. package/dist/bundled/chunks/{local-community-CPvHllf9.js → local-community-CvqLy6Ae.js} +1 -1
  23. package/dist/bundled/chunks/{local-community-CbMGlscJ.js → local-community-V8zNa5f6.js} +11 -2
  24. package/dist/bundled/chunks/{node-eJCx_6gz.js → node-Cb3oyWdO.js} +2854 -283
  25. package/dist/bundled/chunks/{rpc-local-community-CTDbXkkP.js → rpc-local-community-DpGUOcjz.js} +1 -1
  26. package/dist/bundled/chunks/{schema-D0I45iuK.js → schema-8LB1qzJT.js} +1 -1
  27. package/dist/bundled/chunks/{util-C0EAYvmS.js → util-f6LWGHSl.js} +1 -1
  28. package/dist/bundled/index.js +1 -1
  29. package/dist/bundled/rpc/src/index.js +4 -4
  30. package/dist/node/generated-version.d.ts +1 -1
  31. package/dist/node/generated-version.js +1 -1
  32. package/dist/node/pkc/pkc.d.ts +2 -1
  33. package/dist/node/pkc/pkc.js +17 -10
  34. package/dist/node/pkc/pkc.js.map +1 -1
  35. package/dist/node/runtime/browser/setup-kubo-address-rewriter-and-http-router.d.ts +1 -0
  36. package/dist/node/runtime/browser/setup-kubo-address-rewriter-and-http-router.js +4 -0
  37. package/dist/node/runtime/browser/setup-kubo-address-rewriter-and-http-router.js.map +1 -0
  38. package/dist/node/runtime/node/address-rewriter-db.d.ts +32 -0
  39. package/dist/node/runtime/node/address-rewriter-db.js +156 -0
  40. package/dist/node/runtime/node/address-rewriter-db.js.map +1 -0
  41. package/dist/node/runtime/node/addresses-rewriter-proxy-server.d.ts +46 -0
  42. package/dist/node/runtime/node/addresses-rewriter-proxy-server.js +512 -0
  43. package/dist/node/runtime/node/addresses-rewriter-proxy-server.js.map +1 -0
  44. package/dist/node/runtime/node/community/local-community/cleanup.js +21 -0
  45. package/dist/node/runtime/node/community/local-community/cleanup.js.map +1 -1
  46. package/dist/node/runtime/node/setup-kubo-address-rewriter-and-http-router.d.ts +4 -0
  47. package/dist/node/runtime/node/{setup-kubo-http-routers.js → setup-kubo-address-rewriter-and-http-router.js} +96 -18
  48. package/dist/node/runtime/node/setup-kubo-address-rewriter-and-http-router.js.map +1 -0
  49. package/package.json +2 -2
  50. package/dist/browser/runtime/browser/setup-kubo-http-routers.d.ts +0 -1
  51. package/dist/browser/runtime/browser/setup-kubo-http-routers.js +0 -4
  52. package/dist/browser/runtime/browser/setup-kubo-http-routers.js.map +0 -1
  53. package/dist/browser/runtime/node/setup-kubo-http-routers.d.ts +0 -2
  54. package/dist/browser/runtime/node/setup-kubo-http-routers.js.map +0 -1
  55. package/dist/node/runtime/browser/setup-kubo-http-routers.d.ts +0 -1
  56. package/dist/node/runtime/browser/setup-kubo-http-routers.js +0 -4
  57. package/dist/node/runtime/browser/setup-kubo-http-routers.js.map +0 -1
  58. package/dist/node/runtime/node/setup-kubo-http-routers.d.ts +0 -2
  59. package/dist/node/runtime/node/setup-kubo-http-routers.js.map +0 -1
@@ -1,9 +1,13 @@
1
- import { B as isIpfsCid, Cn as CommentUpdateForChallengeVerificationSchema, Cr as parsedType, Ct as findUpdatingCommunity, D as deepMergeRuntimeFields, Dr as __require, Dt as refreshTrackedCommentAliases, E as createAbortError, En as CommentUpdateSchema, Et as listUpdatingCommunities, It as require_sha256, L as hideClassPrivateProps, Lt as TimeoutError, Or as __toESM, Pt as untrackUpdatingComment, Q as isStringDomain, Qn as CID, Rt as pTimeout, Sr as joinValues, St as findUpdatingComment, Tr as __commonJSMin, Tt as listUpdatingComments, Xn as require_commonjs, Zn as require_retry, _t as timestamp, a as ChallengeRequestMessageSchema, b as areEquivalentCommunityAddresses, cn as PubsubTopicSchema, cr as logger_default, ct as resolveWhenPredicateIsTrue, dr as setErrorMap, ft as shortifyAddress, jt as trackUpdatingComment, k as doesDomainAddressHaveCapitalLetter, mt as sleepUntilTimeoutOrAbort, nn as CommunityIpfsSchema, or as PKCError, ot as removeUndefinedValuesRecursively, pt as shortifyCid, r as ChallengeMessageSchema, s as ChallengeVerificationMessageSchema, sr as messages, st as replaceXWithY, t as ChallengeAnswerMessageSchema, tr as FailedToFetchCommentIpfsFromGatewaysError, ut as retryKuboIpfsAdd, vn as CommentIpfsSchema, vt as waitForUpdateInCommunityInstanceWithErrorAndTimeout, wr as stringifyPrimitive, wt as listStartedCommunities, xt as findStartedCommunity, y as version_default, z as isAbortError } from "./schema-D0I45iuK.js";
2
- import { $ as PKCClientsManager, $t as parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails, An as RpcCommunityPageParamSchema, At as cleanWireAuthor, B as CommentClientsManager, Bn as RpcSubscriptionIdResultSchema, Ct as verifyCommentModeration, Dn as RpcCidParamSchema, Dt as verifyCommunityEdit, En as RpcCancelExportParamSchema, F as monitorCommunitiesDirectory, Fn as RpcExportCommunityResultSchema, Ft as getCommunityAddressFromRecord, Hn as RpcUnsubscribeParamSchema, In as RpcFetchCidParamSchema, It as getCommunityNameFromWire, J as findCommentInPageInstanceRecursively, Kn as nativeFunctions$2, Ln as RpcFetchCidResultSchema, Lt as getCommunityPublicKeyFromWire, Mn as RpcExportCommunityModLogsParamSchema, Nn as RpcExportCommunityModLogsResultSchema, Nt as normalizeCreatePublicationAuthor, On as RpcCommentRepliesPageParamSchema, Ot as verifyVote, P as listCommunitiesSync, Pn as RpcExportCommunityParamSchema, Pt as buildRuntimeCommunityFields, Q as PublicationClientsManager, R as setNativeFunctions$1, Rn as RpcPublishChallengeAnswersParamSchema, Rt as normalizeCommunityInputFromCommunity, Sn as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, St as verifyCommentIpfs, T as createKuboRpcClient, Tn as RpcAuthorNameParamSchema, Tt as verifyCommentUpdate, Vn as RpcSuccessResultSchema, Vt as getBufferedPKCAddressFromPublicKey, X as parseRawPages, Xt as parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, Z as RepliesPages, Zt as parseCommentIpfsSchemaWithPKCErrorIfItFails, _ as decryptEd25519AesGcm, _n as parseDecryptedChallengeWithPKCErrorIfItFails, a as pkcJsChallenges, at as signChallengeAnswer, bn as parseRpcCommentEventWithPKCErrorIfItFails, bt as verifyChallengeVerification, c as RemoteCommunity, cn as parseCreateCommentOptionsSchemaWithPKCErrorIfItFails, d as decodeRpcChallengeAnswerPubsubMsg, dt as signCommentModeration, en as parseCommentPubsubMessagePublicationWithPKCErrorIfItFails, et as InflightFetchManager, f as decodeRpcChallengePubsubMsg, fn as parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, g as createSigner, gn as parseDecryptedChallengeVerification, gt as signVote, hn as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, ht as signCommunityEdit, in as parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, it as cleanUpBeforePublishing, j as getDefaultDataPath, jn as RpcEditCommunityParamSchema, jt as getAuthorNameFromRuntime, kn as RpcCommunityIdentifierParamSchema, kt as buildRuntimeAuthor, ln as parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails, lt as signComment, m as decodeRpcChallengeVerificationPubsubMsg, mn as parseCreateVoteOptionsSchemaWithPKCErrorIfItFails, n as RpcRemoteCommunity, nt as PKCTypedEmitter, o as TrackedInstanceRegistry, on as parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails, p as decodeRpcChallengeRequestPubsubMsg, pn as parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, q as extractCommunityRuntimeFieldsFromParsedPages, qn as require_undici, qt as parseCidStringSchemaWithPKCErrorIfItFails, rt as require_lib$1, s as LRUCache, sn as parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails, st as signChallengeRequest, t as RpcLocalCommunity, tn as parseCommunityAddressWithPKCErrorIfItFails, u as KeyvBetterSqlite3, ut as signCommentEdit, vn as parseJsonWithPKCErrorIfFails, vt as verifyChallengeMessage, wn as parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails, wt as verifyCommentPubsubMessage, xn as parseRpcCommentUpdateEventWithPKCErrorIfItFails, xt as verifyCommentEdit, y as encryptEd25519AesGcm, yn as parsePKCUserOptionsSchemaWithPKCErrorIfItFails, z as tryToDeleteCommunitiesThatFailedToBeDeletedBefore, zn as RpcResolveAuthorNameResultSchema, zt as decode } from "./rpc-local-community-CTDbXkkP.js";
3
- import { n as getHeliaDebugContext } from "./util-C0EAYvmS.js";
4
- import path from "path";
1
+ import { B as isIpfsCid, Cn as CommentUpdateForChallengeVerificationSchema, Cr as parsedType, Ct as findUpdatingCommunity, D as deepMergeRuntimeFields, Dr as __require, Dt as refreshTrackedCommentAliases, E as createAbortError, En as CommentUpdateSchema, Et as listUpdatingCommunities, It as require_sha256, L as hideClassPrivateProps, Lt as TimeoutError, Or as __toESM, Pt as untrackUpdatingComment, Q as isStringDomain, Qn as CID, Rt as pTimeout, Sr as joinValues, St as findUpdatingComment, Tr as __commonJSMin, Tt as listUpdatingComments, Xn as require_commonjs, Zn as require_retry, _t as timestamp, a as ChallengeRequestMessageSchema, b as areEquivalentCommunityAddresses, cn as PubsubTopicSchema, cr as logger_default, ct as resolveWhenPredicateIsTrue, dr as setErrorMap, ft as shortifyAddress, jt as trackUpdatingComment, k as doesDomainAddressHaveCapitalLetter, lr as require_supports_color, mt as sleepUntilTimeoutOrAbort, nn as CommunityIpfsSchema, or as PKCError, ot as removeUndefinedValuesRecursively, pt as shortifyCid, r as ChallengeMessageSchema, s as ChallengeVerificationMessageSchema, sr as messages, st as replaceXWithY, t as ChallengeAnswerMessageSchema, tr as FailedToFetchCommentIpfsFromGatewaysError, ut as retryKuboIpfsAdd, vn as CommentIpfsSchema, vt as waitForUpdateInCommunityInstanceWithErrorAndTimeout, wr as stringifyPrimitive, wt as listStartedCommunities, xt as findStartedCommunity, y as version_default, z as isAbortError } from "./schema-8LB1qzJT.js";
2
+ import { $ as PKCClientsManager, $t as parseCommentModerationPubsubMessagePublicationSchemaWithPKCErrorIfItFails, An as RpcCommunityPageParamSchema, At as cleanWireAuthor, B as CommentClientsManager, Bn as RpcSubscriptionIdResultSchema, Ct as verifyCommentModeration, Dn as RpcCidParamSchema, Dt as verifyCommunityEdit, En as RpcCancelExportParamSchema, F as monitorCommunitiesDirectory, Fn as RpcExportCommunityResultSchema, Ft as getCommunityAddressFromRecord, Hn as RpcUnsubscribeParamSchema, In as RpcFetchCidParamSchema, It as getCommunityNameFromWire, J as findCommentInPageInstanceRecursively, Kn as nativeFunctions$2, Ln as RpcFetchCidResultSchema, Lt as getCommunityPublicKeyFromWire, Mn as RpcExportCommunityModLogsParamSchema, Nn as RpcExportCommunityModLogsResultSchema, Nt as normalizeCreatePublicationAuthor, On as RpcCommentRepliesPageParamSchema, Ot as verifyVote, P as listCommunitiesSync, Pn as RpcExportCommunityParamSchema, Pt as buildRuntimeCommunityFields, Q as PublicationClientsManager, R as setNativeFunctions$1, Rn as RpcPublishChallengeAnswersParamSchema, Rt as normalizeCommunityInputFromCommunity, Sn as parseSetNewSettingsPKCWsServerSchemaWithPKCErrorIfItFails, St as verifyCommentIpfs, T as createKuboRpcClient, Tn as RpcAuthorNameParamSchema, Tt as verifyCommentUpdate, Vn as RpcSuccessResultSchema, Vt as getBufferedPKCAddressFromPublicKey, X as parseRawPages, Xt as parseCommentEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, Z as RepliesPages, Zt as parseCommentIpfsSchemaWithPKCErrorIfItFails, _ as decryptEd25519AesGcm, _n as parseDecryptedChallengeWithPKCErrorIfItFails, a as pkcJsChallenges, at as signChallengeAnswer, bn as parseRpcCommentEventWithPKCErrorIfItFails, bt as verifyChallengeVerification, c as RemoteCommunity, cn as parseCreateCommentOptionsSchemaWithPKCErrorIfItFails, d as decodeRpcChallengeAnswerPubsubMsg, dt as signCommentModeration, en as parseCommentPubsubMessagePublicationWithPKCErrorIfItFails, et as InflightFetchManager, f as decodeRpcChallengePubsubMsg, fn as parseCreateRemoteCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, g as createSigner, gn as parseDecryptedChallengeVerification, gt as signVote, hn as parseDecryptedChallengeAnswerWithPKCErrorIfItFails, ht as signCommunityEdit, in as parseCommunityEditPubsubMessagePublicationSchemaWithPKCErrorIfItFails, it as cleanUpBeforePublishing, j as getDefaultDataPath, jn as RpcEditCommunityParamSchema, jt as getAuthorNameFromRuntime, kn as RpcCommunityIdentifierParamSchema, kt as buildRuntimeAuthor, ln as parseCreateCommunityEditPublicationOptionsSchemaWithPKCErrorIfItFails, lt as signComment, m as decodeRpcChallengeVerificationPubsubMsg, mn as parseCreateVoteOptionsSchemaWithPKCErrorIfItFails, n as RpcRemoteCommunity, nt as PKCTypedEmitter, o as TrackedInstanceRegistry, on as parseCreateCommentEditOptionsSchemaWithPKCErrorIfItFails, p as decodeRpcChallengeRequestPubsubMsg, pn as parseCreateRpcCommunityFunctionArgumentSchemaWithPKCErrorIfItFails, q as extractCommunityRuntimeFieldsFromParsedPages, qn as require_undici, qt as parseCidStringSchemaWithPKCErrorIfItFails, rt as require_lib$1, s as LRUCache, sn as parseCreateCommentModerationOptionsSchemaWithPKCErrorIfItFails, st as signChallengeRequest, t as RpcLocalCommunity, tn as parseCommunityAddressWithPKCErrorIfItFails, u as KeyvBetterSqlite3, ut as signCommentEdit, vn as parseJsonWithPKCErrorIfFails, vt as verifyChallengeMessage, wn as parseVotePubsubMessagePublicationSchemaWithPKCErrorIfItFails, wt as verifyCommentPubsubMessage, xn as parseRpcCommentUpdateEventWithPKCErrorIfItFails, xt as verifyCommentEdit, y as encryptEd25519AesGcm, yn as parsePKCUserOptionsSchemaWithPKCErrorIfItFails, z as tryToDeleteCommunitiesThatFailedToBeDeletedBefore, zn as RpcResolveAuthorNameResultSchema, zt as decode } from "./rpc-local-community-DpGUOcjz.js";
3
+ import { n as getHeliaDebugContext } from "./util-f6LWGHSl.js";
4
+ import http from "node:http";
5
+ import fs from "node:fs/promises";
6
+ import path from "node:path";
7
+ import path$1 from "path";
5
8
  import assert from "assert";
6
- import fs from "fs";
9
+ import fs$1 from "fs";
10
+ import https from "node:https";
7
11
  import Database from "better-sqlite3";
8
12
  import { of } from "typestub-ipfs-only-hash";
9
13
  import EventEmitter from "events";
@@ -2029,8 +2033,8 @@ var Storage = class {
2029
2033
  let dbFilePath;
2030
2034
  if (this._pkc.noData || !this._pkc.dataPath) dbFilePath = ":memory:";
2031
2035
  else {
2032
- fs.mkdirSync(this._pkc.dataPath, { recursive: true });
2033
- dbFilePath = path.join(this._pkc.dataPath, "storage.db");
2036
+ fs$1.mkdirSync(this._pkc.dataPath, { recursive: true });
2037
+ dbFilePath = path$1.join(this._pkc.dataPath, "storage.db");
2034
2038
  }
2035
2039
  this._db = new Database(dbFilePath);
2036
2040
  this._keyv = new KeyvBetterSqlite3(this._db);
@@ -2437,7 +2441,7 @@ var PKCRpcClient = class extends import_lib.TypedEmitter {
2437
2441
  //#region node_modules/nofilter/lib/index.js
2438
2442
  var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2439
2443
  const stream$5 = __require("stream");
2440
- const { Buffer: Buffer$6 } = __require("buffer");
2444
+ const { Buffer: Buffer$7 } = __require("buffer");
2441
2445
  const td = new TextDecoder("utf8", {
2442
2446
  fatal: true,
2443
2447
  ignoreBOM: true
@@ -2456,7 +2460,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2456
2460
  let inpE = null;
2457
2461
  switch (typeof input) {
2458
2462
  case "object":
2459
- if (Buffer$6.isBuffer(input)) inp = input;
2463
+ if (Buffer$7.isBuffer(input)) inp = input;
2460
2464
  else if (input) options = input;
2461
2465
  break;
2462
2466
  case "string":
@@ -2537,7 +2541,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2537
2541
  */
2538
2542
  static concat(list, length) {
2539
2543
  if (!Array.isArray(list)) throw new TypeError("list argument must be an Array of NoFilters");
2540
- if (list.length === 0 || length === 0) return Buffer$6.alloc(0);
2544
+ if (list.length === 0 || length === 0) return Buffer$7.alloc(0);
2541
2545
  if (length == null) length = list.reduce((tot, nf) => {
2542
2546
  if (!(nf instanceof NoFilter)) throw new TypeError("list argument must be an Array of NoFilters");
2543
2547
  return tot + nf.length;
@@ -2547,11 +2551,11 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2547
2551
  const bufs = list.map((nf) => {
2548
2552
  if (!(nf instanceof NoFilter)) throw new TypeError("list argument must be an Array of NoFilters");
2549
2553
  const buf = nf.slice();
2550
- if (Buffer$6.isBuffer(buf)) allObjs = false;
2554
+ if (Buffer$7.isBuffer(buf)) allObjs = false;
2551
2555
  else allBufs = false;
2552
2556
  return buf;
2553
2557
  });
2554
- if (allBufs) return Buffer$6.concat(bufs, length);
2558
+ if (allBufs) return Buffer$7.concat(bufs, length);
2555
2559
  if (allObjs) return [].concat(...bufs).slice(0, length);
2556
2560
  throw new Error("Concatenating mixed object and byte streams not supported");
2557
2561
  }
@@ -2559,7 +2563,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2559
2563
  * @ignore
2560
2564
  */
2561
2565
  _transform(chunk, encoding, callback) {
2562
- if (!this._readableState.objectMode && !Buffer$6.isBuffer(chunk)) chunk = Buffer$6.from(chunk, encoding);
2566
+ if (!this._readableState.objectMode && !Buffer$7.isBuffer(chunk)) chunk = Buffer$7.from(chunk, encoding);
2563
2567
  this.push(chunk);
2564
2568
  callback();
2565
2569
  }
@@ -2694,7 +2698,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2694
2698
  if (this === other) return 0;
2695
2699
  const buf1 = this.slice();
2696
2700
  const buf2 = other.slice();
2697
- if (Buffer$6.isBuffer(buf1) && Buffer$6.isBuffer(buf2)) return buf1.compare(buf2);
2701
+ if (Buffer$7.isBuffer(buf1) && Buffer$7.isBuffer(buf2)) return buf1.compare(buf2);
2698
2702
  throw new Error("Cannot compare streams in object mode");
2699
2703
  }
2700
2704
  /**
@@ -2722,9 +2726,9 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2722
2726
  if (this._readableState.objectMode) return this._bufArray().slice(start, end);
2723
2727
  const bufs = this._bufArray();
2724
2728
  switch (bufs.length) {
2725
- case 0: return Buffer$6.alloc(0);
2729
+ case 0: return Buffer$7.alloc(0);
2726
2730
  case 1: return bufs[0].slice(start, end);
2727
- default: return Buffer$6.concat(bufs).slice(start, end);
2731
+ default: return Buffer$7.concat(bufs).slice(start, end);
2728
2732
  }
2729
2733
  }
2730
2734
  /**
@@ -2751,7 +2755,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2751
2755
  */
2752
2756
  toJSON() {
2753
2757
  const b = this.slice();
2754
- if (Buffer$6.isBuffer(b)) return b.toJSON();
2758
+ if (Buffer$7.isBuffer(b)) return b.toJSON();
2755
2759
  return b;
2756
2760
  }
2757
2761
  /**
@@ -2767,7 +2771,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2767
2771
  */
2768
2772
  toString(encoding, start, end) {
2769
2773
  const buf = this.slice(start, end);
2770
- if (!Buffer$6.isBuffer(buf)) return JSON.stringify(buf);
2774
+ if (!Buffer$7.isBuffer(buf)) return JSON.stringify(buf);
2771
2775
  if (!encoding || encoding === "utf8") return td.decode(buf);
2772
2776
  return buf.toString(encoding);
2773
2777
  }
@@ -2776,7 +2780,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2776
2780
  */
2777
2781
  [Symbol.for("nodejs.util.inspect.custom")](depth, options) {
2778
2782
  const hex = this._bufArray().map((b) => {
2779
- if (Buffer$6.isBuffer(b)) return options.stylize(b.toString("hex"), "string");
2783
+ if (Buffer$7.isBuffer(b)) return options.stylize(b.toString("hex"), "string");
2780
2784
  return JSON.stringify(b);
2781
2785
  }).join(", ");
2782
2786
  return `${this.constructor.name} [${hex}]`;
@@ -2804,7 +2808,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2804
2808
  str = val.toString(16);
2805
2809
  }
2806
2810
  if (str.length % 2) str = `0${str}`;
2807
- return this.push(Buffer$6.from(str, "hex"));
2811
+ return this.push(Buffer$7.from(str, "hex"));
2808
2812
  }
2809
2813
  /**
2810
2814
  * Read a variable-sized JavaScript unsigned BigInt from the stream.
@@ -2815,7 +2819,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2815
2819
  */
2816
2820
  readUBigInt(len) {
2817
2821
  const b = this.read(len);
2818
- if (!Buffer$6.isBuffer(b)) return null;
2822
+ if (!Buffer$7.isBuffer(b)) return null;
2819
2823
  return BigInt(`0x${b.toString("hex")}`);
2820
2824
  }
2821
2825
  /**
@@ -2828,7 +2832,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2828
2832
  */
2829
2833
  readBigInt(len) {
2830
2834
  const b = this.read(len);
2831
- if (!Buffer$6.isBuffer(b)) return null;
2835
+ if (!Buffer$7.isBuffer(b)) return null;
2832
2836
  let ret = BigInt(`0x${b.toString("hex")}`);
2833
2837
  if (b[0] & 128) {
2834
2838
  const mask = BigInt(1) << BigInt(b.length) * BigInt(8);
@@ -2843,7 +2847,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2843
2847
  * @returns {boolean} True on success.
2844
2848
  */
2845
2849
  writeUInt8(value) {
2846
- const b = Buffer$6.from([value]);
2850
+ const b = Buffer$7.from([value]);
2847
2851
  return this.push(b);
2848
2852
  }
2849
2853
  /**
@@ -2854,7 +2858,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2854
2858
  * @returns {boolean} True on success.
2855
2859
  */
2856
2860
  writeUInt16LE(value) {
2857
- const b = Buffer$6.alloc(2);
2861
+ const b = Buffer$7.alloc(2);
2858
2862
  b.writeUInt16LE(value);
2859
2863
  return this.push(b);
2860
2864
  }
@@ -2866,7 +2870,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2866
2870
  * @returns {boolean} True on success.
2867
2871
  */
2868
2872
  writeUInt16BE(value) {
2869
- const b = Buffer$6.alloc(2);
2873
+ const b = Buffer$7.alloc(2);
2870
2874
  b.writeUInt16BE(value);
2871
2875
  return this.push(b);
2872
2876
  }
@@ -2878,7 +2882,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2878
2882
  * @returns {boolean} True on success.
2879
2883
  */
2880
2884
  writeUInt32LE(value) {
2881
- const b = Buffer$6.alloc(4);
2885
+ const b = Buffer$7.alloc(4);
2882
2886
  b.writeUInt32LE(value);
2883
2887
  return this.push(b);
2884
2888
  }
@@ -2890,7 +2894,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2890
2894
  * @returns {boolean} True on success.
2891
2895
  */
2892
2896
  writeUInt32BE(value) {
2893
- const b = Buffer$6.alloc(4);
2897
+ const b = Buffer$7.alloc(4);
2894
2898
  b.writeUInt32BE(value);
2895
2899
  return this.push(b);
2896
2900
  }
@@ -2901,7 +2905,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2901
2905
  * @returns {boolean} True on success.
2902
2906
  */
2903
2907
  writeInt8(value) {
2904
- const b = Buffer$6.from([value]);
2908
+ const b = Buffer$7.from([value]);
2905
2909
  return this.push(b);
2906
2910
  }
2907
2911
  /**
@@ -2911,7 +2915,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2911
2915
  * @returns {boolean} True on success.
2912
2916
  */
2913
2917
  writeInt16LE(value) {
2914
- const b = Buffer$6.alloc(2);
2918
+ const b = Buffer$7.alloc(2);
2915
2919
  b.writeUInt16LE(value);
2916
2920
  return this.push(b);
2917
2921
  }
@@ -2922,7 +2926,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2922
2926
  * @returns {boolean} True on success.
2923
2927
  */
2924
2928
  writeInt16BE(value) {
2925
- const b = Buffer$6.alloc(2);
2929
+ const b = Buffer$7.alloc(2);
2926
2930
  b.writeUInt16BE(value);
2927
2931
  return this.push(b);
2928
2932
  }
@@ -2933,7 +2937,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2933
2937
  * @returns {boolean} True on success.
2934
2938
  */
2935
2939
  writeInt32LE(value) {
2936
- const b = Buffer$6.alloc(4);
2940
+ const b = Buffer$7.alloc(4);
2937
2941
  b.writeUInt32LE(value);
2938
2942
  return this.push(b);
2939
2943
  }
@@ -2944,7 +2948,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2944
2948
  * @returns {boolean} True on success.
2945
2949
  */
2946
2950
  writeInt32BE(value) {
2947
- const b = Buffer$6.alloc(4);
2951
+ const b = Buffer$7.alloc(4);
2948
2952
  b.writeUInt32BE(value);
2949
2953
  return this.push(b);
2950
2954
  }
@@ -2955,7 +2959,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2955
2959
  * @returns {boolean} True on success.
2956
2960
  */
2957
2961
  writeFloatLE(value) {
2958
- const b = Buffer$6.alloc(4);
2962
+ const b = Buffer$7.alloc(4);
2959
2963
  b.writeFloatLE(value);
2960
2964
  return this.push(b);
2961
2965
  }
@@ -2966,7 +2970,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2966
2970
  * @returns {boolean} True on success.
2967
2971
  */
2968
2972
  writeFloatBE(value) {
2969
- const b = Buffer$6.alloc(4);
2973
+ const b = Buffer$7.alloc(4);
2970
2974
  b.writeFloatBE(value);
2971
2975
  return this.push(b);
2972
2976
  }
@@ -2977,7 +2981,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2977
2981
  * @returns {boolean} True on success.
2978
2982
  */
2979
2983
  writeDoubleLE(value) {
2980
- const b = Buffer$6.alloc(8);
2984
+ const b = Buffer$7.alloc(8);
2981
2985
  b.writeDoubleLE(value);
2982
2986
  return this.push(b);
2983
2987
  }
@@ -2988,7 +2992,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2988
2992
  * @returns {boolean} True on success.
2989
2993
  */
2990
2994
  writeDoubleBE(value) {
2991
- const b = Buffer$6.alloc(8);
2995
+ const b = Buffer$7.alloc(8);
2992
2996
  b.writeDoubleBE(value);
2993
2997
  return this.push(b);
2994
2998
  }
@@ -2999,7 +3003,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2999
3003
  * @returns {boolean} True on success.
3000
3004
  */
3001
3005
  writeBigInt64LE(value) {
3002
- const b = Buffer$6.alloc(8);
3006
+ const b = Buffer$7.alloc(8);
3003
3007
  b.writeBigInt64LE(value);
3004
3008
  return this.push(b);
3005
3009
  }
@@ -3010,7 +3014,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3010
3014
  * @returns {boolean} True on success.
3011
3015
  */
3012
3016
  writeBigInt64BE(value) {
3013
- const b = Buffer$6.alloc(8);
3017
+ const b = Buffer$7.alloc(8);
3014
3018
  b.writeBigInt64BE(value);
3015
3019
  return this.push(b);
3016
3020
  }
@@ -3021,7 +3025,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3021
3025
  * @returns {boolean} True on success.
3022
3026
  */
3023
3027
  writeBigUInt64LE(value) {
3024
- const b = Buffer$6.alloc(8);
3028
+ const b = Buffer$7.alloc(8);
3025
3029
  b.writeBigUInt64LE(value);
3026
3030
  return this.push(b);
3027
3031
  }
@@ -3032,7 +3036,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3032
3036
  * @returns {boolean} True on success.
3033
3037
  */
3034
3038
  writeBigUInt64BE(value) {
3035
- const b = Buffer$6.alloc(8);
3039
+ const b = Buffer$7.alloc(8);
3036
3040
  b.writeBigUInt64BE(value);
3037
3041
  return this.push(b);
3038
3042
  }
@@ -3043,7 +3047,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3043
3047
  */
3044
3048
  readUInt8() {
3045
3049
  const b = this.read(1);
3046
- if (!Buffer$6.isBuffer(b)) return null;
3050
+ if (!Buffer$7.isBuffer(b)) return null;
3047
3051
  return b.readUInt8();
3048
3052
  }
3049
3053
  /**
@@ -3054,7 +3058,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3054
3058
  */
3055
3059
  readUInt16LE() {
3056
3060
  const b = this.read(2);
3057
- if (!Buffer$6.isBuffer(b)) return null;
3061
+ if (!Buffer$7.isBuffer(b)) return null;
3058
3062
  return b.readUInt16LE();
3059
3063
  }
3060
3064
  /**
@@ -3065,7 +3069,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3065
3069
  */
3066
3070
  readUInt16BE() {
3067
3071
  const b = this.read(2);
3068
- if (!Buffer$6.isBuffer(b)) return null;
3072
+ if (!Buffer$7.isBuffer(b)) return null;
3069
3073
  return b.readUInt16BE();
3070
3074
  }
3071
3075
  /**
@@ -3076,7 +3080,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3076
3080
  */
3077
3081
  readUInt32LE() {
3078
3082
  const b = this.read(4);
3079
- if (!Buffer$6.isBuffer(b)) return null;
3083
+ if (!Buffer$7.isBuffer(b)) return null;
3080
3084
  return b.readUInt32LE();
3081
3085
  }
3082
3086
  /**
@@ -3087,7 +3091,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3087
3091
  */
3088
3092
  readUInt32BE() {
3089
3093
  const b = this.read(4);
3090
- if (!Buffer$6.isBuffer(b)) return null;
3094
+ if (!Buffer$7.isBuffer(b)) return null;
3091
3095
  return b.readUInt32BE();
3092
3096
  }
3093
3097
  /**
@@ -3097,7 +3101,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3097
3101
  */
3098
3102
  readInt8() {
3099
3103
  const b = this.read(1);
3100
- if (!Buffer$6.isBuffer(b)) return null;
3104
+ if (!Buffer$7.isBuffer(b)) return null;
3101
3105
  return b.readInt8();
3102
3106
  }
3103
3107
  /**
@@ -3108,7 +3112,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3108
3112
  */
3109
3113
  readInt16LE() {
3110
3114
  const b = this.read(2);
3111
- if (!Buffer$6.isBuffer(b)) return null;
3115
+ if (!Buffer$7.isBuffer(b)) return null;
3112
3116
  return b.readInt16LE();
3113
3117
  }
3114
3118
  /**
@@ -3119,7 +3123,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3119
3123
  */
3120
3124
  readInt16BE() {
3121
3125
  const b = this.read(2);
3122
- if (!Buffer$6.isBuffer(b)) return null;
3126
+ if (!Buffer$7.isBuffer(b)) return null;
3123
3127
  return b.readInt16BE();
3124
3128
  }
3125
3129
  /**
@@ -3130,7 +3134,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3130
3134
  */
3131
3135
  readInt32LE() {
3132
3136
  const b = this.read(4);
3133
- if (!Buffer$6.isBuffer(b)) return null;
3137
+ if (!Buffer$7.isBuffer(b)) return null;
3134
3138
  return b.readInt32LE();
3135
3139
  }
3136
3140
  /**
@@ -3141,7 +3145,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3141
3145
  */
3142
3146
  readInt32BE() {
3143
3147
  const b = this.read(4);
3144
- if (!Buffer$6.isBuffer(b)) return null;
3148
+ if (!Buffer$7.isBuffer(b)) return null;
3145
3149
  return b.readInt32BE();
3146
3150
  }
3147
3151
  /**
@@ -3152,7 +3156,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3152
3156
  */
3153
3157
  readFloatLE() {
3154
3158
  const b = this.read(4);
3155
- if (!Buffer$6.isBuffer(b)) return null;
3159
+ if (!Buffer$7.isBuffer(b)) return null;
3156
3160
  return b.readFloatLE();
3157
3161
  }
3158
3162
  /**
@@ -3163,7 +3167,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3163
3167
  */
3164
3168
  readFloatBE() {
3165
3169
  const b = this.read(4);
3166
- if (!Buffer$6.isBuffer(b)) return null;
3170
+ if (!Buffer$7.isBuffer(b)) return null;
3167
3171
  return b.readFloatBE();
3168
3172
  }
3169
3173
  /**
@@ -3174,7 +3178,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3174
3178
  */
3175
3179
  readDoubleLE() {
3176
3180
  const b = this.read(8);
3177
- if (!Buffer$6.isBuffer(b)) return null;
3181
+ if (!Buffer$7.isBuffer(b)) return null;
3178
3182
  return b.readDoubleLE();
3179
3183
  }
3180
3184
  /**
@@ -3185,7 +3189,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3185
3189
  */
3186
3190
  readDoubleBE() {
3187
3191
  const b = this.read(8);
3188
- if (!Buffer$6.isBuffer(b)) return null;
3192
+ if (!Buffer$7.isBuffer(b)) return null;
3189
3193
  return b.readDoubleBE();
3190
3194
  }
3191
3195
  /**
@@ -3196,7 +3200,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3196
3200
  */
3197
3201
  readBigInt64LE() {
3198
3202
  const b = this.read(8);
3199
- if (!Buffer$6.isBuffer(b)) return null;
3203
+ if (!Buffer$7.isBuffer(b)) return null;
3200
3204
  return b.readBigInt64LE();
3201
3205
  }
3202
3206
  /**
@@ -3207,7 +3211,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3207
3211
  */
3208
3212
  readBigInt64BE() {
3209
3213
  const b = this.read(8);
3210
- if (!Buffer$6.isBuffer(b)) return null;
3214
+ if (!Buffer$7.isBuffer(b)) return null;
3211
3215
  return b.readBigInt64BE();
3212
3216
  }
3213
3217
  /**
@@ -3218,7 +3222,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3218
3222
  */
3219
3223
  readBigUInt64LE() {
3220
3224
  const b = this.read(8);
3221
- if (!Buffer$6.isBuffer(b)) return null;
3225
+ if (!Buffer$7.isBuffer(b)) return null;
3222
3226
  return b.readBigUInt64LE();
3223
3227
  }
3224
3228
  /**
@@ -3229,7 +3233,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3229
3233
  */
3230
3234
  readBigUInt64BE() {
3231
3235
  const b = this.read(8);
3232
- if (!Buffer$6.isBuffer(b)) return null;
3236
+ if (!Buffer$7.isBuffer(b)) return null;
3233
3237
  return b.readBigUInt64BE();
3234
3238
  }
3235
3239
  };
@@ -3310,7 +3314,7 @@ var require_constants = /* @__PURE__ */ __commonJSMin(((exports) => {
3310
3314
  //#endregion
3311
3315
  //#region node_modules/cbor/lib/utils.js
3312
3316
  var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
3313
- const { Buffer: Buffer$5 } = __require("buffer");
3317
+ const { Buffer: Buffer$6 } = __require("buffer");
3314
3318
  const NoFilter = require_lib();
3315
3319
  const stream$4 = __require("stream");
3316
3320
  const { NUMBYTES, SHIFT32, BI, SYMS } = require_constants();
@@ -3336,12 +3340,12 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
3336
3340
  ].every((f) => typeof s[f] === "function");
3337
3341
  }
3338
3342
  exports.isBufferish = function isBufferish(b) {
3339
- return b && typeof b === "object" && (Buffer$5.isBuffer(b) || b instanceof Uint8Array || b instanceof Uint8ClampedArray || b instanceof ArrayBuffer || b instanceof DataView);
3343
+ return b && typeof b === "object" && (Buffer$6.isBuffer(b) || b instanceof Uint8Array || b instanceof Uint8ClampedArray || b instanceof ArrayBuffer || b instanceof DataView);
3340
3344
  };
3341
3345
  exports.bufferishToBuffer = function bufferishToBuffer(b) {
3342
- if (Buffer$5.isBuffer(b)) return b;
3343
- else if (ArrayBuffer.isView(b)) return Buffer$5.from(b.buffer, b.byteOffset, b.byteLength);
3344
- else if (b instanceof ArrayBuffer) return Buffer$5.from(b);
3346
+ if (Buffer$6.isBuffer(b)) return b;
3347
+ else if (ArrayBuffer.isView(b)) return Buffer$6.from(b.buffer, b.byteOffset, b.byteLength);
3348
+ else if (b instanceof ArrayBuffer) return Buffer$6.from(b);
3345
3349
  return null;
3346
3350
  };
3347
3351
  exports.parseCBORint = function parseCBORint(ai, buf) {
@@ -3359,7 +3363,7 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
3359
3363
  }
3360
3364
  };
3361
3365
  exports.writeHalf = function writeHalf(buf, half) {
3362
- const u32 = Buffer$5.allocUnsafe(4);
3366
+ const u32 = Buffer$6.allocUnsafe(4);
3363
3367
  u32.writeFloatBE(half, 0);
3364
3368
  const u = u32.readUInt32BE(0);
3365
3369
  if ((u & 8191) !== 0) return false;
@@ -3391,7 +3395,7 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
3391
3395
  }
3392
3396
  };
3393
3397
  exports.hex = function hex(s) {
3394
- return Buffer$5.from(s.replace(/^0x/, ""), "hex");
3398
+ return Buffer$6.from(s.replace(/^0x/, ""), "hex");
3395
3399
  };
3396
3400
  exports.bin = function bin(s) {
3397
3401
  s = s.replace(/\s/g, "");
@@ -3403,7 +3407,7 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
3403
3407
  start = end;
3404
3408
  end += 8;
3405
3409
  }
3406
- return Buffer$5.from(chunks);
3410
+ return Buffer$6.from(chunks);
3407
3411
  };
3408
3412
  exports.arrayEqual = function arrayEqual(a, b) {
3409
3413
  if (a == null && b == null) return true;
@@ -3895,7 +3899,7 @@ var require_decoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3895
3899
  const utils = require_utils();
3896
3900
  const NoFilter = require_lib();
3897
3901
  const { MT, NUMBYTES, SYMS, BI } = require_constants();
3898
- const { Buffer: Buffer$4 } = __require("buffer");
3902
+ const { Buffer: Buffer$5 } = __require("buffer");
3899
3903
  const COUNT = Symbol("count");
3900
3904
  const MAJOR = Symbol("major type");
3901
3905
  const ERROR = Symbol("error");
@@ -4244,7 +4248,7 @@ var require_decoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4244
4248
  if (this.max_depth >= 0 && depth > this.max_depth) throw new Error(`Maximum depth ${this.max_depth} exceeded`);
4245
4249
  const [octet] = yield 1;
4246
4250
  if (!this.running) {
4247
- this.bs.unshift(Buffer$4.from([octet]));
4251
+ this.bs.unshift(Buffer$5.from([octet]));
4248
4252
  throw new UnexpectedDataError(octet);
4249
4253
  }
4250
4254
  const mt = octet >> 5;
@@ -4292,7 +4296,7 @@ var require_decoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4292
4296
  case 0:
4293
4297
  this.emit("start-string", mt, val, parent_major, parent_length);
4294
4298
  if (mt === MT.UTF8_STRING) val = "";
4295
- else val = this.preferWeb ? new Uint8Array(0) : Buffer$4.allocUnsafe(0);
4299
+ else val = this.preferWeb ? new Uint8Array(0) : Buffer$5.allocUnsafe(0);
4296
4300
  break;
4297
4301
  case -1:
4298
4302
  this.emit("start", mt, SYMS.STREAM, parent_major, parent_length);
@@ -4435,7 +4439,7 @@ var require_commented = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4435
4439
  const Decoder = require_decoder();
4436
4440
  const NoFilter = require_lib();
4437
4441
  const { MT, NUMBYTES, SYMS } = require_constants();
4438
- const { Buffer: Buffer$3 } = __require("buffer");
4442
+ const { Buffer: Buffer$4 } = __require("buffer");
4439
4443
  function plural(c) {
4440
4444
  if (c > 1) return "s";
4441
4445
  return "";
@@ -4717,7 +4721,7 @@ var require_commented = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4717
4721
  break;
4718
4722
  }
4719
4723
  const str = utils.cborValueToString(val, -Infinity);
4720
- if (typeof val === "string" || Buffer$3.isBuffer(val)) {
4724
+ if (typeof val === "string" || Buffer$4.isBuffer(val)) {
4721
4725
  if (val.length > 0) {
4722
4726
  this.push(str);
4723
4727
  this.push("\n");
@@ -4977,7 +4981,7 @@ var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4977
4981
  const NoFilter = require_lib();
4978
4982
  const utils = require_utils();
4979
4983
  const { MT, NUMBYTES, SHIFT32, SIMPLE, SYMS, TAG, BI } = require_constants();
4980
- const { Buffer: Buffer$2 } = __require("buffer");
4984
+ const { Buffer: Buffer$3 } = __require("buffer");
4981
4985
  const HALF = MT.SIMPLE_FLOAT << 5 | NUMBYTES.TWO;
4982
4986
  const FLOAT = MT.SIMPLE_FLOAT << 5 | NUMBYTES.FOUR;
4983
4987
  const DOUBLE = MT.SIMPLE_FLOAT << 5 | NUMBYTES.EIGHT;
@@ -4985,11 +4989,11 @@ var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4985
4989
  const FALSE = MT.SIMPLE_FLOAT << 5 | SIMPLE.FALSE;
4986
4990
  const UNDEFINED = MT.SIMPLE_FLOAT << 5 | SIMPLE.UNDEFINED;
4987
4991
  const NULL = MT.SIMPLE_FLOAT << 5 | SIMPLE.NULL;
4988
- const BREAK = Buffer$2.from([255]);
4989
- const BUF_NAN = Buffer$2.from("f97e00", "hex");
4990
- const BUF_INF_NEG = Buffer$2.from("f9fc00", "hex");
4991
- const BUF_INF_POS = Buffer$2.from("f97c00", "hex");
4992
- const BUF_NEG_ZERO = Buffer$2.from("f98000", "hex");
4992
+ const BREAK = Buffer$3.from([255]);
4993
+ const BUF_NAN = Buffer$3.from("f97e00", "hex");
4994
+ const BUF_INF_NEG = Buffer$3.from("f9fc00", "hex");
4995
+ const BUF_INF_POS = Buffer$3.from("f97c00", "hex");
4996
+ const BUF_NEG_ZERO = Buffer$3.from("f98000", "hex");
4993
4997
  /**
4994
4998
  * Generate the CBOR for a value. If you are using this, you'll either need
4995
4999
  * to call {@link Encoder.write} with a Buffer, or look into the internals of
@@ -5139,7 +5143,7 @@ var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5139
5143
  * @ignore
5140
5144
  */
5141
5145
  _pushUInt8(val) {
5142
- const b = Buffer$2.allocUnsafe(1);
5146
+ const b = Buffer$3.allocUnsafe(1);
5143
5147
  b.writeUInt8(val, 0);
5144
5148
  return this.push(b);
5145
5149
  }
@@ -5149,7 +5153,7 @@ var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5149
5153
  * @ignore
5150
5154
  */
5151
5155
  _pushUInt16BE(val) {
5152
- const b = Buffer$2.allocUnsafe(2);
5156
+ const b = Buffer$3.allocUnsafe(2);
5153
5157
  b.writeUInt16BE(val, 0);
5154
5158
  return this.push(b);
5155
5159
  }
@@ -5159,7 +5163,7 @@ var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5159
5163
  * @ignore
5160
5164
  */
5161
5165
  _pushUInt32BE(val) {
5162
- const b = Buffer$2.allocUnsafe(4);
5166
+ const b = Buffer$3.allocUnsafe(4);
5163
5167
  b.writeUInt32BE(val, 0);
5164
5168
  return this.push(b);
5165
5169
  }
@@ -5169,7 +5173,7 @@ var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5169
5173
  * @ignore
5170
5174
  */
5171
5175
  _pushFloatBE(val) {
5172
- const b = Buffer$2.allocUnsafe(4);
5176
+ const b = Buffer$3.allocUnsafe(4);
5173
5177
  b.writeFloatBE(val, 0);
5174
5178
  return this.push(b);
5175
5179
  }
@@ -5179,7 +5183,7 @@ var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5179
5183
  * @ignore
5180
5184
  */
5181
5185
  _pushDoubleBE(val) {
5182
- const b = Buffer$2.allocUnsafe(8);
5186
+ const b = Buffer$3.allocUnsafe(8);
5183
5187
  b.writeDoubleBE(val, 0);
5184
5188
  return this.push(b);
5185
5189
  }
@@ -5209,7 +5213,7 @@ var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5209
5213
  */
5210
5214
  _pushFloat(obj) {
5211
5215
  if (this.canonical) {
5212
- const b2 = Buffer$2.allocUnsafe(2);
5216
+ const b2 = Buffer$3.allocUnsafe(2);
5213
5217
  if (utils.writeHalf(b2, obj)) return this._pushUInt8(HALF) && this.push(b2);
5214
5218
  }
5215
5219
  if (Math.fround(obj) === obj) return this._pushUInt8(FLOAT) && this._pushFloatBE(obj);
@@ -5273,7 +5277,7 @@ var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5273
5277
  * @ignore
5274
5278
  */
5275
5279
  _pushString(obj) {
5276
- const len = Buffer$2.byteLength(obj, "utf8");
5280
+ const len = Buffer$3.byteLength(obj, "utf8");
5277
5281
  return this._pushInt(len, MT.UTF8_STRING) && this.push(obj, "utf8");
5278
5282
  }
5279
5283
  /**
@@ -5335,7 +5339,7 @@ var require_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5335
5339
  }
5336
5340
  let str = obj.toString(16);
5337
5341
  if (str.length % 2) str = `0${str}`;
5338
- const buf = Buffer$2.from(str, "hex");
5342
+ const buf = Buffer$3.from(str, "hex");
5339
5343
  return this._pushTag(tag) && Encoder._pushBuffer(this, buf);
5340
5344
  }
5341
5345
  /**
@@ -5619,7 +5623,7 @@ Call removeLoopDetectors before resuming.`);
5619
5623
  8: 3
5620
5624
  }[sz];
5621
5625
  if (!gen._pushTag(typ)) return false;
5622
- return Encoder._pushBuffer(gen, Buffer$2.from(obj.buffer, obj.byteOffset, obj.byteLength));
5626
+ return Encoder._pushBuffer(gen, Buffer$3.from(obj.buffer, obj.byteOffset, obj.byteLength));
5623
5627
  }
5624
5628
  /**
5625
5629
  * @param {Encoder} gen Encoder.
@@ -5628,7 +5632,7 @@ Call removeLoopDetectors before resuming.`);
5628
5632
  * @ignore
5629
5633
  */
5630
5634
  static _pushArrayBuffer(gen, obj) {
5631
- return Encoder._pushBuffer(gen, Buffer$2.from(obj));
5635
+ return Encoder._pushBuffer(gen, Buffer$3.from(obj));
5632
5636
  }
5633
5637
  /**
5634
5638
  * Encode the given object with indefinite length. There are apparently
@@ -5736,7 +5740,7 @@ Call removeLoopDetectors before resuming.`);
5736
5740
  const enc = new Encoder(options);
5737
5741
  enc.on("data", (buf) => bufs.push(buf));
5738
5742
  enc.on("error", reject);
5739
- enc.on("finish", () => resolve(Buffer$2.concat(bufs)));
5743
+ enc.on("finish", () => resolve(Buffer$3.concat(bufs)));
5740
5744
  enc.pushAny(obj);
5741
5745
  enc.end();
5742
5746
  });
@@ -5764,7 +5768,7 @@ Call removeLoopDetectors before resuming.`);
5764
5768
  Array: Encoder.pushArray,
5765
5769
  Date: Encoder._pushDate,
5766
5770
  Buffer: Encoder._pushBuffer,
5767
- [Buffer$2.name]: Encoder._pushBuffer,
5771
+ [Buffer$3.name]: Encoder._pushBuffer,
5768
5772
  Map: Encoder._pushMap,
5769
5773
  NoFilter: Encoder._pushNoFilter,
5770
5774
  [NoFilter.name]: Encoder._pushNoFilter,
@@ -5793,7 +5797,7 @@ Call removeLoopDetectors before resuming.`);
5793
5797
  //#endregion
5794
5798
  //#region node_modules/cbor/lib/map.js
5795
5799
  var require_map = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5796
- const { Buffer: Buffer$1 } = __require("buffer");
5800
+ const { Buffer: Buffer$2 } = __require("buffer");
5797
5801
  const encoder = require_encoder();
5798
5802
  const decoder = require_decoder();
5799
5803
  const { MT } = require_constants();
@@ -5923,10 +5927,10 @@ var require_map = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5923
5927
  encodeCBOR(gen) {
5924
5928
  if (!gen._pushInt(this.size, MT.MAP)) return false;
5925
5929
  if (gen.canonical) {
5926
- const entries = Array.from(super.entries()).map((kv) => [Buffer$1.from(kv[0], "base64"), kv[1]]);
5930
+ const entries = Array.from(super.entries()).map((kv) => [Buffer$2.from(kv[0], "base64"), kv[1]]);
5927
5931
  entries.sort((a, b) => a[0].compare(b[0]));
5928
5932
  for (const kv of entries) if (!(gen.push(kv[0]) && gen.pushAny(kv[1]))) return false;
5929
- } else for (const kv of super.entries()) if (!(gen.push(Buffer$1.from(kv[0], "base64")) && gen.pushAny(kv[1]))) return false;
5933
+ } else for (const kv of super.entries()) if (!(gen.push(Buffer$2.from(kv[0], "base64")) && gen.pushAny(kv[1]))) return false;
5930
5934
  return true;
5931
5935
  }
5932
5936
  };
@@ -5995,7 +5999,7 @@ var require_objectRecorder = /* @__PURE__ */ __commonJSMin(((exports, module) =>
5995
5999
  var require_sharedValueEncoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5996
6000
  const Encoder = require_encoder();
5997
6001
  const ObjectRecorder = require_objectRecorder();
5998
- const { Buffer } = __require("buffer");
6002
+ const { Buffer: Buffer$1 } = __require("buffer");
5999
6003
  module.exports = class SharedValueEncoder extends Encoder {
6000
6004
  constructor(opts) {
6001
6005
  super(opts);
@@ -6097,7 +6101,7 @@ var require_sharedValueEncoder = /* @__PURE__ */ __commonJSMin(((exports, module
6097
6101
  const enc = new SharedValueEncoder(options);
6098
6102
  enc.on("data", () => {});
6099
6103
  enc.on("error", reject);
6100
- enc.on("finish", () => resolve(Buffer.concat(bufs)));
6104
+ enc.on("finish", () => resolve(Buffer$1.concat(bufs)));
6101
6105
  enc.pushAny(obj);
6102
6106
  enc.stopRecording();
6103
6107
  enc.removeAllListeners("data");
@@ -6390,7 +6394,7 @@ var LRUStorage = class {
6390
6394
  }
6391
6395
  toJSON() {}
6392
6396
  async init() {
6393
- const dbPath = this._opts.pkc.noData || !this._opts.pkc.dataPath ? `:memory:` : path.join(this._opts.pkc.dataPath, "lru-storage");
6397
+ const dbPath = this._opts.pkc.noData || !this._opts.pkc.dataPath ? `:memory:` : path$1.join(this._opts.pkc.dataPath, "lru-storage");
6394
6398
  this._cache = new SqliteCache({
6395
6399
  database: dbPath,
6396
6400
  cacheTableName: this._opts.cacheName,
@@ -6466,205 +6470,2764 @@ var CommentModeration = class extends Publication {
6466
6470
  }
6467
6471
  };
6468
6472
  //#endregion
6469
- //#region dist/node/runtime/node/setup-kubo-http-routers.js
6470
- function _mergeRouterConfigs(existingConfig, newConfig) {
6471
- if (!existingConfig?.Routers) return newConfig;
6472
- const existingRoutersByEndpoint = /* @__PURE__ */ new Map();
6473
- Object.entries(existingConfig.Routers).forEach(([routerName, router]) => {
6474
- if (router.Parameters?.Endpoint) existingRoutersByEndpoint.set(router.Parameters.Endpoint, {
6475
- routerName,
6476
- router
6477
- });
6478
- });
6479
- const mergedRouters = { ...newConfig.Routers };
6480
- Object.entries(newConfig.Routers).forEach(([newRouterName, newRouter]) => {
6481
- if (newRouter.Parameters?.Endpoint) {
6482
- const existing = existingRoutersByEndpoint.get(newRouter.Parameters.Endpoint);
6483
- if (existing) mergedRouters[newRouterName] = {
6484
- ...existing.router,
6485
- ...newRouter,
6486
- Parameters: {
6487
- ...existing.router.Parameters,
6488
- ...newRouter.Parameters
6489
- }
6490
- };
6473
+ //#region dist/node/runtime/node/address-rewriter-db.js
6474
+ const debug$1 = logger_default("pkc-js:address-rewriter-db");
6475
+ var AddressRewriterDatabase = class {
6476
+ constructor(dataPath, kuboConfig, proxyTarget) {
6477
+ this._db = null;
6478
+ this._dbPath = this._initializeDbPath(dataPath, kuboConfig, proxyTarget);
6479
+ }
6480
+ _initializeDbPath(dataPath, kuboConfig, proxyTarget) {
6481
+ if (!dataPath) throw new Error("dataPath must be defined for request logging");
6482
+ let kuboIdentifier = "unknown";
6483
+ if (kuboConfig && typeof kuboConfig === "object" && "host" in kuboConfig && "port" in kuboConfig) kuboIdentifier = `${kuboConfig.host}_${kuboConfig.port}`;
6484
+ const proxyIdentifier = `${proxyTarget.hostname}_${proxyTarget.port || (proxyTarget.protocol === "https:" ? "443" : "80")}`;
6485
+ const fileName = `address_rewriter_${kuboIdentifier}_${proxyIdentifier}.db`;
6486
+ return path.join(dataPath, ".address-rewriter", fileName);
6487
+ }
6488
+ async initialize() {
6489
+ try {
6490
+ const dbDir = path.dirname(this._dbPath);
6491
+ await fs.mkdir(dbDir, { recursive: true });
6492
+ this._db = new Database(this._dbPath);
6493
+ this._db.exec(`
6494
+ CREATE TABLE IF NOT EXISTS request_logs (
6495
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
6496
+ keys TEXT NOT NULL,
6497
+ received_at INTEGER NOT NULL,
6498
+ transmitted_at INTEGER,
6499
+ success INTEGER NOT NULL,
6500
+ status_code INTEGER,
6501
+ method TEXT NOT NULL,
6502
+ url TEXT NOT NULL,
6503
+ error TEXT,
6504
+ retry_count INTEGER DEFAULT 0,
6505
+ body_preview TEXT,
6506
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
6507
+ )
6508
+ `);
6509
+ this._db.exec(`
6510
+ CREATE TABLE IF NOT EXISTS reprovide_logs (
6511
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
6512
+ key TEXT NOT NULL,
6513
+ timestamp INTEGER NOT NULL,
6514
+ success INTEGER NOT NULL,
6515
+ error TEXT,
6516
+ block_not_local INTEGER DEFAULT 0,
6517
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
6518
+ )
6519
+ `);
6520
+ this._db.exec(`
6521
+ CREATE TABLE IF NOT EXISTS failed_keys (
6522
+ key TEXT PRIMARY KEY,
6523
+ added_at INTEGER NOT NULL,
6524
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
6525
+ )
6526
+ `);
6527
+ this._db.exec(`
6528
+ CREATE INDEX IF NOT EXISTS idx_request_logs_received_at ON request_logs(received_at);
6529
+ CREATE INDEX IF NOT EXISTS idx_reprovide_logs_timestamp ON reprovide_logs(timestamp);
6530
+ CREATE INDEX IF NOT EXISTS idx_reprovide_logs_key ON reprovide_logs(key);
6531
+ `);
6532
+ try {
6533
+ this._db.exec("ALTER TABLE request_logs ADD COLUMN body_preview TEXT");
6534
+ } catch (error) {
6535
+ if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column name")) throw error;
6536
+ }
6537
+ debug$1(`Initialized SQLite database at ${this._dbPath}`);
6538
+ } catch (error) {
6539
+ debug$1.error(`Failed to initialize database at ${this._dbPath}:`, error);
6540
+ throw error;
6491
6541
  }
6492
- });
6493
- return {
6494
- ...newConfig,
6495
- Routers: mergedRouters
6496
- };
6497
- }
6498
- async function _setProvideDhtSweepEnabledOnKuboNode(kuboClient, sweepEnabled) {
6499
- const log = logger_default("pkc-js:pkc:_init:retrySettingHttpRoutersOnIpfsNodes:setProvideDhtSweepEnabledOnIpfsNode");
6500
- const configKey = "Provide.DHT.SweepEnabled";
6501
- const url = `${kuboClient._clientOptions.url}/config?arg=${configKey}&arg=${JSON.stringify(sweepEnabled)}&json=true`;
6502
- try {
6503
- await fetch(url, {
6504
- method: "POST",
6505
- headers: kuboClient._clientOptions.headers
6542
+ }
6543
+ close() {
6544
+ if (this._db) {
6545
+ this._db.close();
6546
+ this._db = null;
6547
+ }
6548
+ }
6549
+ insertRequestLogs(logs) {
6550
+ if (!this._db) throw new Error("Database not initialized");
6551
+ const insertStmt = this._db.prepare(`
6552
+ INSERT INTO request_logs (
6553
+ keys, received_at, transmitted_at, success, status_code,
6554
+ method, url, error, retry_count, body_preview
6555
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
6556
+ `);
6557
+ this._db.transaction(() => {
6558
+ for (const log of logs) insertStmt.run(JSON.stringify(log.keys), log.receivedAt, log.transmittedAt || null, log.success ? 1 : 0, log.statusCode || null, log.method, log.url, log.error || null, log.retryCount || 0, log.bodyPreview || null);
6559
+ })();
6560
+ }
6561
+ insertReprovideLog(key, success, error, blockNotLocal) {
6562
+ if (!this._db) throw new Error("Database not initialized");
6563
+ this._db.prepare(`
6564
+ INSERT INTO reprovide_logs (key, timestamp, success, error, block_not_local)
6565
+ VALUES (?, ?, ?, ?, ?)
6566
+ `).run(key, Date.now(), success ? 1 : 0, error || null, blockNotLocal ? 1 : 0);
6567
+ }
6568
+ loadFailedKeys() {
6569
+ if (!this._db) return [];
6570
+ try {
6571
+ return this._db.prepare("SELECT key FROM failed_keys").all().map((row) => row.key);
6572
+ } catch (error) {
6573
+ debug$1.error("Failed to load failed keys from database:", error);
6574
+ return [];
6575
+ }
6576
+ }
6577
+ saveFailedKeys(keys) {
6578
+ if (!this._db) throw new Error("Database not initialized");
6579
+ this._db.transaction(() => {
6580
+ this._db.exec("DELETE FROM failed_keys");
6581
+ if (keys.length > 0) {
6582
+ const insertStmt = this._db.prepare("INSERT INTO failed_keys (key, added_at) VALUES (?, ?)");
6583
+ const now = Date.now();
6584
+ for (const key of keys) insertStmt.run(key, now);
6585
+ }
6586
+ })();
6587
+ }
6588
+ };
6589
+ //#endregion
6590
+ //#region dist/node/runtime/node/addresses-rewriter-proxy-server.js
6591
+ const debug = logger_default("pkc-js:addresses-rewriter");
6592
+ const MAX_BODY_PREVIEW_BYTES = 4096;
6593
+ var AddressesRewriterProxyServer = class {
6594
+ constructor({ kuboClients: kuboClient, port, hostname, proxyTargetUrl, pkc }) {
6595
+ this._requestLogBuffer = [];
6596
+ this._isWritingLogs = false;
6597
+ this._failedKeys = /* @__PURE__ */ new Set();
6598
+ this._isRetrying = false;
6599
+ this.addresses = {};
6600
+ this.kuboClients = kuboClient;
6601
+ this.port = port;
6602
+ this.hostname = hostname || "127.0.0.1";
6603
+ this.proxyTarget = new URL(proxyTargetUrl);
6604
+ this.server = http.createServer((req, res) => this._proxyRequestRewrite(req, res));
6605
+ this._storageKeyName = `httprouter_proxy_${proxyTargetUrl}`;
6606
+ this._pkc = pkc;
6607
+ const envValue = process.env.ENABLE_LOGGING_OF_ADDRESS_REWRITER_PROXY;
6608
+ this._loggingEnabled = envValue === "1" || envValue?.toLowerCase() === "true";
6609
+ if (this._loggingEnabled) {
6610
+ const kuboConfig = this.kuboClients?.[0]?.getEndpointConfig();
6611
+ this._db = new AddressRewriterDatabase(this._pkc.dataPath, kuboConfig, this.proxyTarget);
6612
+ } else this._db = null;
6613
+ this._httpAgent = new http.Agent({
6614
+ keepAlive: true,
6615
+ keepAliveMsecs: 3e4,
6616
+ maxSockets: 50,
6617
+ timeout: 1e4
6506
6618
  });
6507
- } catch (e) {
6508
- const error = new PKCError("ERR_FAILED_TO_SET_CONFIG_ON_KUBO_NODE", {
6509
- fullUrl: url,
6510
- actualError: e,
6511
- kuboEndpoint: kuboClient._clientOptions.url,
6512
- configKey,
6513
- configValueToBeSet: sweepEnabled
6619
+ this._httpsAgent = new https.Agent({
6620
+ keepAlive: true,
6621
+ keepAliveMsecs: 3e4,
6622
+ maxSockets: 50,
6623
+ timeout: 1e4
6514
6624
  });
6515
- log.error(e);
6516
- throw error;
6625
+ hideClassPrivateProps(this);
6517
6626
  }
6518
- log.trace("Succeeded in setting config key", configKey, "on node", kuboClient._clientOptions.url, "to be", sweepEnabled);
6519
- }
6520
- async function _setHttpRouterOptionsOnKuboNode(kuboClient, routingValue) {
6521
- const log = logger_default("pkc-js:pkc:_init:retrySettingHttpRoutersOnIpfsNodes:setHttpRouterOptionsOnIpfsNode");
6522
- const routingKey = "Routing";
6523
- let routingConfigBeforeChanging;
6524
- try {
6525
- routingConfigBeforeChanging = await kuboClient._client.config.get(routingKey);
6526
- } catch (e) {
6527
- const error = new PKCError("ERR_FAILED_TO_GET_CONFIG_ON_KUBO_NODE", {
6528
- actualError: e,
6529
- kuboEndpoint: kuboClient._clientOptions.url,
6530
- configKey: routingKey
6531
- });
6532
- log.error(e);
6533
- throw error;
6627
+ async listen(callback) {
6628
+ if (this._loggingEnabled && this._db) {
6629
+ await this._db.initialize();
6630
+ debug("Request logging enabled for addresses rewriter proxy");
6631
+ } else debug("Request logging disabled for addresses rewriter proxy");
6632
+ await this._startUpdateAddressesLoop();
6633
+ if (this._loggingEnabled) this._startRequestLogging();
6634
+ await this._startFailedKeysRetry();
6635
+ this.server.on("error", (err) => debug.error("Error with address rewriter proxy", this.server.address(), "Proxy target", this.proxyTarget, err));
6636
+ this.server.listen(this.port, this.hostname, callback);
6637
+ debug("Addresses rewriter proxy at", this.hostname + ":" + this.port, "started listening to forward requests to", this.proxyTarget.host, `- request logging ${this._loggingEnabled ? "enabled" : "disabled"}`);
6638
+ await this._pkc._storage.setItem(this._storageKeyName, `http://${this.hostname}:${this.port}`);
6534
6639
  }
6535
- const mergedRoutingValue = _mergeRouterConfigs(routingConfigBeforeChanging, routingValue);
6536
- const url = `${kuboClient._clientOptions.url}/config?arg=${routingKey}&arg=${JSON.stringify(mergedRoutingValue)}&json=true`;
6537
- try {
6538
- await fetch(url, {
6539
- method: "POST",
6540
- headers: kuboClient._clientOptions.headers
6640
+ async destroy() {
6641
+ this.server.close();
6642
+ if (this._updateAddressesInterval) clearInterval(this._updateAddressesInterval);
6643
+ if (this._logWriteInterval) clearInterval(this._logWriteInterval);
6644
+ if (this._retryInterval) clearInterval(this._retryInterval);
6645
+ await this._writeRequestLogs();
6646
+ this._db?.close();
6647
+ this._httpAgent.destroy();
6648
+ this._httpsAgent.destroy();
6649
+ await this._pkc._storage.removeItem(this._storageKeyName);
6650
+ }
6651
+ _proxyRequestRewrite(req, res) {
6652
+ let reqBody = "";
6653
+ req.on("data", (chunk) => {
6654
+ reqBody += chunk.toString();
6541
6655
  });
6542
- } catch (e) {
6543
- const error = new PKCError("ERR_FAILED_TO_SET_CONFIG_ON_KUBO_NODE", {
6544
- fullUrl: url,
6545
- actualError: e,
6546
- kuboEndpoint: kuboClient._clientOptions.url,
6547
- configKey: routingKey,
6548
- configValueToBeSet: mergedRoutingValue
6656
+ req.on("end", () => {
6657
+ const shouldRewrite = req.method === "PUT" || req.method === "POST";
6658
+ let requestLogEntry = null;
6659
+ if (shouldRewrite) {
6660
+ const keys = this._extractKeysFromRequestBody(reqBody);
6661
+ const shouldLogRequest = this._loggingEnabled;
6662
+ if (keys.length > 0 || shouldLogRequest) {
6663
+ requestLogEntry = {
6664
+ keys,
6665
+ receivedAt: Date.now(),
6666
+ success: false,
6667
+ method: req.method || "UNKNOWN",
6668
+ url: req.url || "/",
6669
+ retryCount: 0,
6670
+ bodyPreview: shouldLogRequest ? this._createBodyPreview(reqBody) : void 0
6671
+ };
6672
+ if (shouldLogRequest) this._requestLogBuffer.push(requestLogEntry);
6673
+ }
6674
+ }
6675
+ let rewrittenBody = reqBody;
6676
+ if (shouldRewrite && rewrittenBody) try {
6677
+ const json = JSON.parse(rewrittenBody);
6678
+ if (json.Providers && Array.isArray(json.Providers)) {
6679
+ for (const provider of json.Providers) {
6680
+ const peerId = provider?.Payload?.ID;
6681
+ if (peerId && this.addresses[peerId]) provider.Payload.Addrs = this.addresses[peerId];
6682
+ }
6683
+ rewrittenBody = JSON.stringify(json);
6684
+ }
6685
+ } catch (e) {
6686
+ debug("proxy body rewrite error:", e, "body", rewrittenBody, req.url, req.method);
6687
+ }
6688
+ this._proxyRequest(req, res, rewrittenBody, requestLogEntry);
6689
+ });
6690
+ req.on("error", (err) => {
6691
+ debug.trace("Request error:", req.url, req.method, req.headers, reqBody, err);
6692
+ if (!res.headersSent) {
6693
+ debug.trace("Request error:", req.url, req.method, req.headers, reqBody, err);
6694
+ res.writeHead(500);
6695
+ res.end("Internal Server Error");
6696
+ }
6549
6697
  });
6550
- log.error(e);
6551
- throw error;
6552
6698
  }
6553
- log.trace("Succeeded in setting config key", routingKey, "on node", kuboClient._clientOptions.url, "to be", mergedRoutingValue);
6554
- await _setProvideDhtSweepEnabledOnKuboNode(kuboClient, false);
6555
- const endpointsBefore = Object.values(routingConfigBeforeChanging?.["Routers"] || {}).map((router) => router["Parameters"]["Endpoint"]);
6556
- const endpointsAfter = Object.values(mergedRoutingValue.Routers).map((router) => router["Parameters"]["Endpoint"]);
6557
- if (!import_commonjs.isDeepEqual(endpointsBefore.sort(), endpointsAfter.sort())) {
6558
- log("Config on kubo node has been changed. PKC-js will send shutdown command to node", kuboClient._clientOptions.url, "Clients of pkc-js should restart ipfs node");
6559
- const shutdownUrl = `${kuboClient._clientOptions.url}/shutdown`;
6560
- try {
6561
- await fetch(shutdownUrl, {
6562
- method: "POST",
6563
- headers: kuboClient._clientOptions.headers
6699
+ _proxyRequest(req, res, rewrittenBody, requestLogEntry) {
6700
+ if (requestLogEntry) {
6701
+ requestLogEntry.retryCount = 0;
6702
+ requestLogEntry.transmittedAt = Date.now();
6703
+ }
6704
+ const { request: httpRequest } = this.proxyTarget.protocol === "https:" ? https : http;
6705
+ const agent = this.proxyTarget.protocol === "https:" ? this._httpsAgent : this._httpAgent;
6706
+ const requestOptions = {
6707
+ hostname: this.proxyTarget.hostname,
6708
+ protocol: this.proxyTarget.protocol,
6709
+ path: req.url,
6710
+ method: req.method,
6711
+ headers: {
6712
+ ...req.headers,
6713
+ "content-length": Buffer.byteLength(rewrittenBody),
6714
+ host: this.proxyTarget.host
6715
+ },
6716
+ agent,
6717
+ timeout: 1e4
6718
+ };
6719
+ if (this.proxyTarget.port) requestOptions.port = this.proxyTarget.port;
6720
+ const proxyReq = httpRequest(requestOptions);
6721
+ proxyReq.setTimeout(1e4, () => {
6722
+ debug.trace("Proxy request timed out", requestOptions);
6723
+ if (requestLogEntry) {
6724
+ requestLogEntry.success = false;
6725
+ requestLogEntry.statusCode = 504;
6726
+ requestLogEntry.error = "Request timeout";
6727
+ if (requestLogEntry.keys) {
6728
+ const sizeBefore = this._failedKeys.size;
6729
+ requestLogEntry.keys.forEach((key) => this._failedKeys.add(key));
6730
+ if (this._failedKeys.size > sizeBefore) this._saveFailedKeysToDatabase();
6731
+ }
6732
+ }
6733
+ proxyReq.destroy();
6734
+ if (!res.headersSent) {
6735
+ res.writeHead(504);
6736
+ res.end("Gateway Timeout");
6737
+ }
6738
+ });
6739
+ proxyReq.on("error", (e) => {
6740
+ proxyReq.destroy();
6741
+ if (requestLogEntry) {
6742
+ requestLogEntry.success = false;
6743
+ requestLogEntry.statusCode = 500;
6744
+ requestLogEntry.error = `Proxy error: ${e.message}`;
6745
+ debug.trace(`Updated log entry with error for keys: ${requestLogEntry.keys.join(", ")}`);
6746
+ if (requestLogEntry.keys) {
6747
+ const sizeBefore = this._failedKeys.size;
6748
+ requestLogEntry.keys.forEach((key) => this._failedKeys.add(key));
6749
+ if (this._failedKeys.size > sizeBefore) this._saveFailedKeysToDatabase();
6750
+ }
6751
+ }
6752
+ if (!res.headersSent) {
6753
+ debug.trace("address rewriter proxy error:", e, "Request options", requestOptions);
6754
+ res.writeHead(500);
6755
+ res.end("Internal Server Error");
6756
+ }
6757
+ });
6758
+ proxyReq.on("response", (proxyRes) => {
6759
+ const statusCode = proxyRes.statusCode || 500;
6760
+ const isSuccess = statusCode >= 200 && statusCode < 300;
6761
+ if (requestLogEntry) {
6762
+ requestLogEntry.success = isSuccess;
6763
+ requestLogEntry.statusCode = statusCode;
6764
+ if (!isSuccess) {
6765
+ requestLogEntry.error = `HTTP ${statusCode}`;
6766
+ if (requestLogEntry.keys) {
6767
+ const sizeBefore = this._failedKeys.size;
6768
+ requestLogEntry.keys.forEach((key) => this._failedKeys.add(key));
6769
+ if (this._failedKeys.size > sizeBefore) this._saveFailedKeysToDatabase();
6770
+ }
6771
+ }
6772
+ }
6773
+ proxyRes.on("error", (err) => {
6774
+ debug.trace("Proxy response error:", err);
6775
+ if (!res.headersSent) {
6776
+ res.writeHead(500);
6777
+ res.end("Proxy Response Error");
6778
+ }
6779
+ if (requestLogEntry) {
6780
+ requestLogEntry.success = false;
6781
+ requestLogEntry.statusCode = 500;
6782
+ requestLogEntry.error = `Proxy response error: ${err.message}`;
6783
+ }
6784
+ proxyRes.destroy(err);
6564
6785
  });
6565
- } catch (e) {
6566
- const error = new PKCError("ERR_FAILED_TO_SHUTDOWN_KUBO_NODE", {
6567
- actualError: e,
6568
- kuboEndpoint: kuboClient._clientOptions.url,
6569
- shutdownUrl
6786
+ if (!res.headersSent) {
6787
+ res.writeHead(statusCode, proxyRes.headers);
6788
+ proxyRes.pipe(res);
6789
+ }
6790
+ res.on("finish", () => {
6791
+ proxyRes.resume();
6570
6792
  });
6571
- log.error(e);
6572
- throw error;
6573
- }
6574
- }
6575
- }
6576
- async function setupKuboHttpRouters(pkc) {
6577
- if (pkc.destroyed) return;
6578
- if (!Array.isArray(pkc.kuboRpcClientsOptions) || pkc.kuboRpcClientsOptions.length <= 0) throw Error("need ipfs http client to be defined");
6579
- if (!Array.isArray(pkc.httpRoutersOptions) || pkc.httpRoutersOptions.length <= 0) throw Error("Need http router options to defined");
6580
- const httpRouterUrls = [...pkc.httpRoutersOptions].sort();
6581
- const kuboClients = pkc.clients.kuboRpcClients;
6582
- const httpRoutersConfig = {
6583
- HttpRoutersParallel: {
6584
- Type: "parallel",
6585
- Parameters: { Routers: [] }
6586
- },
6587
- HttpRouterNotSupported: {
6588
- Type: "http",
6589
- Parameters: { Endpoint: "http://kubohttprouternotsupported" }
6590
- }
6591
- };
6592
- for (const [i, httpRouterUrl] of httpRouterUrls.entries()) {
6593
- const RouterName = `HttpRouter${i + 1}`;
6594
- httpRoutersConfig[RouterName] = {
6595
- Type: "http",
6596
- Parameters: { Endpoint: httpRouterUrl }
6793
+ });
6794
+ proxyReq.write(rewrittenBody);
6795
+ proxyReq.end();
6796
+ }
6797
+ async _startUpdateAddressesLoop() {
6798
+ if (!this.kuboClients?.length) throw Error("should have a defined kubo rpc client option to start the address rewriter");
6799
+ const isRetriableError = (error) => {
6800
+ if (typeof error !== "object" || error === null) return false;
6801
+ const err = error;
6802
+ return err.response?.status === 500 || err.status === 500 || err.statusCode === 500;
6597
6803
  };
6598
- httpRoutersConfig.HttpRoutersParallel.Parameters.Routers[i] = {
6599
- RouterName,
6600
- IgnoreErrors: true,
6601
- Timeout: "10s"
6804
+ const tryUpdateAddressesForClient = async (kuboClient) => {
6805
+ return new Promise((resolve) => {
6806
+ const operation = import_retry.operation({
6807
+ retries: 3,
6808
+ factor: 2,
6809
+ minTimeout: 1e3,
6810
+ maxTimeout: 8e3
6811
+ });
6812
+ operation.attempt(async (currentAttempt) => {
6813
+ try {
6814
+ const idRes = await kuboClient.id();
6815
+ const swarmAddrsRes = await kuboClient.swarm.addrs();
6816
+ const peerId = idRes.id.toString();
6817
+ if (typeof peerId !== "string") throw Error("Failed to get Peer ID of kubo node");
6818
+ const swarmListeningAddresses = swarmAddrsRes.filter((swarmAddr) => swarmAddr.id.toString() === peerId);
6819
+ const addresses = import_commonjs.unique([...idRes.addresses.map((addr) => addr.toString()), ...import_commonjs.flatten(swarmListeningAddresses.map((swarmAddr) => swarmAddr.addrs.map((addr) => addr.toString())))]);
6820
+ if (addresses.length === 0) throw Error(`Failed to get any addresses for peer ${peerId}`);
6821
+ this.addresses[peerId] = addresses;
6822
+ resolve();
6823
+ } catch (e) {
6824
+ const error = e;
6825
+ if (isRetriableError(error)) {
6826
+ debug(`tryUpdateAddresses attempt ${currentAttempt}/4 failed with 500 error:`, error.message, { kuboConfig: kuboClient.getEndpointConfig() });
6827
+ if (operation.retry(error)) return;
6828
+ }
6829
+ debug("tryUpdateAddresses error:", error.message, { kuboConfig: kuboClient.getEndpointConfig() });
6830
+ resolve();
6831
+ }
6832
+ });
6833
+ });
6602
6834
  };
6835
+ const tryUpdateAddresses = async () => {
6836
+ const promises = this.kuboClients.map(tryUpdateAddressesForClient);
6837
+ await Promise.allSettled(promises);
6838
+ };
6839
+ await tryUpdateAddresses();
6840
+ this._updateAddressesInterval = setInterval(tryUpdateAddresses, 1e3 * 60);
6603
6841
  }
6604
- const routingValue = {
6605
- Type: "custom",
6606
- Methods: {
6607
- "find-providers": { RouterName: "HttpRoutersParallel" },
6608
- provide: { RouterName: "HttpRoutersParallel" },
6609
- "find-peers": { RouterName: "HttpRouterNotSupported" },
6610
- "get-ipns": { RouterName: "HttpRouterNotSupported" },
6611
- "put-ipns": { RouterName: "HttpRouterNotSupported" }
6612
- },
6613
- Routers: httpRoutersConfig
6614
- };
6615
- const settingOptionRetryOption = import_retry.operation({
6616
- forever: true,
6617
- factor: 2
6618
- });
6619
- await new Promise((resolve) => {
6620
- settingOptionRetryOption.attempt(async (curAttempt) => {
6621
- if (pkc.destroyed) {
6622
- resolve(1);
6623
- return;
6842
+ _extractKeysFromRequestBody(body) {
6843
+ try {
6844
+ const json = JSON.parse(body);
6845
+ const keys = [];
6846
+ if (json.Providers && Array.isArray(json.Providers)) {
6847
+ for (const provider of json.Providers) if (provider?.Payload?.Keys) keys.push(...provider.Payload.Keys);
6624
6848
  }
6625
- for (const kuboClient of Object.values(kuboClients)) try {
6626
- await _setHttpRouterOptionsOnKuboNode(kuboClient, routingValue);
6627
- } catch (e) {
6628
- settingOptionRetryOption.retry(e);
6849
+ return keys;
6850
+ } catch {
6851
+ return [];
6852
+ }
6853
+ }
6854
+ _createBodyPreview(body) {
6855
+ const buffer = Buffer.from(body, "utf8");
6856
+ if (buffer.length <= MAX_BODY_PREVIEW_BYTES) return body;
6857
+ return `${buffer.subarray(0, MAX_BODY_PREVIEW_BYTES).toString("utf8")}...[truncated ${buffer.length - MAX_BODY_PREVIEW_BYTES} bytes]`;
6858
+ }
6859
+ async _writeRequestLogs() {
6860
+ if (!this._loggingEnabled || !this._db) return;
6861
+ if (this._requestLogBuffer.length === 0 || this._isWritingLogs) return;
6862
+ this._isWritingLogs = true;
6863
+ const logsToWrite = [...this._requestLogBuffer];
6864
+ this._requestLogBuffer = [];
6865
+ try {
6866
+ this._db.insertRequestLogs(logsToWrite);
6867
+ debug.trace(`Wrote ${logsToWrite.length} new request log entries to SQLite database`);
6868
+ } catch (error) {
6869
+ debug.error(`Failed to write request logs to SQLite database:`, error);
6870
+ this._requestLogBuffer.unshift(...logsToWrite);
6871
+ } finally {
6872
+ this._isWritingLogs = false;
6873
+ }
6874
+ }
6875
+ _startRequestLogging() {
6876
+ if (!this._loggingEnabled || !this._db) return;
6877
+ const writeInterval = 5 * 1e3;
6878
+ this._logWriteInterval = setInterval(async () => {
6879
+ await this._writeRequestLogs();
6880
+ }, writeInterval);
6881
+ }
6882
+ async _startFailedKeysRetry() {
6883
+ this._loadFailedKeysFromDatabase();
6884
+ const retryInterval = 120 * 1e3;
6885
+ this._retryInterval = setInterval(async () => {
6886
+ if (this._isRetrying) {
6887
+ debug.trace("Previous failed-keys retry still running, skipping this tick");
6629
6888
  return;
6630
6889
  }
6631
- resolve(1);
6632
- });
6633
- });
6634
- settingOptionRetryOption.stop();
6635
- }
6636
- //#endregion
6637
- //#region dist/node/publications/community-edit/community-edit.js
6638
- var CommunityEdit = class extends Publication {
6639
- constructor(pkc) {
6640
- super(pkc);
6641
- this.raw = {};
6642
- this.publish = this.publish.bind(this);
6643
- hideClassPrivateProps(this);
6890
+ this._isRetrying = true;
6891
+ try {
6892
+ await this._retryFailedKeys();
6893
+ } finally {
6894
+ this._isRetrying = false;
6895
+ }
6896
+ }, retryInterval);
6897
+ debug(`Started failed keys retry with ${this._failedKeys.size} keys from previous sessions`);
6644
6898
  }
6645
- _initUnsignedLocalProps(opts) {
6646
- super._initUnsignedLocalProps(opts);
6647
- const o = opts.unsignedOptions;
6648
- this.communityEdit = o.communityEdit;
6899
+ _loadFailedKeysFromDatabase() {
6900
+ if (!this._loggingEnabled || !this._db) return;
6901
+ try {
6902
+ const keys = this._db.loadFailedKeys();
6903
+ keys.forEach((key) => this._failedKeys.add(key));
6904
+ debug(`Loaded ${keys.length} failed keys from database`);
6905
+ } catch (error) {
6906
+ debug.error("Failed to load failed keys from database:", error);
6907
+ throw error;
6908
+ }
6649
6909
  }
6650
- _initLocalProps(props) {
6651
- this._initRemoteProps(props.communityEdit);
6652
- this.challengeRequest = props.challengeRequest;
6653
- this.signer = props.signer;
6910
+ _saveFailedKeysToDatabase() {
6911
+ if (!this._loggingEnabled || !this._db) return;
6912
+ try {
6913
+ const keys = Array.from(this._failedKeys);
6914
+ this._db.saveFailedKeys(keys);
6915
+ if (keys.length === 0) debug.trace(`All keys successfully provided - no failed keys to save`);
6916
+ else debug.trace(`Saved ${keys.length} failed keys to database`);
6917
+ } catch (error) {
6918
+ debug.error("Failed to save failed keys to database:", error);
6919
+ throw error;
6920
+ }
6654
6921
  }
6655
- async _signPublicationOptionsToPublish(cleanedPublication) {
6656
- return signCommunityEdit({
6657
- communityEdit: cleanedPublication,
6658
- pkc: this._pkc
6659
- });
6922
+ async _retryFailedKeys() {
6923
+ if (this._failedKeys.size === 0) {
6924
+ debug.trace(`No failed keys to retry - all keys successfully provided`);
6925
+ return;
6926
+ }
6927
+ debug(`Retrying ${this._failedKeys.size} failed keys`);
6928
+ const keysToRetry = Array.from(this._failedKeys);
6929
+ const kuboClient = this.kuboClients?.[0];
6930
+ if (!kuboClient) {
6931
+ debug.error("No kubo client available for retry");
6932
+ return;
6933
+ }
6934
+ const successfulKeys = [];
6935
+ const stillFailedKeys = [];
6936
+ const keysToDiscard = [];
6937
+ for (const key of keysToRetry) try {
6938
+ debug.trace(`Providing key to HTTP routers: ${key}`);
6939
+ const events = [];
6940
+ for await (const event of kuboClient.routing.provide(key, {
6941
+ recursive: true,
6942
+ verbose: true
6943
+ })) {
6944
+ events.push(event);
6945
+ debug(`Routing provide event for ${key}:`, event);
6946
+ }
6947
+ successfulKeys.push(key);
6948
+ debug.trace(`Successfully provided key: ${key}`);
6949
+ this._logReprovideAttempt(key, true, void 0, false);
6950
+ } catch (error) {
6951
+ const errorMessage = error instanceof Error ? error.message : String(error);
6952
+ const isBlockNotLocal = errorMessage.includes("block") && errorMessage.includes("not found locally");
6953
+ this._logReprovideAttempt(key, false, errorMessage, isBlockNotLocal);
6954
+ if (isBlockNotLocal) {
6955
+ keysToDiscard.push(key);
6956
+ debug.trace(`Discarding key ${key} - block not found locally, will not retry`);
6957
+ } else {
6958
+ stillFailedKeys.push(key);
6959
+ debug.trace(`Failed to provide key ${key}:`, error);
6960
+ }
6961
+ }
6962
+ successfulKeys.forEach((key) => this._failedKeys.delete(key));
6963
+ keysToDiscard.forEach((key) => this._failedKeys.delete(key));
6964
+ this._saveFailedKeysToDatabase();
6965
+ debug.trace(`Retry completed: ${successfulKeys.length} successful, ${stillFailedKeys.length} still failed, ${keysToDiscard.length} discarded`);
6660
6966
  }
6661
- _initRemoteProps(props) {
6662
- super._initBaseRemoteProps(props);
6663
- this.communityEdit = props.communityEdit;
6664
- this.raw.pubsubMessageToPublish = props;
6967
+ _logReprovideAttempt(key, success, error, blockNotLocal) {
6968
+ if (!this._loggingEnabled || !this._db) return;
6969
+ try {
6970
+ this._db.insertReprovideLog(key, success, error, blockNotLocal);
6971
+ debug.trace(`Logged reprovide attempt for key ${key}: success=${success}, blockNotLocal=${blockNotLocal}`);
6972
+ } catch (error) {
6973
+ debug.error(`Failed to log reprovide attempt for key ${key}:`, error);
6974
+ throw error;
6975
+ }
6665
6976
  }
6666
- getType() {
6667
- return "communityEdit";
6977
+ };
6978
+ //#endregion
6979
+ //#region node_modules/deep-is/index.js
6980
+ var require_deep_is = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6981
+ var pSlice = Array.prototype.slice;
6982
+ var Object_keys = typeof Object.keys === "function" ? Object.keys : function(obj) {
6983
+ var keys = [];
6984
+ for (var key in obj) keys.push(key);
6985
+ return keys;
6986
+ };
6987
+ var deepEqual = module.exports = function(actual, expected) {
6988
+ if (actual === 0 && expected === 0) return areZerosEqual(actual, expected);
6989
+ else if (actual === expected) return true;
6990
+ else if (actual instanceof Date && expected instanceof Date) return actual.getTime() === expected.getTime();
6991
+ else if (isNumberNaN(actual)) return isNumberNaN(expected);
6992
+ else if (typeof actual != "object" && typeof expected != "object") return actual == expected;
6993
+ else return objEquiv(actual, expected);
6994
+ };
6995
+ function isUndefinedOrNull(value) {
6996
+ return value === null || value === void 0;
6997
+ }
6998
+ function isArguments(object) {
6999
+ return Object.prototype.toString.call(object) == "[object Arguments]";
7000
+ }
7001
+ function isNumberNaN(value) {
7002
+ return typeof value == "number" && value !== value;
7003
+ }
7004
+ function areZerosEqual(zeroA, zeroB) {
7005
+ return 1 / zeroA === 1 / zeroB;
7006
+ }
7007
+ function objEquiv(a, b) {
7008
+ if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false;
7009
+ if (a.prototype !== b.prototype) return false;
7010
+ if (isArguments(a)) {
7011
+ if (!isArguments(b)) return false;
7012
+ a = pSlice.call(a);
7013
+ b = pSlice.call(b);
7014
+ return deepEqual(a, b);
7015
+ }
7016
+ try {
7017
+ var ka = Object_keys(a), kb = Object_keys(b), key, i;
7018
+ } catch (e) {
7019
+ return false;
7020
+ }
7021
+ if (ka.length != kb.length) return false;
7022
+ ka.sort();
7023
+ kb.sort();
7024
+ for (i = ka.length - 1; i >= 0; i--) if (ka[i] != kb[i]) return false;
7025
+ for (i = ka.length - 1; i >= 0; i--) {
7026
+ key = ka[i];
7027
+ if (!deepEqual(a[key], b[key])) return false;
7028
+ }
7029
+ return true;
7030
+ }
7031
+ }));
7032
+ //#endregion
7033
+ //#region node_modules/is2/node_modules/ip-regex/index.js
7034
+ var require_ip_regex = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7035
+ const word = "[a-fA-F\\d:]";
7036
+ const b = (options) => options && options.includeBoundaries ? `(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))` : "";
7037
+ const v4 = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}";
7038
+ const v6seg = "[a-fA-F\\d]{1,4}";
7039
+ const v6 = `
7040
+ (?:
7041
+ (?:${v6seg}:){7}(?:${v6seg}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
7042
+ (?:${v6seg}:){6}(?:${v4}|:${v6seg}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
7043
+ (?:${v6seg}:){5}(?::${v4}|(?::${v6seg}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
7044
+ (?:${v6seg}:){4}(?:(?::${v6seg}){0,1}:${v4}|(?::${v6seg}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
7045
+ (?:${v6seg}:){3}(?:(?::${v6seg}){0,2}:${v4}|(?::${v6seg}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
7046
+ (?:${v6seg}:){2}(?:(?::${v6seg}){0,3}:${v4}|(?::${v6seg}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
7047
+ (?:${v6seg}:){1}(?:(?::${v6seg}){0,4}:${v4}|(?::${v6seg}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
7048
+ (?::(?:(?::${v6seg}){0,5}:${v4}|(?::${v6seg}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
7049
+ )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
7050
+ `.replace(/\s*\/\/.*$/gm, "").replace(/\n/g, "").trim();
7051
+ const v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`);
7052
+ const v4exact = new RegExp(`^${v4}$`);
7053
+ const v6exact = new RegExp(`^${v6}$`);
7054
+ const ip = (options) => options && options.exact ? v46Exact : new RegExp(`(?:${b(options)}${v4}${b(options)})|(?:${b(options)}${v6}${b(options)})`, "g");
7055
+ ip.v4 = (options) => options && options.exact ? v4exact : new RegExp(`${b(options)}${v4}${b(options)}`, "g");
7056
+ ip.v6 = (options) => options && options.exact ? v6exact : new RegExp(`${b(options)}${v6}${b(options)}`, "g");
7057
+ module.exports = ip;
7058
+ }));
7059
+ //#endregion
7060
+ //#region node_modules/is2/package.json
7061
+ var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7062
+ module.exports = {
7063
+ "name": "is2",
7064
+ "version": "2.0.9",
7065
+ "description": "A type checking library where each exported function returns either true or false and does not throw. Also added tests.",
7066
+ "license": "MIT",
7067
+ "tags": [
7068
+ "type",
7069
+ "check",
7070
+ "checker",
7071
+ "checking",
7072
+ "utilities",
7073
+ "network",
7074
+ "networking",
7075
+ "credit",
7076
+ "card",
7077
+ "validation"
7078
+ ],
7079
+ "keywords": [
7080
+ "type",
7081
+ "check",
7082
+ "checker",
7083
+ "checking",
7084
+ "utilities",
7085
+ "network",
7086
+ "networking",
7087
+ "credit",
7088
+ "card",
7089
+ "validation"
7090
+ ],
7091
+ "author": "Enrico Marino <enrico.marino@email.com>",
7092
+ "maintainers": "Edmond Meinfelder <edmond@stdarg.com>, Chris Oyler <christopher.oyler@gmail.com>",
7093
+ "homepage": "http://github.com/stdarg/is2",
7094
+ "repository": {
7095
+ "type": "git",
7096
+ "url": "git@github.com:stdarg/is2.git"
7097
+ },
7098
+ "bugs": { "url": "http://github.com/stdarg/is/issues" },
7099
+ "main": "./index.js",
7100
+ "scripts": { "test": "./node_modules/.bin/mocha -C --reporter list tests.js" },
7101
+ "engines": { "node": ">=v0.10.0" },
7102
+ "dependencies": {
7103
+ "deep-is": "^0.1.3",
7104
+ "ip-regex": "^4.1.0",
7105
+ "is-url": "^1.2.4"
7106
+ },
7107
+ "devDependencies": {
7108
+ "mocha": "6.2.3",
7109
+ "mongodb": "3.2.4"
7110
+ }
7111
+ };
7112
+ }));
7113
+ //#endregion
7114
+ //#region node_modules/is-url/index.js
7115
+ var require_is_url = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7116
+ /**
7117
+ * Expose `isUrl`.
7118
+ */
7119
+ module.exports = isUrl;
7120
+ /**
7121
+ * RegExps.
7122
+ * A URL must match #1 and then at least one of #2/#3.
7123
+ * Use two levels of REs to avoid REDOS.
7124
+ */
7125
+ var protocolAndDomainRE = /^(?:\w+:)?\/\/(\S+)$/;
7126
+ var localhostDomainRE = /^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/;
7127
+ var nonLocalhostDomainRE = /^[^\s\.]+\.\S{2,}$/;
7128
+ /**
7129
+ * Loosely validate a URL `string`.
7130
+ *
7131
+ * @param {String} string
7132
+ * @return {Boolean}
7133
+ */
7134
+ function isUrl(string) {
7135
+ if (typeof string !== "string") return false;
7136
+ var match = string.match(protocolAndDomainRE);
7137
+ if (!match) return false;
7138
+ var everythingAfterProtocol = match[1];
7139
+ if (!everythingAfterProtocol) return false;
7140
+ if (localhostDomainRE.test(everythingAfterProtocol) || nonLocalhostDomainRE.test(everythingAfterProtocol)) return true;
7141
+ return false;
7142
+ }
7143
+ }));
7144
+ //#endregion
7145
+ //#region node_modules/is2/index.js
7146
+ /**
7147
+ * @fileOverview
7148
+ * is2 derived from is by Enrico Marino, adapted for Node.js.
7149
+ * Slightly modified by Edmond Meinfelder
7150
+ *
7151
+ * is
7152
+ * the definitive JavaScript type testing library
7153
+ * Copyright(c) 2013,2014 Edmond Meinfelder <edmond@stdarg.com>
7154
+ * Copyright(c) 2011 Enrico Marino <enrico.marino@email.com>
7155
+ * MIT license
7156
+ */
7157
+ var require_is2 = /* @__PURE__ */ __commonJSMin(((exports) => {
7158
+ const owns = {}.hasOwnProperty;
7159
+ const toString = {}.toString;
7160
+ const is = exports;
7161
+ const deepIs = require_deep_is();
7162
+ const ipRegEx = require_ip_regex();
7163
+ is.version = require_package().version;
7164
+ /**
7165
+ * Tests if is is running under a browser.
7166
+ * @return {Boolean} true if the environment has process, process.version and process.versions.
7167
+ */
7168
+ is.browser = function() {
7169
+ return !is.node() && typeof window !== "undefined" && toString.call(window) === "[object global]";
7170
+ };
7171
+ /**
7172
+ * Test if 'value' is defined.
7173
+ * Alias: def
7174
+ * @param {Any} value The value to test.
7175
+ * @return {Boolean} true if 'value' is defined, false otherwise.
7176
+ */
7177
+ is.defined = function(value) {
7178
+ return typeof value !== "undefined";
7179
+ };
7180
+ is.def = is.defined;
7181
+ /**
7182
+ * Tests if is is running under node.js
7183
+ * @return {Boolean} true if the environment has process, process.version and process.versions.
7184
+ */
7185
+ is.nodejs = function() {
7186
+ return process && process.hasOwnProperty("version") && process.hasOwnProperty("versions");
7187
+ };
7188
+ is.node = is.nodejs;
7189
+ /**
7190
+ * Test if 'value' is undefined.
7191
+ * Aliases: undef, udef
7192
+ * @param {Any} value value to test.
7193
+ * @return {Boolean} true if 'value' is undefined, false otherwise.
7194
+ */
7195
+ is.undefined = function(value) {
7196
+ return value === void 0;
7197
+ };
7198
+ is.udef = is.undef = is.undefined;
7199
+ /**
7200
+ * Test if 'value' is an array.
7201
+ * Alias: ary, arry
7202
+ * @param {Any} value value to test.
7203
+ * @return {Boolean} true if 'value' is an array, false otherwise.
7204
+ */
7205
+ is.array = function(value) {
7206
+ return "[object Array]" === toString.call(value);
7207
+ };
7208
+ is.arr = is.ary = is.arry = is.array;
7209
+ /**
7210
+ * Test if 'value' is an arraylike object (i.e. it has a length property with a valid value)
7211
+ * Aliases: arraylike, arryLike, aryLike
7212
+ * @param {Any} value value to test.
7213
+ * @return {Boolean} true if 'value' is an arguments object, false otherwise.
7214
+ */
7215
+ is.arrayLike = function(value) {
7216
+ if (is.nullOrUndef(value)) return false;
7217
+ return value !== void 0 && owns.call(value, "length") && isFinite(value.length);
7218
+ };
7219
+ is.arrLike = is.arryLike = is.aryLike = is.arraylike = is.arrayLike;
7220
+ /**
7221
+ * Test if 'value' is an arguments object.
7222
+ * Alias: args
7223
+ * @param {Any} value value to test
7224
+ * @return {Boolean} true if 'value' is an arguments object, false otherwise
7225
+ */
7226
+ is.arguments = function(value) {
7227
+ return "[object Arguments]" === toString.call(value);
7228
+ };
7229
+ is.args = is.arguments;
7230
+ /**
7231
+ * Test if 'value' is a boolean.
7232
+ * Alias: bool
7233
+ * @param {Any} value value to test.
7234
+ * @return {Boolean} true if 'value' is a boolean, false otherwise.
7235
+ */
7236
+ is.boolean = function(value) {
7237
+ return "[object Boolean]" === toString.call(value);
7238
+ };
7239
+ is.bool = is.boolean;
7240
+ /**
7241
+ * Test if 'value' is an instance of Buffer.
7242
+ * Aliases: instOf, instanceof
7243
+ * @param {Any} value value to test.
7244
+ * @return {Boolean} true if 'value' is an instance of 'constructor'.
7245
+ */
7246
+ is.buffer = function(value) {
7247
+ return is.nodejs() && Buffer && Buffer.hasOwnProperty("isBuffer") && Buffer.isBuffer(value);
7248
+ };
7249
+ is.buff = is.buf = is.buffer;
7250
+ /**
7251
+ * Test if 'value' is a date.
7252
+ * @param {Any} value value to test.
7253
+ * @return {Boolean} true if 'value' is a date, false otherwise.
7254
+ */
7255
+ is.date = function(value) {
7256
+ return "[object Date]" === toString.call(value);
7257
+ };
7258
+ /**
7259
+ * Test if 'value' is an error object.
7260
+ * Alias: err
7261
+ * @param value value to test.
7262
+ * @return {Boolean} true if 'value' is an error object, false otherwise.
7263
+ */
7264
+ is.error = function(value) {
7265
+ return "[object Error]" === toString.call(value);
7266
+ };
7267
+ is.err = is.error;
7268
+ /**
7269
+ * Test if 'value' is false.
7270
+ * @param {Any} value value to test.
7271
+ * @return {Boolean} true if 'value' is false, false otherwise
7272
+ */
7273
+ is.false = function(value) {
7274
+ return value === false;
7275
+ };
7276
+ /**
7277
+ * Test if 'value' is a function or async function.
7278
+ * Alias: func
7279
+ * @param {Any} value value to test.
7280
+ * @return {Boolean} true if 'value' is a function, false otherwise.
7281
+ */
7282
+ is.function = function(value) {
7283
+ return is.syncFunction(value) || is.asyncFunction(value);
7284
+ };
7285
+ is.fun = is.func = is.function;
7286
+ /**
7287
+ * Test if 'value' is an async function using `async () => {}` or `async function () {}`.
7288
+ * Alias: func
7289
+ * @param {Any} value value to test.
7290
+ * @return {Boolean} true if 'value' is a function, false otherwise.
7291
+ */
7292
+ is.asyncFunction = function(value) {
7293
+ return "[object AsyncFunction]" === toString.call(value);
7294
+ };
7295
+ is.asyncFun = is.asyncFunc = is.asyncFunction;
7296
+ /**
7297
+ * Test if 'value' is a synchronous function.
7298
+ * Alias: syncFunc
7299
+ * @param {Any} value value to test.
7300
+ * @return {Boolean} true if 'value' is a function, false otherwise.
7301
+ */
7302
+ is.syncFunction = function(value) {
7303
+ return "[object Function]" === toString.call(value);
7304
+ };
7305
+ is.syncFun = is.syncFunc = is.syncFunction;
7306
+ /**
7307
+ * Test if 'value' is null.
7308
+ * @param {Any} value to test.
7309
+ * @return {Boolean} true if 'value' is null, false otherwise.
7310
+ */
7311
+ is.null = function(value) {
7312
+ return value === null;
7313
+ };
7314
+ /**
7315
+ * Test is 'value' is either null or undefined.
7316
+ * Alias: nullOrUndef
7317
+ * @param {Any} value value to test.
7318
+ * @return {Boolean} True if value is null or undefined, false otherwise.
7319
+ */
7320
+ is.nullOrUndefined = function(value) {
7321
+ return value === null || typeof value === "undefined";
7322
+ };
7323
+ is.nullOrUndef = is.nullOrUndefined;
7324
+ /**
7325
+ * Test if 'value' is a number.
7326
+ * Alias: num
7327
+ * @param {Any} value to test.
7328
+ * @return {Boolean} true if 'value' is a number, false otherwise.
7329
+ */
7330
+ is.number = function(value) {
7331
+ return "[object Number]" === toString.call(value);
7332
+ };
7333
+ is.num = is.number;
7334
+ /**
7335
+ * Test if 'value' is an object. Note: Arrays, RegExps, Date, Error, etc all return false.
7336
+ * Alias: obj
7337
+ * @param {Any} value to test.
7338
+ * @return {Boolean} true if 'value' is an object, false otherwise.
7339
+ */
7340
+ is.object = function(value) {
7341
+ return "[object Object]" === toString.call(value);
7342
+ };
7343
+ is.obj = is.object;
7344
+ /**
7345
+ * Test if 'value' is a regular expression.
7346
+ * Alias: regexp
7347
+ * @param {Any} value to test.
7348
+ * @return {Boolean} true if 'value' is a regexp, false otherwise.
7349
+ */
7350
+ is.regExp = function(value) {
7351
+ return "[object RegExp]" === toString.call(value);
7352
+ };
7353
+ is.re = is.regexp = is.regExp;
7354
+ /**
7355
+ * Test if 'value' is a string.
7356
+ * Alias: str
7357
+ * @param {Any} value to test.
7358
+ * @return {Boolean} true if 'value' is a string, false otherwise.
7359
+ */
7360
+ is.string = function(value) {
7361
+ return "[object String]" === toString.call(value);
7362
+ };
7363
+ is.str = is.string;
7364
+ /**
7365
+ * Test if 'value' is true.
7366
+ * @param {Any} value to test.
7367
+ * @return {Boolean} true if 'value' is true, false otherwise.
7368
+ */
7369
+ is.true = function(value) {
7370
+ return value === true;
7371
+ };
7372
+ /**
7373
+ * Test if 'value' is a uuid (v1-v5)
7374
+ * @param {Any} value to test.
7375
+ * @return {Boolean} true if 'value is a valid RFC4122 UUID. Case non-specific.
7376
+ */
7377
+ var uuidRegExp = /* @__PURE__ */ new RegExp("[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}", "i");
7378
+ is.uuid = function(value) {
7379
+ return uuidRegExp.test(value);
7380
+ };
7381
+ /**
7382
+ * Test if 'value' is equal to 'other'. Works for objects and arrays and will do deep comparisions,
7383
+ * using recursion.
7384
+ * Alias: eq
7385
+ * @param {Any} value value.
7386
+ * @param {Any} other value to compare with.
7387
+ * @return {Boolean} true if 'value' is equal to 'other', false otherwise
7388
+ */
7389
+ is.equal = function(value, other) {
7390
+ var type = toString.call(value);
7391
+ if (typeof value !== typeof other) return false;
7392
+ if (type !== toString.call(other)) return false;
7393
+ if ("[object Object]" === type || "[object Array]" === type) return deepIs(value, other);
7394
+ else if ("[object Function]" === type) return value.prototype === other.prototype;
7395
+ else if ("[object Date]" === type) return value.getTime() === other.getTime();
7396
+ return value === other;
7397
+ };
7398
+ is.objEquals = is.eq = is.equal;
7399
+ /**
7400
+ * JS Type definitions which cannot host values.
7401
+ * @api private
7402
+ */
7403
+ var NON_HOST_TYPES = {
7404
+ "boolean": 1,
7405
+ "number": 1,
7406
+ "string": 1,
7407
+ "undefined": 1
7408
+ };
7409
+ /**
7410
+ * Test if 'key' in host is an object. To be hosted means host[value] is an object.
7411
+ * @param {Any} value The value to test.
7412
+ * @param {Any} host Host that may contain value.
7413
+ * @return {Boolean} true if 'value' is hosted by 'host', false otherwise.
7414
+ */
7415
+ is.hosted = function(value, host) {
7416
+ if (is.nullOrUndef(value)) return false;
7417
+ var type = typeof host[value];
7418
+ return type === "object" ? !!host[value] : !NON_HOST_TYPES[type];
7419
+ };
7420
+ /**
7421
+ * Test if 'value' is an instance of 'constructor'.
7422
+ * Aliases: instOf, instanceof
7423
+ * @param {Any} value value to test.
7424
+ * @return {Boolean} true if 'value' is an instance of 'constructor'.
7425
+ */
7426
+ is.instanceOf = function(value, constructor) {
7427
+ if (is.nullOrUndef(value) || is.nullOrUndef(constructor)) return false;
7428
+ return value instanceof constructor;
7429
+ };
7430
+ is.instOf = is.instanceof = is.instanceOf;
7431
+ /**
7432
+ * Test if 'value' is an instance type objType.
7433
+ * Aliases: objInstOf, objectinstanceof, instOf, instanceOf
7434
+ * @param {object} objInst an object to testfor type.
7435
+ * @param {object} objType an object type to compare.
7436
+ * @return {Boolean} true if 'value' is an object, false otherwise.
7437
+ */
7438
+ is.objectInstanceOf = function(objInst, objType) {
7439
+ try {
7440
+ return "[object Object]" === toString.call(objInst) && objInst instanceof objType;
7441
+ } catch (err) {
7442
+ return false;
7443
+ }
7444
+ };
7445
+ is.instOf = is.instanceOf = is.objInstOf = is.objectInstanceOf;
7446
+ /**
7447
+ * Test if 'value' is a type of 'type'.
7448
+ * Alias: a
7449
+ * @param value value to test.
7450
+ * @param {String} type The name of the type.
7451
+ * @return {Boolean} true if 'value' is an arguments object, false otherwise.
7452
+ */
7453
+ is.type = function(value, type) {
7454
+ return typeof value === type;
7455
+ };
7456
+ is.a = is.type;
7457
+ /**
7458
+ * Test if 'value' is empty. To be empty means to be an array, object or string with nothing contained.
7459
+ * @param {Any} value value to test.
7460
+ * @return {Boolean} true if 'value' is empty, false otherwise.
7461
+ */
7462
+ is.empty = function(value) {
7463
+ var type = toString.call(value);
7464
+ if ("[object Array]" === type || "[object Arguments]" === type) return value.length === 0;
7465
+ if ("[object Object]" === type) {
7466
+ for (var key in value) if (owns.call(value, key)) return false;
7467
+ return true;
7468
+ }
7469
+ if ("[object String]" === type) return value === "";
7470
+ return false;
7471
+ };
7472
+ /**
7473
+ * Test if 'value' is an arguments object that is empty.
7474
+ * Alias: args
7475
+ * @param {Any} value value to test
7476
+ * @return {Boolean} true if 'value' is an arguments object with no args, false otherwise
7477
+ */
7478
+ is.emptyArguments = function(value) {
7479
+ return "[object Arguments]" === toString.call(value) && value.length === 0;
7480
+ };
7481
+ is.noArgs = is.emptyArgs = is.emptyArguments;
7482
+ /**
7483
+ * Test if 'value' is an array containing no entries.
7484
+ * Aliases: emptyArry, emptyAry
7485
+ * @param {Any} value The value to test.
7486
+ * @return {Boolean} true if 'value' is an array with no elemnets.
7487
+ */
7488
+ is.emptyArray = function(value) {
7489
+ return "[object Array]" === toString.call(value) && value.length === 0;
7490
+ };
7491
+ is.emptyArry = is.emptyAry = is.emptyArray;
7492
+ /**
7493
+ * Test if 'value' is an empty array(like) object.
7494
+ * Aliases: arguents.empty, args.empty, ary.empty, arry.empty
7495
+ * @param {Any} value value to test.
7496
+ * @return {Boolean} true if 'value' is an empty array(like), false otherwise.
7497
+ */
7498
+ is.emptyArrayLike = function(value) {
7499
+ return value.length === 0;
7500
+ };
7501
+ is.emptyArrLike = is.emptyArrayLike;
7502
+ /**
7503
+ * Test if 'value' is an empty string.
7504
+ * Alias: emptyStr
7505
+ * @param {Any} value to test.
7506
+ * @return {Boolean} true if 'value' is am empty string, false otherwise.
7507
+ */
7508
+ is.emptyString = function(value) {
7509
+ return is.string(value) && value.length === 0;
7510
+ };
7511
+ is.emptyStr = is.emptyString;
7512
+ /**
7513
+ * Test if 'value' is an array containing at least 1 entry.
7514
+ * Aliases: nonEmptyArry, nonEmptyAry
7515
+ * @param {Any} value The value to test.
7516
+ * @return {Boolean} true if 'value' is an array with at least 1 value, false otherwise.
7517
+ */
7518
+ is.nonEmptyArray = function(value) {
7519
+ return "[object Array]" === toString.call(value) && value.length > 0;
7520
+ };
7521
+ is.nonEmptyArr = is.nonEmptyArry = is.nonEmptyAry = is.nonEmptyArray;
7522
+ /**
7523
+ * Test if 'value' is an object with properties. Note: Arrays are objects.
7524
+ * Alias: nonEmptyObj
7525
+ * @param {Any} value to test.
7526
+ * @return {Boolean} true if 'value' is an object, false otherwise.
7527
+ */
7528
+ is.nonEmptyObject = function(value) {
7529
+ return "[object Object]" === toString.call(value) && Object.keys(value).length > 0;
7530
+ };
7531
+ is.nonEmptyObj = is.nonEmptyObject;
7532
+ /**
7533
+ * Test if 'value' is an object with no properties. Note: Arrays are objects.
7534
+ * Alias: nonEmptyObj
7535
+ * @param {Any} value to test.
7536
+ * @return {Boolean} true if 'value' is an object, false otherwise.
7537
+ */
7538
+ is.emptyObject = function(value) {
7539
+ return "[object Object]" === toString.call(value) && Object.keys(value).length === 0;
7540
+ };
7541
+ is.emptyObj = is.emptyObject;
7542
+ /**
7543
+ * Test if 'value' is a non-empty string.
7544
+ * Alias: nonEmptyStr
7545
+ * @param {Any} value to test.
7546
+ * @return {Boolean} true if 'value' is a non-empty string, false otherwise.
7547
+ */
7548
+ is.nonEmptyString = function(value) {
7549
+ return is.string(value) && value.length > 0;
7550
+ };
7551
+ is.nonEmptyStr = is.nonEmptyString;
7552
+ /**
7553
+ * Test if 'value' is an even number.
7554
+ * @param {Number} value to test.
7555
+ * @return {Boolean} true if 'value' is an even number, false otherwise.
7556
+ */
7557
+ is.even = function(value) {
7558
+ return "[object Number]" === toString.call(value) && value % 2 === 0;
7559
+ };
7560
+ /**
7561
+ * Test if 'value' is a decimal number.
7562
+ * Aliases: decimalNumber, decNum
7563
+ * @param {Any} value value to test.
7564
+ * @return {Boolean} true if 'value' is a decimal number, false otherwise.
7565
+ */
7566
+ is.decimal = function(value) {
7567
+ return "[object Number]" === toString.call(value) && value % 1 !== 0;
7568
+ };
7569
+ is.dec = is.decNum = is.decimal;
7570
+ /**
7571
+ * Test if 'value' is an integer.
7572
+ * Alias: integer
7573
+ * @param {Any} value to test.
7574
+ * @return {Boolean} true if 'value' is an integer, false otherwise.
7575
+ */
7576
+ is.integer = function(value) {
7577
+ return "[object Number]" === toString.call(value) && value % 1 === 0;
7578
+ };
7579
+ is.int = is.integer;
7580
+ /**
7581
+ * is.nan
7582
+ * Test if `value` is not a number.
7583
+ *
7584
+ * @param {Mixed} value value to test
7585
+ * @return {Boolean} true if `value` is not a number, false otherwise
7586
+ * @api public
7587
+ */
7588
+ is.notANumber = function(value) {
7589
+ return !is.num(value) || value !== value;
7590
+ };
7591
+ is.nan = is.notANum = is.notANumber;
7592
+ /**
7593
+ * Test if 'value' is an odd number.
7594
+ * @param {Number} value to test.
7595
+ * @return {Boolean} true if 'value' is an odd number, false otherwise.
7596
+ */
7597
+ is.odd = function(value) {
7598
+ return !is.decimal(value) && "[object Number]" === toString.call(value) && value % 2 !== 0;
7599
+ };
7600
+ is.oddNumber = is.oddNum = is.odd;
7601
+ /**
7602
+ * Test if 'value' is a positive number.
7603
+ * Alias: positiveNum, posNum
7604
+ * @param {Any} value to test.
7605
+ * @return {Boolean} true if 'value' is a number, false otherwise.
7606
+ */
7607
+ is.positiveNumber = function(value) {
7608
+ return "[object Number]" === toString.call(value) && value > 0;
7609
+ };
7610
+ is.pos = is.positive = is.posNum = is.positiveNum = is.positiveNumber;
7611
+ /**
7612
+ * Test if 'value' is a negative number.
7613
+ * Aliases: negNum, negativeNum
7614
+ * @param {Any} value to test.
7615
+ * @return {Boolean} true if 'value' is a number, false otherwise.
7616
+ */
7617
+ is.negativeNumber = function(value) {
7618
+ return "[object Number]" === toString.call(value) && value < 0;
7619
+ };
7620
+ is.neg = is.negNum = is.negativeNum = is.negativeNumber;
7621
+ /**
7622
+ * Test if 'value' is a negative integer.
7623
+ * Aliases: negInt, negativeInteger
7624
+ * @param {Any} value to test.
7625
+ * @return {Boolean} true if 'value' is a negative integer, false otherwise.
7626
+ */
7627
+ is.negativeInteger = function(value) {
7628
+ return "[object Number]" === toString.call(value) && value % 1 === 0 && value < 0;
7629
+ };
7630
+ is.negativeInt = is.negInt = is.negativeInteger;
7631
+ /**
7632
+ * Test if 'value' is a positive integer.
7633
+ * Alias: posInt
7634
+ * @param {Any} value to test.
7635
+ * @return {Boolean} true if 'value' is a positive integer, false otherwise.
7636
+ */
7637
+ is.positiveInteger = function(value) {
7638
+ return "[object Number]" === toString.call(value) && value % 1 === 0 && value > 0;
7639
+ };
7640
+ is.posInt = is.positiveInt = is.positiveInteger;
7641
+ /**
7642
+ * Test if 'value' is divisible by 'n'.
7643
+ * Alias: divisBy
7644
+ * @param {Number} value value to test.
7645
+ * @param {Number} n dividend.
7646
+ * @return {Boolean} true if 'value' is divisible by 'n', false otherwise.
7647
+ */
7648
+ is.divisibleBy = function(value, n) {
7649
+ if (value === 0) return false;
7650
+ return "[object Number]" === toString.call(value) && n !== 0 && value % n === 0;
7651
+ };
7652
+ is.divBy = is.divisBy = is.divisibleBy;
7653
+ /**
7654
+ * Test if 'value' is greater than or equal to 'other'.
7655
+ * Aliases: greaterOrEq, greaterOrEqual
7656
+ * @param {Number} value value to test.
7657
+ * @param {Number} other value to compare with.
7658
+ * @return {Boolean} true, if value is greater than or equal to other, false otherwise.
7659
+ */
7660
+ is.greaterOrEqualTo = function(value, other) {
7661
+ return value >= other;
7662
+ };
7663
+ is.greaterOrEqual = is.ge = is.greaterOrEqualTo;
7664
+ /**
7665
+ * Test if 'value' is greater than 'other'.
7666
+ * Aliases: greaterThan
7667
+ * @param {Number} value value to test.
7668
+ * @param {Number} other value to compare with.
7669
+ * @return {Boolean} true, if value is greater than other, false otherwise.
7670
+ */
7671
+ is.greaterThan = function(value, other) {
7672
+ return value > other;
7673
+ };
7674
+ is.gt = is.greaterThan;
7675
+ /**
7676
+ * Test if 'value' is less than or equal to 'other'.
7677
+ * Alias: lessThanOrEq, lessThanOrEqual
7678
+ * @param {Number} value value to test
7679
+ * @param {Number} other value to compare with
7680
+ * @return {Boolean} true, if 'value' is less than or equal to 'other', false otherwise.
7681
+ */
7682
+ is.lessThanOrEqualTo = function(value, other) {
7683
+ return value <= other;
7684
+ };
7685
+ is.lessThanOrEq = is.lessThanOrEqual = is.le = is.lessThanOrEqualTo;
7686
+ /**
7687
+ * Test if 'value' is less than 'other'.
7688
+ * Alias: lessThan
7689
+ * @param {Number} value value to test
7690
+ * @param {Number} other value to compare with
7691
+ * @return {Boolean} true, if 'value' is less than 'other', false otherwise.
7692
+ */
7693
+ is.lessThan = function(value, other) {
7694
+ return value < other;
7695
+ };
7696
+ is.lt = is.lessThan;
7697
+ /**
7698
+ * Test if 'value' is greater than 'others' values.
7699
+ * Alias: max
7700
+ * @param {Number} value value to test.
7701
+ * @param {Array} others values to compare with.
7702
+ * @return {Boolean} true if 'value' is greater than 'others' values.
7703
+ */
7704
+ is.maximum = function(value, others) {
7705
+ if (!is.arrayLike(others) || !is.number(value)) return false;
7706
+ var len = others.length;
7707
+ while (--len > -1) if (value < others[len]) return false;
7708
+ return true;
7709
+ };
7710
+ is.max = is.maximum;
7711
+ /**
7712
+ * Test if 'value' is less than 'others' values.
7713
+ * Alias: min
7714
+ * @param {Number} value value to test.
7715
+ * @param {Array} others values to compare with.
7716
+ * @return {Boolean} true if 'value' is less than 'others' values.
7717
+ */
7718
+ is.minimum = function(value, others) {
7719
+ if (!is.arrayLike(others) || !is.number(value)) return false;
7720
+ var len = others.length;
7721
+ while (--len > -1) if (value > others[len]) return false;
7722
+ return true;
7723
+ };
7724
+ is.min = is.minimum;
7725
+ /**
7726
+ * Test if 'value' is within 'start' and 'finish'.
7727
+ * Alias: withIn
7728
+ * @param {Number} value value to test.
7729
+ * @param {Number} start lower bound.
7730
+ * @param {Number} finish upper bound.
7731
+ * @return {Boolean} true if 'value' is is within 'start' and 'finish', false otherwise.
7732
+ */
7733
+ is.within = function(value, start, finish) {
7734
+ return value >= start && value <= finish;
7735
+ };
7736
+ is.withIn = is.within;
7737
+ /**
7738
+ * Test if 'value' is within 'precision' decimal places from 'comparitor'.
7739
+ * Alias: closish, near.
7740
+ * @param {Number} value value to test
7741
+ * @param {Number} comparitor value to test 'value' against
7742
+ * @param {Number} precision number of decimals to compare floating points, defaults to 2
7743
+ * @return {Boolean} true if 'value' is within 'precision' decimal places from 'comparitor', false otherwise.
7744
+ */
7745
+ is.prettyClose = function(value, comparitor, precision) {
7746
+ if (!is.number(value) || !is.number(comparitor)) return false;
7747
+ if (is.defined(precision) && !is.posInt(precision)) return false;
7748
+ if (is.undefined(precision)) precision = 2;
7749
+ return value.toFixed(precision) === comparitor.toFixed(precision);
7750
+ };
7751
+ is.closish = is.near = is.prettyClose;
7752
+ /**
7753
+ * Test if a value is a valid DNS address. eg www.stdarg.com is true while
7754
+ * 127.0.0.1 is false.
7755
+ * @param {Any} value to test if a DNS address.
7756
+ * @return {Boolean} true if a DNS address, false otherwise.
7757
+ * DNS Address is made up of labels separated by '.'
7758
+ * Each label must be between 1 and 63 characters long
7759
+ * The entire hostname (including the delimiting dots) has a maximum of 255 characters.
7760
+ * Hostname may not contain other characters, such as the underscore character (_)
7761
+ * other DNS names may contain the underscore.
7762
+ */
7763
+ is.dnsAddress = function(value) {
7764
+ if (!is.nonEmptyStr(value)) return false;
7765
+ if (value.length > 255) return false;
7766
+ if (numbersLabel.test(value)) return false;
7767
+ if (!dnsLabel.test(value)) return false;
7768
+ return true;
7769
+ };
7770
+ is.dnsAddr = is.dns = is.dnsAddress;
7771
+ var dnsLabel = /^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$/;
7772
+ var numbersLabel = /^([0-9]|[0-9][0-9\-]{0,61}[0-9])(\.([0-9]|[0-9][0-9\-]{0,61}[0-9]))*$/;
7773
+ /**
7774
+ * Test if value is a valid email address.
7775
+ * @param {Any} value to test if an email address.
7776
+ * @return {Boolean} true if an email address, false otherwise.
7777
+ */
7778
+ is.emailAddress = function(value) {
7779
+ if (!is.nonEmptyStr(value)) return false;
7780
+ return emailRegexp.test(value);
7781
+ };
7782
+ is.email = is.emailAddr = is.emailAddress;
7783
+ var emailRegexp = /^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$/;
7784
+ /**
7785
+ * Test if a value is either an IPv4 numeric IP address.
7786
+ * The rules are:
7787
+ * must be a string
7788
+ * length must be 15 characters or less
7789
+ * There must be four octets separated by a '.'
7790
+ * No octet can be less than 0 or greater than 255.
7791
+ * @param {Any} value to test if an ip address.
7792
+ * @return {Boolean} true if an ip address, false otherwise.
7793
+ */
7794
+ is.ipv4Address = function(value) {
7795
+ if (!is.nonEmptyStr(value)) return false;
7796
+ if (value.length > 15) return false;
7797
+ var octets = value.split(".");
7798
+ if (!is.array(octets) || octets.length !== 4) return false;
7799
+ for (var i = 0; i < octets.length; i++) {
7800
+ var val = parseInt(octets[i], 10);
7801
+ if (isNaN(val)) return false;
7802
+ if (val < 0 || val > 255) return false;
7803
+ }
7804
+ return true;
7805
+ };
7806
+ is.ipv4 = is.ipv4Addr = is.ipv4Address;
7807
+ /**
7808
+ * Test if a value is either an IPv6 numeric IP address.
7809
+ * @param {Any} value to test if an ip address.
7810
+ * @return {Boolean} true if an ip address, false otherwise.
7811
+ */
7812
+ is.ipv6Address = function(value) {
7813
+ if (!is.nonEmptyStr(value)) return false;
7814
+ return ipRegEx.v6({ extract: true }).test(value);
7815
+ };
7816
+ is.ipv6 = is.ipv6Addr = is.ipv6Address;
7817
+ /**
7818
+ * Test if a value is either an IPv4 or IPv6 numeric IP address.
7819
+ * @param {Any} value to test if an ip address.
7820
+ * @return {Boolean} true if an ip address, false otherwise.
7821
+ */
7822
+ is.ipAddress = function(value) {
7823
+ if (!is.nonEmptyStr(value)) return false;
7824
+ return is.ipv4Address(value) || is.ipv6Address(value);
7825
+ };
7826
+ is.ip = is.ipAddr = is.ipAddress;
7827
+ /**
7828
+ * Test is a value is a valid ipv4, ipv6 or DNS name.
7829
+ * Aliases: host, hostAddr, hostAddress.
7830
+ * @param {Any} value to test if a host address.
7831
+ * @return {Boolean} true if a host address, false otherwise.
7832
+ */
7833
+ is.hostAddress = function(value) {
7834
+ if (!is.nonEmptyStr(value)) return false;
7835
+ return is.dns(value) || is.ipv4(value) || is.ipv6(value);
7836
+ };
7837
+ is.host = is.hostIp = is.hostAddr = is.hostAddress;
7838
+ /**
7839
+ * Test if a number is a valid TCP port
7840
+ * @param {Any} value to test if its a valid TCP port
7841
+ */
7842
+ is.port = function(value) {
7843
+ if (!is.num(value) || is.negativeInt(value) || value > 65535) return false;
7844
+ return true;
7845
+ };
7846
+ /**
7847
+ * Test if a number is a valid TCP port in the range 0-1023.
7848
+ * Alias: is.sysPort.
7849
+ * @param {Any} value to test if its a valid TCP port
7850
+ */
7851
+ is.systemPort = function(value) {
7852
+ if (is.port(value) && value < 1024) return true;
7853
+ return false;
7854
+ };
7855
+ is.sysPort = is.systemPort;
7856
+ /**
7857
+ * Test if a number is a valid TCP port in the range 1024-65535.
7858
+ * @param {Any} value to test if its a valid TCP port
7859
+ */
7860
+ is.userPort = function(value) {
7861
+ if (is.port(value) && value > 1023) return true;
7862
+ return false;
7863
+ };
7864
+ /**
7865
+ * Test if a string is a credit card.
7866
+ * From http://en.wikipedia.org/wiki/Luhn_algorithm
7867
+ * @param {String} value to test if a credit card.
7868
+ * @return true if the string is the correct format, false otherwise
7869
+ */
7870
+ is.creditCardNumber = function(str) {
7871
+ if (!is.str(str)) return false;
7872
+ var ary = str.split("");
7873
+ var i, cnt;
7874
+ for (i = ary.length - 1, cnt = 1; i > -1; i--, cnt++) if (cnt % 2 === 0) ary[i] *= 2;
7875
+ str = ary.join("");
7876
+ var sum = 0;
7877
+ for (i = 0; i < str.length; i++) sum += Math.floor(str[i]);
7878
+ return sum % 10 === 0;
7879
+ };
7880
+ is.creditCard = is.creditCardNum = is.creditCardNumber;
7881
+ /**
7882
+ * Test if card number is an American Express card.
7883
+ * @param {String} the credit card number string to test.
7884
+ * @return true if the string is the correct format, false otherwise
7885
+ */
7886
+ is.americanExpressCardNumber = function(str) {
7887
+ if (!is.str(str) || str.length !== 15) return false;
7888
+ var prefix = Math.floor(str.slice(0, 2));
7889
+ if (prefix !== 34 && prefix !== 37) return false;
7890
+ if (!is.creditCardNumber(str)) return false;
7891
+ return true;
7892
+ };
7893
+ is.amexCard = is.amexCardNum = is.americanExpressCardNumber;
7894
+ /**
7895
+ * Test if card number is a China UnionPay card.
7896
+ * @param {String} the credit card number string to test.
7897
+ * @return true if the string is the correct format, false otherwise
7898
+ */
7899
+ is.chinaUnionPayCardNumber = function(str) {
7900
+ if (!is.str(str) || str.length < 16 && str.length > 19) return false;
7901
+ var prefix = Math.floor(str.slice(0, 2));
7902
+ if (prefix !== 62 && prefix !== 88) return false;
7903
+ return true;
7904
+ };
7905
+ is.chinaUnion = is.chinaUnionPayCard = is.chinaUnionPayCardNumber;
7906
+ /**
7907
+ * Test if card number is a Diner's Club Carte Blance card.
7908
+ * @param {String} the credit card number string to test.
7909
+ * @return true if the string is the correct format, false otherwise
7910
+ */
7911
+ is.dinersClubCarteBlancheCardNumber = function(str) {
7912
+ if (!is.str(str) || str.length !== 14) return false;
7913
+ var prefix = Math.floor(str.slice(0, 3));
7914
+ if (prefix < 300 || prefix > 305) return false;
7915
+ if (!is.creditCardNumber(str)) return false;
7916
+ return true;
7917
+ };
7918
+ is.dinersClubCB = is.dinersClubCarteBlancheCard = is.dinersClubCarteBlancheCardNumber;
7919
+ /**
7920
+ * Test if card number is a Diner's Club International card.
7921
+ * @param {String} the credit card number string to test.
7922
+ * @return true if the string is the correct format, false otherwise
7923
+ */
7924
+ is.dinersClubInternationalCardNumber = function(str) {
7925
+ if (!is.str(str) || str.length !== 14) return false;
7926
+ var prefix = Math.floor(str.slice(0, 3));
7927
+ var prefix2 = Math.floor(str.slice(0, 2));
7928
+ if ((prefix < 300 || prefix > 305) && prefix !== 309 && prefix2 !== 36 && (prefix2 < 38 || prefix2 > 39)) return false;
7929
+ if (!is.creditCardNumber(str)) return false;
7930
+ return true;
7931
+ };
7932
+ is.dinersClubInt = is.dinersClubInternationalCard = is.dinersClubInternationalCardNumber;
7933
+ /**
7934
+ * Test if card number is a Diner's Club USA & CA card.
7935
+ * @param {String} the credit card number string to test.
7936
+ * @return true if the string is the correct format, false otherwise
7937
+ */
7938
+ is.dinersClubUSACanadaCardNumber = function(str) {
7939
+ if (!is.str(str) || str.length !== 16) return false;
7940
+ var prefix = Math.floor(str.slice(0, 2));
7941
+ if (prefix !== 54 && prefix !== 55) return false;
7942
+ if (!is.creditCardNumber(str)) return false;
7943
+ return true;
7944
+ };
7945
+ is.dinersClub = is.dinersClubUSACanCard = is.dinersClubUSACanadaCardNumber;
7946
+ /**
7947
+ * Test if card number is a Diner's Club USA/CA card.
7948
+ * @param {String} the credit card number string to test.
7949
+ * @return true if the string is the correct format, false otherwise
7950
+ */
7951
+ is.discoverCardNumber = function(str) {
7952
+ if (!is.str(str) || str.length !== 16) return false;
7953
+ var prefix = Math.floor(str.slice(0, 6));
7954
+ var prefix2 = Math.floor(str.slice(0, 3));
7955
+ if (str.slice(0, 4) !== "6011" && (prefix < 622126 || prefix > 622925) && (prefix2 < 644 || prefix2 > 649) && str.slice(0, 2) !== "65") return false;
7956
+ if (!is.creditCardNumber(str)) return false;
7957
+ return true;
7958
+ };
7959
+ is.discover = is.discoverCard = is.discoverCardNumber;
7960
+ /**
7961
+ * Test if card number is an InstaPayment card number
7962
+ * @param {String} the credit card number string to test.
7963
+ * @return true if the string is the correct format, false otherwise
7964
+ */
7965
+ is.instaPaymentCardNumber = function(str) {
7966
+ if (!is.str(str) || str.length !== 16) return false;
7967
+ var prefix = Math.floor(str.slice(0, 3));
7968
+ if (prefix < 637 || prefix > 639) return false;
7969
+ if (!is.creditCardNumber(str)) return false;
7970
+ return true;
7971
+ };
7972
+ is.instaPayment = is.instaPaymentCardNumber;
7973
+ /**
7974
+ * Test if card number is a JCB card number
7975
+ * @param {String} the credit card number string to test.
7976
+ * @return true if the string is the correct format, false otherwise
7977
+ */
7978
+ is.jcbCardNumber = function(str) {
7979
+ if (!is.str(str) || str.length !== 16) return false;
7980
+ var prefix = Math.floor(str.slice(0, 4));
7981
+ if (prefix < 3528 || prefix > 3589) return false;
7982
+ if (!is.creditCardNumber(str)) return false;
7983
+ return true;
7984
+ };
7985
+ is.jcb = is.jcbCard = is.jcbCardNumber;
7986
+ /**
7987
+ * Test if card number is a Laser card number
7988
+ * @param {String} the credit card number string to test.
7989
+ * @return true if the string is the correct format, false otherwise
7990
+ */
7991
+ is.laserCardNumber = function(str) {
7992
+ if (!is.str(str) || str.length < 16 && str.length > 19) return false;
7993
+ var prefix = Math.floor(str.slice(0, 4));
7994
+ if ([
7995
+ 6304,
7996
+ 6706,
7997
+ 6771,
7998
+ 6709
7999
+ ].indexOf(prefix) === -1) return false;
8000
+ if (!is.creditCardNumber(str)) return false;
8001
+ return true;
8002
+ };
8003
+ is.laser = is.laserCard = is.laserCardNumber;
8004
+ /**
8005
+ * Test if card number is a Maestro card number
8006
+ * @param {String} the credit card number string to test.
8007
+ * @return true if the string is the correct format, false otherwise
8008
+ */
8009
+ is.maestroCardNumber = function(str) {
8010
+ if (!is.str(str) || str.length < 12 || str.length > 19) return false;
8011
+ var prefix = str.slice(0, 4);
8012
+ if ([
8013
+ "5018",
8014
+ "5020",
8015
+ "5038",
8016
+ "5612",
8017
+ "5893",
8018
+ "6304",
8019
+ "6759",
8020
+ "6761",
8021
+ "6762",
8022
+ "6763",
8023
+ "0604",
8024
+ "6390"
8025
+ ].indexOf(prefix) === -1) return false;
8026
+ if (!is.creditCardNumber(str)) return false;
8027
+ return true;
8028
+ };
8029
+ is.maestro = is.maestroCard = is.maestroCardNumber;
8030
+ /**
8031
+ * Test if card number is a Dankort card number
8032
+ * @param {String} the credit card number string to test.
8033
+ * @return true if the string is the correct format, false otherwise
8034
+ */
8035
+ is.dankortCardNumber = function(str) {
8036
+ if (!is.str(str) || str.length !== 16) return false;
8037
+ if (str.slice(0, 4) !== "5019") return false;
8038
+ if (!is.creditCardNumber(str)) return false;
8039
+ return true;
8040
+ };
8041
+ is.dankort = is.dankortCard = is.dankortCardNumber;
8042
+ /**
8043
+ * Test if card number is a MasterCard card number
8044
+ * @param {String} the credit card number string to test.
8045
+ * @return true if the string is the correct format, false otherwise
8046
+ */
8047
+ is.masterCardCardNumber = function(str) {
8048
+ if (!is.str(str) || str.length !== 16) return false;
8049
+ var prefix = Math.floor(str.slice(0, 2));
8050
+ if (prefix < 50 || prefix > 55) return false;
8051
+ if (!is.creditCardNumber(str)) return false;
8052
+ return true;
8053
+ };
8054
+ is.masterCard = is.masterCardCard = is.masterCardCardNumber;
8055
+ /**
8056
+ * Test if card number is a Visa card number
8057
+ * @param {String} the credit card number string to test.
8058
+ * @return true if the string is the correct format, false otherwise
8059
+ */
8060
+ is.visaCardNumber = function(str) {
8061
+ if (!is.str(str) || str.length !== 13 && str.length !== 16) return false;
8062
+ if ("4" !== str.slice(0, 1)) return false;
8063
+ if (!is.creditCardNumber(str)) return false;
8064
+ return true;
8065
+ };
8066
+ is.visa = is.visaCard = is.visaCardNumber;
8067
+ /**
8068
+ * Test if card number is a Visa card number
8069
+ * @param {String} the credit card number string to test.
8070
+ * @return true if the string is the correct format, false otherwise
8071
+ */
8072
+ is.visaElectronCardNumber = function(str) {
8073
+ if (!is.str(str) || str.length !== 16) return false;
8074
+ var prefix = Math.floor(str.slice(0, 4));
8075
+ if ("417500" !== str.slice(0, 6) && [
8076
+ 4026,
8077
+ 4405,
8078
+ 4508,
8079
+ 4844,
8080
+ 4913,
8081
+ 4917
8082
+ ].indexOf(prefix) === -1) return false;
8083
+ if (!is.creditCardNumber(str)) return false;
8084
+ return false;
8085
+ };
8086
+ is.visaElectron = is.visaElectronCard = is.visaElectronCardNumber;
8087
+ /**
8088
+ * Test if the input is a valid MongoDB id.
8089
+ * @param {String|Object} Either a mongodb object id or a string representation.
8090
+ * @return true if the string is the correct format, false otherwise
8091
+ * Thanks to Jason Denizac (https://github.com/jden) for pointing this out.
8092
+ * https://github.com/jden/objectid/blob/master/index.js#L7-L10
8093
+ */
8094
+ var objIdPattern = /^[0-9a-fA-F]{24}$/;
8095
+ is.mongoId = is.objectId = is.objId = function(id) {
8096
+ return Boolean(id) && !Array.isArray(id) && objIdPattern.test(String(id));
8097
+ };
8098
+ /**
8099
+ * Test is the first argument is structly equal to any of the subsequent args.
8100
+ * @param Value to test against subsequent arguments.
8101
+ * @return true if the first value matches any of subsequent values.
8102
+ */
8103
+ is.matching = is.match = is.inArgs = function(val) {
8104
+ if (arguments.length < 2) return false;
8105
+ var result = false;
8106
+ for (var i = 1; i < arguments.length; i++) {
8107
+ var eq = is.equal(val, arguments[i]);
8108
+ result = result || eq;
8109
+ }
8110
+ return result;
8111
+ };
8112
+ /**********************************
8113
+ ***Definitely a work in progress***
8114
+ **********************************/
8115
+ /**
8116
+ * Test if a string contains a US street address
8117
+ * @param {String} the string to search
8118
+ * @return true if an address is present, false otherwise
8119
+ */
8120
+ is.streetAddress = function(str) {
8121
+ if (!is.str(str)) return false;
8122
+ return /\b\d+[\s](?:[A-Za-z0-9.-]+[\s]+)+\b(ALLEY|ALY|AVENUE|AVE|BEND|BND|BLUFFS?|BLFS?|BOULEVARD|BLVD|BRANCH|BR|CENTERS?|CTRS?|CIRCLES?|CIRS?|CLIFFS?|CLFS?|COURTS?|CTS?|COVES?|CVS?|CREEK|CRK|CRESCENT|CRES|CREST|CRST|CROSSING|XING|DRIVES?|DRS?|EXPRESSWAY|EXPY|FREEWAY|FWY|HEIGHTS|HTS|HIGHWAY|HWY|HILLS?|HLS?|LANE|LN|LOOP|MANORS?|MNRS?|MOTORWAY|MTWY|MOUNT|MT|PARKS?|PARKWAYS?|PKWY|PASS|PLACE|PL|PLAZA|PLZ|POINTS?|PTS?|RIDGES?|RDGS?|ROADS?|RDS?|ROUTE|RTE?|SHOALS?|SHLS?|SHORES?|SHRS?|SPRINGS?|SPGS?|SPURS?|STREETS?|STS?|SUMMIT|SMT|TERRACE|TER|THROUGHWAY|TRWY|TRAFFICWAY|TRFY|TRAIL|TRL|TURNPIKE|TPKE|VALLEYS?|VLYS?|WAYS?)+(?:[\.\-\s\,]?)*((APARTMENT|APT|APPT|#|NUMBER|NUM|FLOOR|FL|\s)?(\d)*)\b/gi.test(str);
8123
+ };
8124
+ is.street = is.address = is.streetAddress;
8125
+ /**
8126
+ * Test if a string resembles a US Zip code,
8127
+ * no regular expression will be perfect for this,
8128
+ * as there are many numbers that aren't valid zip codes
8129
+ * @param {String || Number} the string or number literal to test
8130
+ * @return true if zipcode like, false otherwise
8131
+ */
8132
+ is.zipCode = function(str) {
8133
+ if (is.undefined(str) || !(is.string(str) || is.number(str))) return false;
8134
+ return /^\d{5}(?:-\d{4})?$/.test(str);
8135
+ };
8136
+ is.zip = is.zipCode;
8137
+ /**
8138
+ * Test if a string contains a US phone number
8139
+ * @param {String} the string to search
8140
+ * @return true if str contains a phone number, false otherwise.
8141
+ */
8142
+ is.phoneNumber = function(str) {
8143
+ if (!is.string(str)) return false;
8144
+ return /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\(?)(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]‌​)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\)?)\s*(?:[.-]\s*)?)?([2-9]1[02-‌​9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})/g.test(str);
8145
+ };
8146
+ is.phone = is.phoneNumber;
8147
+ /**
8148
+ * Test is a string is a valid URL
8149
+ * @param {string} val - the possible url to check
8150
+ * @return true if str contains a phone number, false otherwise.
8151
+ */
8152
+ var isUrl = require_is_url();
8153
+ is.url = function(val) {
8154
+ return isUrl(val);
8155
+ };
8156
+ is.uri = is.url;
8157
+ is.enumerator = function(val, ary) {
8158
+ var value = false;
8159
+ if (!is.defined(val) || !is.defined(ary) || !is.arrayLike(ary)) return value;
8160
+ for (var i = 0, len = ary.length; i < len; i++) if (is.equal(val, ary[i])) {
8161
+ value = true;
8162
+ break;
8163
+ }
8164
+ return value;
8165
+ };
8166
+ is.enum = is.inArray = is.enumerator;
8167
+ }));
8168
+ //#endregion
8169
+ //#region node_modules/tcp-port-used/node_modules/ms/index.js
8170
+ var require_ms = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8171
+ /**
8172
+ * Helpers.
8173
+ */
8174
+ var s = 1e3;
8175
+ var m = s * 60;
8176
+ var h = m * 60;
8177
+ var d = h * 24;
8178
+ var w = d * 7;
8179
+ var y = d * 365.25;
8180
+ /**
8181
+ * Parse or format the given `val`.
8182
+ *
8183
+ * Options:
8184
+ *
8185
+ * - `long` verbose formatting [false]
8186
+ *
8187
+ * @param {String|Number} val
8188
+ * @param {Object} [options]
8189
+ * @throws {Error} throw an error if val is not a non-empty string or a number
8190
+ * @return {String|Number}
8191
+ * @api public
8192
+ */
8193
+ module.exports = function(val, options) {
8194
+ options = options || {};
8195
+ var type = typeof val;
8196
+ if (type === "string" && val.length > 0) return parse(val);
8197
+ else if (type === "number" && isFinite(val)) return options.long ? fmtLong(val) : fmtShort(val);
8198
+ throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val));
8199
+ };
8200
+ /**
8201
+ * Parse the given `str` and return milliseconds.
8202
+ *
8203
+ * @param {String} str
8204
+ * @return {Number}
8205
+ * @api private
8206
+ */
8207
+ function parse(str) {
8208
+ str = String(str);
8209
+ if (str.length > 100) return;
8210
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
8211
+ if (!match) return;
8212
+ var n = parseFloat(match[1]);
8213
+ switch ((match[2] || "ms").toLowerCase()) {
8214
+ case "years":
8215
+ case "year":
8216
+ case "yrs":
8217
+ case "yr":
8218
+ case "y": return n * y;
8219
+ case "weeks":
8220
+ case "week":
8221
+ case "w": return n * w;
8222
+ case "days":
8223
+ case "day":
8224
+ case "d": return n * d;
8225
+ case "hours":
8226
+ case "hour":
8227
+ case "hrs":
8228
+ case "hr":
8229
+ case "h": return n * h;
8230
+ case "minutes":
8231
+ case "minute":
8232
+ case "mins":
8233
+ case "min":
8234
+ case "m": return n * m;
8235
+ case "seconds":
8236
+ case "second":
8237
+ case "secs":
8238
+ case "sec":
8239
+ case "s": return n * s;
8240
+ case "milliseconds":
8241
+ case "millisecond":
8242
+ case "msecs":
8243
+ case "msec":
8244
+ case "ms": return n;
8245
+ default: return;
8246
+ }
8247
+ }
8248
+ /**
8249
+ * Short format for `ms`.
8250
+ *
8251
+ * @param {Number} ms
8252
+ * @return {String}
8253
+ * @api private
8254
+ */
8255
+ function fmtShort(ms) {
8256
+ var msAbs = Math.abs(ms);
8257
+ if (msAbs >= d) return Math.round(ms / d) + "d";
8258
+ if (msAbs >= h) return Math.round(ms / h) + "h";
8259
+ if (msAbs >= m) return Math.round(ms / m) + "m";
8260
+ if (msAbs >= s) return Math.round(ms / s) + "s";
8261
+ return ms + "ms";
8262
+ }
8263
+ /**
8264
+ * Long format for `ms`.
8265
+ *
8266
+ * @param {Number} ms
8267
+ * @return {String}
8268
+ * @api private
8269
+ */
8270
+ function fmtLong(ms) {
8271
+ var msAbs = Math.abs(ms);
8272
+ if (msAbs >= d) return plural(ms, msAbs, d, "day");
8273
+ if (msAbs >= h) return plural(ms, msAbs, h, "hour");
8274
+ if (msAbs >= m) return plural(ms, msAbs, m, "minute");
8275
+ if (msAbs >= s) return plural(ms, msAbs, s, "second");
8276
+ return ms + " ms";
8277
+ }
8278
+ /**
8279
+ * Pluralization helper.
8280
+ */
8281
+ function plural(ms, msAbs, n, name) {
8282
+ var isPlural = msAbs >= n * 1.5;
8283
+ return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
8284
+ }
8285
+ }));
8286
+ //#endregion
8287
+ //#region node_modules/tcp-port-used/node_modules/debug/src/common.js
8288
+ var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8289
+ /**
8290
+ * This is the common logic for both the Node.js and web browser
8291
+ * implementations of `debug()`.
8292
+ */
8293
+ function setup(env) {
8294
+ createDebug.debug = createDebug;
8295
+ createDebug.default = createDebug;
8296
+ createDebug.coerce = coerce;
8297
+ createDebug.disable = disable;
8298
+ createDebug.enable = enable;
8299
+ createDebug.enabled = enabled;
8300
+ createDebug.humanize = require_ms();
8301
+ createDebug.destroy = destroy;
8302
+ Object.keys(env).forEach((key) => {
8303
+ createDebug[key] = env[key];
8304
+ });
8305
+ /**
8306
+ * The currently active debug mode names, and names to skip.
8307
+ */
8308
+ createDebug.names = [];
8309
+ createDebug.skips = [];
8310
+ /**
8311
+ * Map of special "%n" handling functions, for the debug "format" argument.
8312
+ *
8313
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
8314
+ */
8315
+ createDebug.formatters = {};
8316
+ /**
8317
+ * Selects a color for a debug namespace
8318
+ * @param {String} namespace The namespace string for the for the debug instance to be colored
8319
+ * @return {Number|String} An ANSI color code for the given namespace
8320
+ * @api private
8321
+ */
8322
+ function selectColor(namespace) {
8323
+ let hash = 0;
8324
+ for (let i = 0; i < namespace.length; i++) {
8325
+ hash = (hash << 5) - hash + namespace.charCodeAt(i);
8326
+ hash |= 0;
8327
+ }
8328
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
8329
+ }
8330
+ createDebug.selectColor = selectColor;
8331
+ /**
8332
+ * Create a debugger with the given `namespace`.
8333
+ *
8334
+ * @param {String} namespace
8335
+ * @return {Function}
8336
+ * @api public
8337
+ */
8338
+ function createDebug(namespace) {
8339
+ let prevTime;
8340
+ let enableOverride = null;
8341
+ function debug(...args) {
8342
+ if (!debug.enabled) return;
8343
+ const self = debug;
8344
+ const curr = Number(/* @__PURE__ */ new Date());
8345
+ self.diff = curr - (prevTime || curr);
8346
+ self.prev = prevTime;
8347
+ self.curr = curr;
8348
+ prevTime = curr;
8349
+ args[0] = createDebug.coerce(args[0]);
8350
+ if (typeof args[0] !== "string") args.unshift("%O");
8351
+ let index = 0;
8352
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
8353
+ if (match === "%%") return "%";
8354
+ index++;
8355
+ const formatter = createDebug.formatters[format];
8356
+ if (typeof formatter === "function") {
8357
+ const val = args[index];
8358
+ match = formatter.call(self, val);
8359
+ args.splice(index, 1);
8360
+ index--;
8361
+ }
8362
+ return match;
8363
+ });
8364
+ createDebug.formatArgs.call(self, args);
8365
+ (self.log || createDebug.log).apply(self, args);
8366
+ }
8367
+ debug.namespace = namespace;
8368
+ debug.useColors = createDebug.useColors();
8369
+ debug.color = createDebug.selectColor(namespace);
8370
+ debug.extend = extend;
8371
+ debug.destroy = createDebug.destroy;
8372
+ Object.defineProperty(debug, "enabled", {
8373
+ enumerable: true,
8374
+ configurable: false,
8375
+ get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,
8376
+ set: (v) => {
8377
+ enableOverride = v;
8378
+ }
8379
+ });
8380
+ if (typeof createDebug.init === "function") createDebug.init(debug);
8381
+ return debug;
8382
+ }
8383
+ function extend(namespace, delimiter) {
8384
+ const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
8385
+ newDebug.log = this.log;
8386
+ return newDebug;
8387
+ }
8388
+ /**
8389
+ * Enables a debug mode by namespaces. This can include modes
8390
+ * separated by a colon and wildcards.
8391
+ *
8392
+ * @param {String} namespaces
8393
+ * @api public
8394
+ */
8395
+ function enable(namespaces) {
8396
+ createDebug.save(namespaces);
8397
+ createDebug.names = [];
8398
+ createDebug.skips = [];
8399
+ let i;
8400
+ const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
8401
+ const len = split.length;
8402
+ for (i = 0; i < len; i++) {
8403
+ if (!split[i]) continue;
8404
+ namespaces = split[i].replace(/\*/g, ".*?");
8405
+ if (namespaces[0] === "-") createDebug.skips.push(new RegExp("^" + namespaces.substr(1) + "$"));
8406
+ else createDebug.names.push(new RegExp("^" + namespaces + "$"));
8407
+ }
8408
+ }
8409
+ /**
8410
+ * Disable debug output.
8411
+ *
8412
+ * @return {String} namespaces
8413
+ * @api public
8414
+ */
8415
+ function disable() {
8416
+ const namespaces = [...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)].join(",");
8417
+ createDebug.enable("");
8418
+ return namespaces;
8419
+ }
8420
+ /**
8421
+ * Returns true if the given mode name is enabled, false otherwise.
8422
+ *
8423
+ * @param {String} name
8424
+ * @return {Boolean}
8425
+ * @api public
8426
+ */
8427
+ function enabled(name) {
8428
+ if (name[name.length - 1] === "*") return true;
8429
+ let i;
8430
+ let len;
8431
+ for (i = 0, len = createDebug.skips.length; i < len; i++) if (createDebug.skips[i].test(name)) return false;
8432
+ for (i = 0, len = createDebug.names.length; i < len; i++) if (createDebug.names[i].test(name)) return true;
8433
+ return false;
8434
+ }
8435
+ /**
8436
+ * Convert regexp to namespace
8437
+ *
8438
+ * @param {RegExp} regxep
8439
+ * @return {String} namespace
8440
+ * @api private
8441
+ */
8442
+ function toNamespace(regexp) {
8443
+ return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
8444
+ }
8445
+ /**
8446
+ * Coerce `val`.
8447
+ *
8448
+ * @param {Mixed} val
8449
+ * @return {Mixed}
8450
+ * @api private
8451
+ */
8452
+ function coerce(val) {
8453
+ if (val instanceof Error) return val.stack || val.message;
8454
+ return val;
8455
+ }
8456
+ /**
8457
+ * XXX DO NOT USE. This is a temporary stub function.
8458
+ * XXX It WILL be removed in the next major release.
8459
+ */
8460
+ function destroy() {
8461
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
8462
+ }
8463
+ createDebug.enable(createDebug.load());
8464
+ return createDebug;
8465
+ }
8466
+ module.exports = setup;
8467
+ }));
8468
+ //#endregion
8469
+ //#region node_modules/tcp-port-used/node_modules/debug/src/browser.js
8470
+ var require_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8471
+ /**
8472
+ * This is the web browser implementation of `debug()`.
8473
+ */
8474
+ exports.formatArgs = formatArgs;
8475
+ exports.save = save;
8476
+ exports.load = load;
8477
+ exports.useColors = useColors;
8478
+ exports.storage = localstorage();
8479
+ exports.destroy = (() => {
8480
+ let warned = false;
8481
+ return () => {
8482
+ if (!warned) {
8483
+ warned = true;
8484
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
8485
+ }
8486
+ };
8487
+ })();
8488
+ /**
8489
+ * Colors.
8490
+ */
8491
+ exports.colors = [
8492
+ "#0000CC",
8493
+ "#0000FF",
8494
+ "#0033CC",
8495
+ "#0033FF",
8496
+ "#0066CC",
8497
+ "#0066FF",
8498
+ "#0099CC",
8499
+ "#0099FF",
8500
+ "#00CC00",
8501
+ "#00CC33",
8502
+ "#00CC66",
8503
+ "#00CC99",
8504
+ "#00CCCC",
8505
+ "#00CCFF",
8506
+ "#3300CC",
8507
+ "#3300FF",
8508
+ "#3333CC",
8509
+ "#3333FF",
8510
+ "#3366CC",
8511
+ "#3366FF",
8512
+ "#3399CC",
8513
+ "#3399FF",
8514
+ "#33CC00",
8515
+ "#33CC33",
8516
+ "#33CC66",
8517
+ "#33CC99",
8518
+ "#33CCCC",
8519
+ "#33CCFF",
8520
+ "#6600CC",
8521
+ "#6600FF",
8522
+ "#6633CC",
8523
+ "#6633FF",
8524
+ "#66CC00",
8525
+ "#66CC33",
8526
+ "#9900CC",
8527
+ "#9900FF",
8528
+ "#9933CC",
8529
+ "#9933FF",
8530
+ "#99CC00",
8531
+ "#99CC33",
8532
+ "#CC0000",
8533
+ "#CC0033",
8534
+ "#CC0066",
8535
+ "#CC0099",
8536
+ "#CC00CC",
8537
+ "#CC00FF",
8538
+ "#CC3300",
8539
+ "#CC3333",
8540
+ "#CC3366",
8541
+ "#CC3399",
8542
+ "#CC33CC",
8543
+ "#CC33FF",
8544
+ "#CC6600",
8545
+ "#CC6633",
8546
+ "#CC9900",
8547
+ "#CC9933",
8548
+ "#CCCC00",
8549
+ "#CCCC33",
8550
+ "#FF0000",
8551
+ "#FF0033",
8552
+ "#FF0066",
8553
+ "#FF0099",
8554
+ "#FF00CC",
8555
+ "#FF00FF",
8556
+ "#FF3300",
8557
+ "#FF3333",
8558
+ "#FF3366",
8559
+ "#FF3399",
8560
+ "#FF33CC",
8561
+ "#FF33FF",
8562
+ "#FF6600",
8563
+ "#FF6633",
8564
+ "#FF9900",
8565
+ "#FF9933",
8566
+ "#FFCC00",
8567
+ "#FFCC33"
8568
+ ];
8569
+ /**
8570
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
8571
+ * and the Firebug extension (any Firefox version) are known
8572
+ * to support "%c" CSS customizations.
8573
+ *
8574
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
8575
+ */
8576
+ function useColors() {
8577
+ if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) return true;
8578
+ if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) return false;
8579
+ return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
8580
+ }
8581
+ /**
8582
+ * Colorize log arguments if enabled.
8583
+ *
8584
+ * @api public
8585
+ */
8586
+ function formatArgs(args) {
8587
+ args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
8588
+ if (!this.useColors) return;
8589
+ const c = "color: " + this.color;
8590
+ args.splice(1, 0, c, "color: inherit");
8591
+ let index = 0;
8592
+ let lastC = 0;
8593
+ args[0].replace(/%[a-zA-Z%]/g, (match) => {
8594
+ if (match === "%%") return;
8595
+ index++;
8596
+ if (match === "%c") lastC = index;
8597
+ });
8598
+ args.splice(lastC, 0, c);
8599
+ }
8600
+ /**
8601
+ * Invokes `console.debug()` when available.
8602
+ * No-op when `console.debug` is not a "function".
8603
+ * If `console.debug` is not available, falls back
8604
+ * to `console.log`.
8605
+ *
8606
+ * @api public
8607
+ */
8608
+ exports.log = console.debug || console.log || (() => {});
8609
+ /**
8610
+ * Save `namespaces`.
8611
+ *
8612
+ * @param {String} namespaces
8613
+ * @api private
8614
+ */
8615
+ function save(namespaces) {
8616
+ try {
8617
+ if (namespaces) exports.storage.setItem("debug", namespaces);
8618
+ else exports.storage.removeItem("debug");
8619
+ } catch (error) {}
8620
+ }
8621
+ /**
8622
+ * Load `namespaces`.
8623
+ *
8624
+ * @return {String} returns the previously persisted debug modes
8625
+ * @api private
8626
+ */
8627
+ function load() {
8628
+ let r;
8629
+ try {
8630
+ r = exports.storage.getItem("debug");
8631
+ } catch (error) {}
8632
+ if (!r && typeof process !== "undefined" && "env" in process) r = process.env.DEBUG;
8633
+ return r;
8634
+ }
8635
+ /**
8636
+ * Localstorage attempts to return the localstorage.
8637
+ *
8638
+ * This is necessary because safari throws
8639
+ * when a user disables cookies/localstorage
8640
+ * and you attempt to access it.
8641
+ *
8642
+ * @return {LocalStorage}
8643
+ * @api private
8644
+ */
8645
+ function localstorage() {
8646
+ try {
8647
+ return localStorage;
8648
+ } catch (error) {}
8649
+ }
8650
+ module.exports = require_common()(exports);
8651
+ const { formatters } = module.exports;
8652
+ /**
8653
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
8654
+ */
8655
+ formatters.j = function(v) {
8656
+ try {
8657
+ return JSON.stringify(v);
8658
+ } catch (error) {
8659
+ return "[UnexpectedJSONParseError]: " + error.message;
8660
+ }
8661
+ };
8662
+ }));
8663
+ //#endregion
8664
+ //#region node_modules/tcp-port-used/node_modules/debug/src/node.js
8665
+ var require_node = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8666
+ /**
8667
+ * Module dependencies.
8668
+ */
8669
+ const tty = __require("tty");
8670
+ const util$1 = __require("util");
8671
+ /**
8672
+ * This is the Node.js implementation of `debug()`.
8673
+ */
8674
+ exports.init = init;
8675
+ exports.log = log;
8676
+ exports.formatArgs = formatArgs;
8677
+ exports.save = save;
8678
+ exports.load = load;
8679
+ exports.useColors = useColors;
8680
+ exports.destroy = util$1.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
8681
+ /**
8682
+ * Colors.
8683
+ */
8684
+ exports.colors = [
8685
+ 6,
8686
+ 2,
8687
+ 3,
8688
+ 4,
8689
+ 5,
8690
+ 1
8691
+ ];
8692
+ try {
8693
+ const supportsColor = require_supports_color();
8694
+ if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) exports.colors = [
8695
+ 20,
8696
+ 21,
8697
+ 26,
8698
+ 27,
8699
+ 32,
8700
+ 33,
8701
+ 38,
8702
+ 39,
8703
+ 40,
8704
+ 41,
8705
+ 42,
8706
+ 43,
8707
+ 44,
8708
+ 45,
8709
+ 56,
8710
+ 57,
8711
+ 62,
8712
+ 63,
8713
+ 68,
8714
+ 69,
8715
+ 74,
8716
+ 75,
8717
+ 76,
8718
+ 77,
8719
+ 78,
8720
+ 79,
8721
+ 80,
8722
+ 81,
8723
+ 92,
8724
+ 93,
8725
+ 98,
8726
+ 99,
8727
+ 112,
8728
+ 113,
8729
+ 128,
8730
+ 129,
8731
+ 134,
8732
+ 135,
8733
+ 148,
8734
+ 149,
8735
+ 160,
8736
+ 161,
8737
+ 162,
8738
+ 163,
8739
+ 164,
8740
+ 165,
8741
+ 166,
8742
+ 167,
8743
+ 168,
8744
+ 169,
8745
+ 170,
8746
+ 171,
8747
+ 172,
8748
+ 173,
8749
+ 178,
8750
+ 179,
8751
+ 184,
8752
+ 185,
8753
+ 196,
8754
+ 197,
8755
+ 198,
8756
+ 199,
8757
+ 200,
8758
+ 201,
8759
+ 202,
8760
+ 203,
8761
+ 204,
8762
+ 205,
8763
+ 206,
8764
+ 207,
8765
+ 208,
8766
+ 209,
8767
+ 214,
8768
+ 215,
8769
+ 220,
8770
+ 221
8771
+ ];
8772
+ } catch (error) {}
8773
+ /**
8774
+ * Build up the default `inspectOpts` object from the environment variables.
8775
+ *
8776
+ * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
8777
+ */
8778
+ exports.inspectOpts = Object.keys(process.env).filter((key) => {
8779
+ return /^debug_/i.test(key);
8780
+ }).reduce((obj, key) => {
8781
+ const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
8782
+ return k.toUpperCase();
8783
+ });
8784
+ let val = process.env[key];
8785
+ if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
8786
+ else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
8787
+ else if (val === "null") val = null;
8788
+ else val = Number(val);
8789
+ obj[prop] = val;
8790
+ return obj;
8791
+ }, {});
8792
+ /**
8793
+ * Is stdout a TTY? Colored output is enabled when `true`.
8794
+ */
8795
+ function useColors() {
8796
+ return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
8797
+ }
8798
+ /**
8799
+ * Adds ANSI color escape codes if enabled.
8800
+ *
8801
+ * @api public
8802
+ */
8803
+ function formatArgs(args) {
8804
+ const { namespace: name, useColors } = this;
8805
+ if (useColors) {
8806
+ const c = this.color;
8807
+ const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
8808
+ const prefix = ` ${colorCode};1m${name} \u001B[0m`;
8809
+ args[0] = prefix + args[0].split("\n").join("\n" + prefix);
8810
+ args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
8811
+ } else args[0] = getDate() + name + " " + args[0];
8812
+ }
8813
+ function getDate() {
8814
+ if (exports.inspectOpts.hideDate) return "";
8815
+ return (/* @__PURE__ */ new Date()).toISOString() + " ";
8816
+ }
8817
+ /**
8818
+ * Invokes `util.format()` with the specified arguments and writes to stderr.
8819
+ */
8820
+ function log(...args) {
8821
+ return process.stderr.write(util$1.format(...args) + "\n");
8822
+ }
8823
+ /**
8824
+ * Save `namespaces`.
8825
+ *
8826
+ * @param {String} namespaces
8827
+ * @api private
8828
+ */
8829
+ function save(namespaces) {
8830
+ if (namespaces) process.env.DEBUG = namespaces;
8831
+ else delete process.env.DEBUG;
8832
+ }
8833
+ /**
8834
+ * Load `namespaces`.
8835
+ *
8836
+ * @return {String} returns the previously persisted debug modes
8837
+ * @api private
8838
+ */
8839
+ function load() {
8840
+ return process.env.DEBUG;
8841
+ }
8842
+ /**
8843
+ * Init logic for `debug` instances.
8844
+ *
8845
+ * Create a new `inspectOpts` object in case `useColors` is set
8846
+ * differently for a particular `debug` instance.
8847
+ */
8848
+ function init(debug) {
8849
+ debug.inspectOpts = {};
8850
+ const keys = Object.keys(exports.inspectOpts);
8851
+ for (let i = 0; i < keys.length; i++) debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
8852
+ }
8853
+ module.exports = require_common()(exports);
8854
+ const { formatters } = module.exports;
8855
+ /**
8856
+ * Map %o to `util.inspect()`, all on a single line.
8857
+ */
8858
+ formatters.o = function(v) {
8859
+ this.inspectOpts.colors = this.useColors;
8860
+ return util$1.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
8861
+ };
8862
+ /**
8863
+ * Map %O to `util.inspect()`, allowing multiple lines if needed.
8864
+ */
8865
+ formatters.O = function(v) {
8866
+ this.inspectOpts.colors = this.useColors;
8867
+ return util$1.inspect(v, this.inspectOpts);
8868
+ };
8869
+ }));
8870
+ //#endregion
8871
+ //#region node_modules/tcp-port-used/node_modules/debug/src/index.js
8872
+ var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8873
+ /**
8874
+ * Detect Electron renderer / nwjs process, which is node, but we should
8875
+ * treat as a browser.
8876
+ */
8877
+ if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) module.exports = require_browser();
8878
+ else module.exports = require_node();
8879
+ }));
8880
+ //#endregion
8881
+ //#region dist/node/runtime/node/setup-kubo-address-rewriter-and-http-router.js
8882
+ var import_tcp_port_used = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
8883
+ exports.check = check;
8884
+ var is = require_is2();
8885
+ var net = __require("net");
8886
+ var util = __require("util");
8887
+ var debug = require_src()("tcp-port-used");
8888
+ function getDeferred() {
8889
+ var resolve, reject, promise = new Promise(function(res, rej) {
8890
+ resolve = res;
8891
+ reject = rej;
8892
+ });
8893
+ return {
8894
+ resolve,
8895
+ reject,
8896
+ promise
8897
+ };
8898
+ }
8899
+ /**
8900
+ * Creates an options object from all the possible arguments
8901
+ * @private
8902
+ * @param {Number} port a valid TCP port number
8903
+ * @param {String} host The DNS name or IP address.
8904
+ * @param {Boolean} status The desired in use status to wait for: false === not in use, true === in use
8905
+ * @param {Number} retryTimeMs the retry interval in milliseconds - defaultis is 200ms
8906
+ * @param {Number} timeOutMs the amount of time to wait until port is free default is 1000ms
8907
+ * @return {Object} An options object with all the above parameters as properties.
8908
+ */
8909
+ function makeOptionsObj(port, host, inUse, retryTimeMs, timeOutMs) {
8910
+ var opts = {};
8911
+ opts.port = port;
8912
+ opts.host = host;
8913
+ opts.inUse = inUse;
8914
+ opts.retryTimeMs = retryTimeMs;
8915
+ opts.timeOutMs = timeOutMs;
8916
+ return opts;
8917
+ }
8918
+ /**
8919
+ * Checks if a TCP port is in use by creating the socket and binding it to the
8920
+ * target port. Once bound, successfully, it's assume the port is availble.
8921
+ * After the socket is closed or in error, the promise is resolved.
8922
+ * Note: you have to be super user to correctly test system ports (0-1023).
8923
+ * @param {Number|Object} port The port you are curious to see if available. If an object, must have the parameters as properties.
8924
+ * @param {String} [host] May be a DNS name or IP address. Default '127.0.0.1'
8925
+ * @return {Object} A deferred Q promise.
8926
+ *
8927
+ * Example usage:
8928
+ *
8929
+ * var tcpPortUsed = require('tcp-port-used');
8930
+ * tcpPortUsed.check(22, '127.0.0.1')
8931
+ * .then(function(inUse) {
8932
+ * debug('Port 22 usage: '+inUse);
8933
+ * }, function(err) {
8934
+ * console.error('Error on check: '+util.inspect(err));
8935
+ * });
8936
+ */
8937
+ function check(port, host) {
8938
+ var deferred = getDeferred();
8939
+ var inUse = true;
8940
+ var client;
8941
+ var opts;
8942
+ if (!is.obj(port)) opts = makeOptionsObj(port, host);
8943
+ else opts = port;
8944
+ if (!is.port(opts.port)) {
8945
+ debug("Error invalid port: " + util.inspect(opts.port));
8946
+ deferred.reject(/* @__PURE__ */ new Error("invalid port: " + util.inspect(opts.port)));
8947
+ return deferred.promise;
8948
+ }
8949
+ if (is.nullOrUndefined(opts.host)) {
8950
+ debug("set host address to default 127.0.0.1");
8951
+ opts.host = "127.0.0.1";
8952
+ }
8953
+ function cleanUp() {
8954
+ if (client) {
8955
+ client.removeAllListeners("connect");
8956
+ client.removeAllListeners("error");
8957
+ client.end();
8958
+ client.destroy();
8959
+ client.unref();
8960
+ }
8961
+ }
8962
+ function onConnectCb() {
8963
+ deferred.resolve(inUse);
8964
+ cleanUp();
8965
+ }
8966
+ function onErrorCb(err) {
8967
+ if (err.code !== "ECONNREFUSED") deferred.reject(err);
8968
+ else {
8969
+ inUse = false;
8970
+ deferred.resolve(inUse);
8971
+ }
8972
+ cleanUp();
8973
+ }
8974
+ client = new net.Socket();
8975
+ client.once("connect", onConnectCb);
8976
+ client.once("error", onErrorCb);
8977
+ client.connect({
8978
+ port: opts.port,
8979
+ host: opts.host
8980
+ }, function() {});
8981
+ return deferred.promise;
8982
+ }
8983
+ })))(), 1);
8984
+ function _mergeRouterConfigs(existingConfig, newConfig) {
8985
+ if (!existingConfig?.Routers) return newConfig;
8986
+ const existingRoutersByEndpoint = /* @__PURE__ */ new Map();
8987
+ Object.entries(existingConfig.Routers).forEach(([routerName, router]) => {
8988
+ if (router.Parameters?.Endpoint) existingRoutersByEndpoint.set(router.Parameters.Endpoint, {
8989
+ routerName,
8990
+ router
8991
+ });
8992
+ });
8993
+ const mergedRouters = { ...newConfig.Routers };
8994
+ Object.entries(newConfig.Routers).forEach(([newRouterName, newRouter]) => {
8995
+ if (newRouter.Parameters?.Endpoint) {
8996
+ const existing = existingRoutersByEndpoint.get(newRouter.Parameters.Endpoint);
8997
+ if (existing) mergedRouters[newRouterName] = {
8998
+ ...existing.router,
8999
+ ...newRouter,
9000
+ Parameters: {
9001
+ ...existing.router.Parameters,
9002
+ ...newRouter.Parameters
9003
+ }
9004
+ };
9005
+ }
9006
+ });
9007
+ return {
9008
+ ...newConfig,
9009
+ Routers: mergedRouters
9010
+ };
9011
+ }
9012
+ async function _setProvideDhtSweepEnabledOnKuboNode(kuboClient, sweepEnabled) {
9013
+ const log = logger_default("pkc-js:pkc:_init:retrySettingHttpRoutersOnIpfsNodes:setProvideDhtSweepEnabledOnIpfsNode");
9014
+ const configKey = "Provide.DHT.SweepEnabled";
9015
+ const url = `${kuboClient._clientOptions.url}/config?arg=${configKey}&arg=${JSON.stringify(sweepEnabled)}&json=true`;
9016
+ try {
9017
+ await fetch(url, {
9018
+ method: "POST",
9019
+ headers: kuboClient._clientOptions.headers
9020
+ });
9021
+ } catch (e) {
9022
+ const error = new PKCError("ERR_FAILED_TO_SET_CONFIG_ON_KUBO_NODE", {
9023
+ fullUrl: url,
9024
+ actualError: e,
9025
+ kuboEndpoint: kuboClient._clientOptions.url,
9026
+ configKey,
9027
+ configValueToBeSet: sweepEnabled
9028
+ });
9029
+ log.error(e);
9030
+ throw error;
9031
+ }
9032
+ log.trace("Succeeded in setting config key", configKey, "on node", kuboClient._clientOptions.url, "to be", sweepEnabled);
9033
+ }
9034
+ async function _setHttpRouterOptionsOnKuboNode(kuboClient, routingValue) {
9035
+ const log = logger_default("pkc-js:pkc:_init:retrySettingHttpRoutersOnIpfsNodes:setHttpRouterOptionsOnIpfsNode");
9036
+ const routingKey = "Routing";
9037
+ let routingConfigBeforeChanging;
9038
+ try {
9039
+ routingConfigBeforeChanging = await kuboClient._client.config.get(routingKey);
9040
+ } catch (e) {
9041
+ const error = new PKCError("ERR_FAILED_TO_GET_CONFIG_ON_KUBO_NODE", {
9042
+ actualError: e,
9043
+ kuboEndpoint: kuboClient._clientOptions.url,
9044
+ configKey: routingKey
9045
+ });
9046
+ log.error(e);
9047
+ throw error;
9048
+ }
9049
+ const mergedRoutingValue = _mergeRouterConfigs(routingConfigBeforeChanging, routingValue);
9050
+ const url = `${kuboClient._clientOptions.url}/config?arg=${routingKey}&arg=${JSON.stringify(mergedRoutingValue)}&json=true`;
9051
+ try {
9052
+ await fetch(url, {
9053
+ method: "POST",
9054
+ headers: kuboClient._clientOptions.headers
9055
+ });
9056
+ } catch (e) {
9057
+ const error = new PKCError("ERR_FAILED_TO_SET_CONFIG_ON_KUBO_NODE", {
9058
+ fullUrl: url,
9059
+ actualError: e,
9060
+ kuboEndpoint: kuboClient._clientOptions.url,
9061
+ configKey: routingKey,
9062
+ configValueToBeSet: mergedRoutingValue
9063
+ });
9064
+ log.error(e);
9065
+ throw error;
9066
+ }
9067
+ log.trace("Succeeded in setting config key", routingKey, "on node", kuboClient._clientOptions.url, "to be", mergedRoutingValue);
9068
+ await _setProvideDhtSweepEnabledOnKuboNode(kuboClient, false);
9069
+ const endpointsBefore = Object.values(routingConfigBeforeChanging?.Routers || {}).map((router) => router.Parameters?.Endpoint).filter((endpoint) => endpoint !== void 0);
9070
+ const endpointsAfter = Object.values(mergedRoutingValue.Routers).map((router) => router.Parameters?.Endpoint).filter((endpoint) => endpoint !== void 0);
9071
+ if (!import_commonjs.isDeepEqual(endpointsBefore.sort(), endpointsAfter.sort())) {
9072
+ log("Config on kubo node has been changed. PKC-js will send shutdown command to node", kuboClient._clientOptions.url, "Clients of pkc-js should restart ipfs node");
9073
+ const shutdownUrl = `${kuboClient._clientOptions.url}/shutdown`;
9074
+ try {
9075
+ await fetch(shutdownUrl, {
9076
+ method: "POST",
9077
+ headers: kuboClient._clientOptions.headers
9078
+ });
9079
+ } catch (e) {
9080
+ const error = new PKCError("ERR_FAILED_TO_SHUTDOWN_KUBO_NODE", {
9081
+ actualError: e,
9082
+ kuboEndpoint: kuboClient._clientOptions.url,
9083
+ shutdownUrl
9084
+ });
9085
+ log.error(e);
9086
+ throw error;
9087
+ }
9088
+ }
9089
+ }
9090
+ async function _getStartedProxyUrl(pkc, httpRouterUrl) {
9091
+ if (pkc.destroyed) return void 0;
9092
+ const mappingKeyName = `httprouter_proxy_${httpRouterUrl}`;
9093
+ try {
9094
+ const urlOfProxyOfHttpRouter = await pkc._storage.getItem(mappingKeyName);
9095
+ if (pkc.destroyed) return void 0;
9096
+ if (urlOfProxyOfHttpRouter) {
9097
+ const proxyHttpUrl = new URL(urlOfProxyOfHttpRouter);
9098
+ if (await import_tcp_port_used.check(Number(proxyHttpUrl.port), "127.0.0.1")) return urlOfProxyOfHttpRouter;
9099
+ if (pkc.destroyed) return void 0;
9100
+ await pkc._storage.removeItem(mappingKeyName);
9101
+ }
9102
+ return;
9103
+ } catch (error) {
9104
+ if (pkc.destroyed && error instanceof Error && error.message.includes("database connection is not open")) return;
9105
+ throw error;
9106
+ }
9107
+ }
9108
+ async function setupKuboAddressesRewriterAndHttpRouters(pkc) {
9109
+ if (pkc.destroyed) return { destroy: async () => {} };
9110
+ if (!Array.isArray(pkc.kuboRpcClientsOptions) || pkc.kuboRpcClientsOptions.length <= 0) throw Error("need ipfs http client to be defined");
9111
+ if (!Array.isArray(pkc.httpRoutersOptions) || pkc.httpRoutersOptions.length <= 0) throw Error("Need http router options to defined");
9112
+ logger_default("pkc-js:node:setupKuboAddressesRewriterAndHttpRouters");
9113
+ const httpRouterProxyUrls = [];
9114
+ const proxyServers = [];
9115
+ let addressesRewriterStartPort = 19575;
9116
+ for (const httpRouter of pkc.httpRoutersOptions) {
9117
+ if (pkc.destroyed) break;
9118
+ const startedProxyUrl = await _getStartedProxyUrl(pkc, httpRouter);
9119
+ if (startedProxyUrl) {
9120
+ httpRouterProxyUrls.push(startedProxyUrl);
9121
+ continue;
9122
+ }
9123
+ let port = addressesRewriterStartPort;
9124
+ const hostname = "127.0.0.1";
9125
+ while (await import_tcp_port_used.check(port, hostname)) port++;
9126
+ const addressesRewriterProxyServer = new AddressesRewriterProxyServer({
9127
+ kuboClients: Object.values(pkc.clients.kuboRpcClients).map((kubo) => kubo._client),
9128
+ port,
9129
+ hostname,
9130
+ proxyTargetUrl: httpRouter,
9131
+ pkc
9132
+ });
9133
+ await addressesRewriterProxyServer.listen();
9134
+ if (pkc.destroyed) {
9135
+ await addressesRewriterProxyServer.destroy();
9136
+ break;
9137
+ }
9138
+ proxyServers.push(addressesRewriterProxyServer);
9139
+ const httpRouterProxyUrl = `http://${hostname}:${port}`;
9140
+ httpRouterProxyUrls.push(httpRouterProxyUrl);
9141
+ }
9142
+ httpRouterProxyUrls.sort();
9143
+ const kuboClients = pkc.clients.kuboRpcClients;
9144
+ const parallelRouters = [];
9145
+ const httpRoutersConfig = {
9146
+ HttpRoutersParallel: {
9147
+ Type: "parallel",
9148
+ Parameters: { Routers: parallelRouters }
9149
+ },
9150
+ HttpRouterNotSupported: {
9151
+ Type: "http",
9152
+ Parameters: { Endpoint: "http://kubohttprouternotsupported" }
9153
+ }
9154
+ };
9155
+ for (const [i, httpRouterUrl] of httpRouterProxyUrls.entries()) {
9156
+ const RouterName = `HttpRouter${i + 1}`;
9157
+ httpRoutersConfig[RouterName] = {
9158
+ Type: "http",
9159
+ Parameters: { Endpoint: httpRouterUrl }
9160
+ };
9161
+ parallelRouters[i] = {
9162
+ RouterName,
9163
+ IgnoreErrors: true,
9164
+ Timeout: "10s"
9165
+ };
9166
+ }
9167
+ const routingValue = {
9168
+ Type: "custom",
9169
+ Methods: {
9170
+ "find-providers": { RouterName: "HttpRoutersParallel" },
9171
+ provide: { RouterName: "HttpRoutersParallel" },
9172
+ "find-peers": { RouterName: "HttpRouterNotSupported" },
9173
+ "get-ipns": { RouterName: "HttpRouterNotSupported" },
9174
+ "put-ipns": { RouterName: "HttpRouterNotSupported" }
9175
+ },
9176
+ Routers: httpRoutersConfig
9177
+ };
9178
+ const settingOptionRetryOption = import_retry.operation({
9179
+ forever: true,
9180
+ factor: 2,
9181
+ maxTimeout: 60 * 1e3
9182
+ });
9183
+ await new Promise((resolve) => {
9184
+ settingOptionRetryOption.attempt(async (curAttempt) => {
9185
+ for (const kuboClient of Object.values(kuboClients)) try {
9186
+ await _setHttpRouterOptionsOnKuboNode(kuboClient, routingValue);
9187
+ } catch (e) {
9188
+ settingOptionRetryOption.retry(e);
9189
+ return;
9190
+ }
9191
+ resolve(1);
9192
+ });
9193
+ });
9194
+ settingOptionRetryOption.stop();
9195
+ return { destroy: async () => {
9196
+ for (const proxyServer of proxyServers) await proxyServer.destroy();
9197
+ } };
9198
+ }
9199
+ //#endregion
9200
+ //#region dist/node/publications/community-edit/community-edit.js
9201
+ var CommunityEdit = class extends Publication {
9202
+ constructor(pkc) {
9203
+ super(pkc);
9204
+ this.raw = {};
9205
+ this.publish = this.publish.bind(this);
9206
+ hideClassPrivateProps(this);
9207
+ }
9208
+ _initUnsignedLocalProps(opts) {
9209
+ super._initUnsignedLocalProps(opts);
9210
+ const o = opts.unsignedOptions;
9211
+ this.communityEdit = o.communityEdit;
9212
+ }
9213
+ _initLocalProps(props) {
9214
+ this._initRemoteProps(props.communityEdit);
9215
+ this.challengeRequest = props.challengeRequest;
9216
+ this.signer = props.signer;
9217
+ }
9218
+ async _signPublicationOptionsToPublish(cleanedPublication) {
9219
+ return signCommunityEdit({
9220
+ communityEdit: cleanedPublication,
9221
+ pkc: this._pkc
9222
+ });
9223
+ }
9224
+ _initRemoteProps(props) {
9225
+ super._initBaseRemoteProps(props);
9226
+ this.communityEdit = props.communityEdit;
9227
+ this.raw.pubsubMessageToPublish = props;
9228
+ }
9229
+ getType() {
9230
+ return "communityEdit";
6668
9231
  }
6669
9232
  async _validateSignatureHook() {
6670
9233
  const signatureValidity = await verifyCommunityEdit({
@@ -6804,7 +9367,7 @@ var PKC$1 = class extends PKCTypedEmitter {
6804
9367
  this.clients.libp2pJsClients = {};
6805
9368
  if (!this.libp2pJsClientsOptions) return;
6806
9369
  if (!this.httpRoutersOptions) throw Error("httpRoutersOptions is required for libp2pJsClient");
6807
- const { createLibp2pJsClientOrUseExistingOne } = await import("./helia-for-pkc-BZ6rZnW_.js");
9370
+ const { createLibp2pJsClientOrUseExistingOne } = await import("./helia-for-pkc-CUP6OHZK.js");
6808
9371
  for (const clientOptions of this.libp2pJsClientsOptions) {
6809
9372
  const heliaNode = await createLibp2pJsClientOrUseExistingOne({
6810
9373
  ...clientOptions,
@@ -6827,15 +9390,19 @@ var PKC$1 = class extends PKCTypedEmitter {
6827
9390
  const log = logger_default("pkc-js:pkc:_initHttpRoutersWithIpfsInBackground");
6828
9391
  if (this.destroyed) return;
6829
9392
  if (this.httpRoutersOptions?.length && this.kuboRpcClientsOptions?.length && this._canCreateNewLocalCommunity()) {
6830
- const setupPromise = setupKuboHttpRouters(this).then(() => {
6831
- if (this.destroyed) return;
6832
- log("Set http router options successfully on all connected ipfs", Object.keys(this.clients.kuboRpcClients));
9393
+ const setupPromise = setupKuboAddressesRewriterAndHttpRouters(this).then(async (addressesRewriterProxyServer) => {
9394
+ if (this.destroyed) {
9395
+ await addressesRewriterProxyServer.destroy();
9396
+ return;
9397
+ }
9398
+ log("Set http router options and their proxies successfully on all connected ipfs", Object.keys(this.clients.kuboRpcClients));
9399
+ this._addressRewriterDestroy = addressesRewriterProxyServer.destroy;
6833
9400
  }).catch((e) => {
6834
9401
  if (this.destroyed) return;
6835
- log.error("Failed to set http router options on ipfs nodes due to error", e);
9402
+ log.error("Failed to set http router options and their proxies on ipfs nodes due to error", e);
6836
9403
  this.emit("error", e);
6837
9404
  });
6838
- this._httpRouterSetupPromise = setupPromise;
9405
+ this._addressRewriterSetupPromise = setupPromise;
6839
9406
  }
6840
9407
  }
6841
9408
  async _init() {
@@ -7043,7 +9610,7 @@ var PKC$1 = class extends PKCTypedEmitter {
7043
9610
  const log = logger_default("pkc-js:pkc:createLocalCommunity");
7044
9611
  log.trace("Received community options to create a local community instance:", options);
7045
9612
  if (!this._canCreateNewLocalCommunity()) throw new PKCError("ERR_CAN_NOT_CREATE_A_LOCAL_COMMUNITY", { pkcOptions: this._userPKCOptions });
7046
- const { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb } = await import("./local-community-CPvHllf9.js");
9613
+ const { LocalCommunity, createNewLocalCommunityDb, updateInstancePropsWithStartedCommunityOrDb } = await import("./local-community-CvqLy6Ae.js");
7047
9614
  const isLocalCommunity = (await listCommunitiesSync(this)).includes(options.address);
7048
9615
  const community = new LocalCommunity(this);
7049
9616
  if (isLocalCommunity) {
@@ -7401,9 +9968,13 @@ var PKC$1 = class extends PKCTypedEmitter {
7401
9968
  for (const community of listUpdatingCommunities(this)) await community.stop();
7402
9969
  await Promise.all(listStartedCommunities(this).map((community) => community.stop()));
7403
9970
  if (this._communityFsWatchAbort) this._communityFsWatchAbort.abort();
7404
- if (this._httpRouterSetupPromise) {
7405
- await this._httpRouterSetupPromise;
7406
- this._httpRouterSetupPromise = void 0;
9971
+ if (this._addressRewriterSetupPromise) {
9972
+ await this._addressRewriterSetupPromise;
9973
+ this._addressRewriterSetupPromise = void 0;
9974
+ }
9975
+ if (this._addressRewriterDestroy) {
9976
+ await this._addressRewriterDestroy();
9977
+ this._addressRewriterDestroy = void 0;
7407
9978
  }
7408
9979
  await this._storage.destroy();
7409
9980
  for (const storage of Object.values(this._storageLRUs)) await storage.destroy();